xref: /openbmc/qemu/block.c (revision e855e4fb7b97f7f605e1f44427b98022e39e6f8f)
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;
338b338082bSbellard 
339f2d953ecSKevin Wolf     if (bdrv_find(device_name)) {
340f2d953ecSKevin Wolf         error_setg(errp, "Device with id '%s' already exists",
341f2d953ecSKevin Wolf                    device_name);
342f2d953ecSKevin Wolf         return NULL;
343f2d953ecSKevin Wolf     }
344f2d953ecSKevin Wolf     if (bdrv_find_node(device_name)) {
345f2d953ecSKevin Wolf         error_setg(errp, "Device with node-name '%s' already exists",
346f2d953ecSKevin Wolf                    device_name);
347f2d953ecSKevin Wolf         return NULL;
348f2d953ecSKevin Wolf     }
349f2d953ecSKevin Wolf 
3507267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
351e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
352b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
353ea2384d3Sbellard     if (device_name[0] != '\0') {
354dc364f4cSBenoît Canet         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
355ea2384d3Sbellard     }
35628a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
357d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
358d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
359cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
360cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3619fcb0251SFam Zheng     bs->refcnt = 1;
362d7d512f6SPaolo Bonzini 
363b338082bSbellard     return bs;
364b338082bSbellard }
365b338082bSbellard 
366d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
367d7d512f6SPaolo Bonzini {
368d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
369d7d512f6SPaolo Bonzini }
370d7d512f6SPaolo Bonzini 
371ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
372ea2384d3Sbellard {
373ea2384d3Sbellard     BlockDriver *drv1;
3748a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3758a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
376ea2384d3Sbellard             return drv1;
377ea2384d3Sbellard         }
3788a22f02aSStefan Hajnoczi     }
379ea2384d3Sbellard     return NULL;
380ea2384d3Sbellard }
381ea2384d3Sbellard 
382b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
383eb852011SMarkus Armbruster {
384b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
385b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
386b64ec4e4SFam Zheng     };
387b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
388b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
389eb852011SMarkus Armbruster     };
390eb852011SMarkus Armbruster     const char **p;
391eb852011SMarkus Armbruster 
392b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
393eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
394b64ec4e4SFam Zheng     }
395eb852011SMarkus Armbruster 
396b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
397eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
398eb852011SMarkus Armbruster             return 1;
399eb852011SMarkus Armbruster         }
400eb852011SMarkus Armbruster     }
401b64ec4e4SFam Zheng     if (read_only) {
402b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
403b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
404b64ec4e4SFam Zheng                 return 1;
405b64ec4e4SFam Zheng             }
406b64ec4e4SFam Zheng         }
407b64ec4e4SFam Zheng     }
408eb852011SMarkus Armbruster     return 0;
409eb852011SMarkus Armbruster }
410eb852011SMarkus Armbruster 
411b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
412b64ec4e4SFam Zheng                                           bool read_only)
413eb852011SMarkus Armbruster {
414eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
415b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
416eb852011SMarkus Armbruster }
417eb852011SMarkus Armbruster 
4185b7e1542SZhi Yong Wu typedef struct CreateCo {
4195b7e1542SZhi Yong Wu     BlockDriver *drv;
4205b7e1542SZhi Yong Wu     char *filename;
4215b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
4225b7e1542SZhi Yong Wu     int ret;
423cc84d90fSMax Reitz     Error *err;
4245b7e1542SZhi Yong Wu } CreateCo;
4255b7e1542SZhi Yong Wu 
4265b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4275b7e1542SZhi Yong Wu {
428cc84d90fSMax Reitz     Error *local_err = NULL;
429cc84d90fSMax Reitz     int ret;
430cc84d90fSMax Reitz 
4315b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4325b7e1542SZhi Yong Wu     assert(cco->drv);
4335b7e1542SZhi Yong Wu 
434cc84d90fSMax Reitz     ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
43584d18f06SMarkus Armbruster     if (local_err) {
436cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
437cc84d90fSMax Reitz     }
438cc84d90fSMax Reitz     cco->ret = ret;
4395b7e1542SZhi Yong Wu }
4405b7e1542SZhi Yong Wu 
4410e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
442cc84d90fSMax Reitz     QEMUOptionParameter *options, Error **errp)
443ea2384d3Sbellard {
4445b7e1542SZhi Yong Wu     int ret;
4450e7e1989SKevin Wolf 
4465b7e1542SZhi Yong Wu     Coroutine *co;
4475b7e1542SZhi Yong Wu     CreateCo cco = {
4485b7e1542SZhi Yong Wu         .drv = drv,
4495b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
4505b7e1542SZhi Yong Wu         .options = options,
4515b7e1542SZhi Yong Wu         .ret = NOT_DONE,
452cc84d90fSMax Reitz         .err = NULL,
4535b7e1542SZhi Yong Wu     };
4545b7e1542SZhi Yong Wu 
4555b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
456cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
45780168bffSLuiz Capitulino         ret = -ENOTSUP;
45880168bffSLuiz Capitulino         goto out;
4595b7e1542SZhi Yong Wu     }
4605b7e1542SZhi Yong Wu 
4615b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4625b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4635b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4645b7e1542SZhi Yong Wu     } else {
4655b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4665b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4675b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4685b7e1542SZhi Yong Wu             qemu_aio_wait();
4695b7e1542SZhi Yong Wu         }
4705b7e1542SZhi Yong Wu     }
4715b7e1542SZhi Yong Wu 
4725b7e1542SZhi Yong Wu     ret = cco.ret;
473cc84d90fSMax Reitz     if (ret < 0) {
47484d18f06SMarkus Armbruster         if (cco.err) {
475cc84d90fSMax Reitz             error_propagate(errp, cco.err);
476cc84d90fSMax Reitz         } else {
477cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
478cc84d90fSMax Reitz         }
479cc84d90fSMax Reitz     }
4805b7e1542SZhi Yong Wu 
48180168bffSLuiz Capitulino out:
48280168bffSLuiz Capitulino     g_free(cco.filename);
4835b7e1542SZhi Yong Wu     return ret;
484ea2384d3Sbellard }
485ea2384d3Sbellard 
486cc84d90fSMax Reitz int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
487cc84d90fSMax Reitz                      Error **errp)
48884a12e66SChristoph Hellwig {
48984a12e66SChristoph Hellwig     BlockDriver *drv;
490cc84d90fSMax Reitz     Error *local_err = NULL;
491cc84d90fSMax Reitz     int ret;
49284a12e66SChristoph Hellwig 
49398289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
49484a12e66SChristoph Hellwig     if (drv == NULL) {
495cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
49616905d71SStefan Hajnoczi         return -ENOENT;
49784a12e66SChristoph Hellwig     }
49884a12e66SChristoph Hellwig 
499cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, options, &local_err);
50084d18f06SMarkus Armbruster     if (local_err) {
501cc84d90fSMax Reitz         error_propagate(errp, local_err);
502cc84d90fSMax Reitz     }
503cc84d90fSMax Reitz     return ret;
50484a12e66SChristoph Hellwig }
50584a12e66SChristoph Hellwig 
506355ef4acSKevin Wolf int bdrv_refresh_limits(BlockDriverState *bs)
507d34682cdSKevin Wolf {
508d34682cdSKevin Wolf     BlockDriver *drv = bs->drv;
509d34682cdSKevin Wolf 
510d34682cdSKevin Wolf     memset(&bs->bl, 0, sizeof(bs->bl));
511d34682cdSKevin Wolf 
512466ad822SKevin Wolf     if (!drv) {
513466ad822SKevin Wolf         return 0;
514466ad822SKevin Wolf     }
515466ad822SKevin Wolf 
516466ad822SKevin Wolf     /* Take some limits from the children as a default */
517466ad822SKevin Wolf     if (bs->file) {
518466ad822SKevin Wolf         bdrv_refresh_limits(bs->file);
519466ad822SKevin Wolf         bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
520339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
521339064d5SKevin Wolf     } else {
522339064d5SKevin Wolf         bs->bl.opt_mem_alignment = 512;
523466ad822SKevin Wolf     }
524466ad822SKevin Wolf 
525466ad822SKevin Wolf     if (bs->backing_hd) {
526466ad822SKevin Wolf         bdrv_refresh_limits(bs->backing_hd);
527466ad822SKevin Wolf         bs->bl.opt_transfer_length =
528466ad822SKevin Wolf             MAX(bs->bl.opt_transfer_length,
529466ad822SKevin Wolf                 bs->backing_hd->bl.opt_transfer_length);
530339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
531339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
532339064d5SKevin Wolf                 bs->backing_hd->bl.opt_mem_alignment);
533466ad822SKevin Wolf     }
534466ad822SKevin Wolf 
535466ad822SKevin Wolf     /* Then let the driver override it */
536466ad822SKevin Wolf     if (drv->bdrv_refresh_limits) {
537d34682cdSKevin Wolf         return drv->bdrv_refresh_limits(bs);
538d34682cdSKevin Wolf     }
539d34682cdSKevin Wolf 
540d34682cdSKevin Wolf     return 0;
541d34682cdSKevin Wolf }
542d34682cdSKevin Wolf 
543eba25057SJim Meyering /*
544eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
545eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
546eba25057SJim Meyering  */
547eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
548eba25057SJim Meyering {
549d5249393Sbellard #ifdef _WIN32
5503b9f94e1Sbellard     char temp_dir[MAX_PATH];
551eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
552eba25057SJim Meyering        have length MAX_PATH or greater.  */
553eba25057SJim Meyering     assert(size >= MAX_PATH);
554eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
555eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
556eba25057SJim Meyering             ? 0 : -GetLastError());
557d5249393Sbellard #else
558ea2384d3Sbellard     int fd;
5597ccfb2ebSblueswir1     const char *tmpdir;
5600badc1eeSaurel32     tmpdir = getenv("TMPDIR");
56169bef793SAmit Shah     if (!tmpdir) {
56269bef793SAmit Shah         tmpdir = "/var/tmp";
56369bef793SAmit Shah     }
564eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
565eba25057SJim Meyering         return -EOVERFLOW;
566ea2384d3Sbellard     }
567eba25057SJim Meyering     fd = mkstemp(filename);
568fe235a06SDunrong Huang     if (fd < 0) {
569fe235a06SDunrong Huang         return -errno;
570fe235a06SDunrong Huang     }
571fe235a06SDunrong Huang     if (close(fd) != 0) {
572fe235a06SDunrong Huang         unlink(filename);
573eba25057SJim Meyering         return -errno;
574eba25057SJim Meyering     }
575eba25057SJim Meyering     return 0;
576d5249393Sbellard #endif
577eba25057SJim Meyering }
578ea2384d3Sbellard 
579f3a5d3f8SChristoph Hellwig /*
580f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
581f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
582f3a5d3f8SChristoph Hellwig  */
583f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
584f3a5d3f8SChristoph Hellwig {
585508c7cb3SChristoph Hellwig     int score_max = 0, score;
586508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
587f3a5d3f8SChristoph Hellwig 
5888a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
589508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
590508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
591508c7cb3SChristoph Hellwig             if (score > score_max) {
592508c7cb3SChristoph Hellwig                 score_max = score;
593508c7cb3SChristoph Hellwig                 drv = d;
594f3a5d3f8SChristoph Hellwig             }
595508c7cb3SChristoph Hellwig         }
596f3a5d3f8SChristoph Hellwig     }
597f3a5d3f8SChristoph Hellwig 
598508c7cb3SChristoph Hellwig     return drv;
599f3a5d3f8SChristoph Hellwig }
600f3a5d3f8SChristoph Hellwig 
60198289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
60298289620SKevin Wolf                                 bool allow_protocol_prefix)
60384a12e66SChristoph Hellwig {
60484a12e66SChristoph Hellwig     BlockDriver *drv1;
60584a12e66SChristoph Hellwig     char protocol[128];
60684a12e66SChristoph Hellwig     int len;
60784a12e66SChristoph Hellwig     const char *p;
60884a12e66SChristoph Hellwig 
60966f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
61066f82ceeSKevin Wolf 
61139508e7aSChristoph Hellwig     /*
61239508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
61339508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
61439508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
61539508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
61639508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
61739508e7aSChristoph Hellwig      */
61884a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
61939508e7aSChristoph Hellwig     if (drv1) {
62084a12e66SChristoph Hellwig         return drv1;
62184a12e66SChristoph Hellwig     }
62239508e7aSChristoph Hellwig 
62398289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
62439508e7aSChristoph Hellwig         return bdrv_find_format("file");
62539508e7aSChristoph Hellwig     }
62698289620SKevin Wolf 
6279e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
6289e0b22f4SStefan Hajnoczi     assert(p != NULL);
62984a12e66SChristoph Hellwig     len = p - filename;
63084a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
63184a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
63284a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
63384a12e66SChristoph Hellwig     protocol[len] = '\0';
63484a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
63584a12e66SChristoph Hellwig         if (drv1->protocol_name &&
63684a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
63784a12e66SChristoph Hellwig             return drv1;
63884a12e66SChristoph Hellwig         }
63984a12e66SChristoph Hellwig     }
64084a12e66SChristoph Hellwig     return NULL;
64184a12e66SChristoph Hellwig }
64284a12e66SChristoph Hellwig 
643f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
64434b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
645ea2384d3Sbellard {
646f500a6d3SKevin Wolf     int score, score_max;
647ea2384d3Sbellard     BlockDriver *drv1, *drv;
64883f64091Sbellard     uint8_t buf[2048];
649f500a6d3SKevin Wolf     int ret = 0;
650f8ea0b00SNicholas Bellinger 
65108a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
6528e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
653c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
654c98ac35dSStefan Weil         if (!drv) {
65534b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
656c98ac35dSStefan Weil             ret = -ENOENT;
657c98ac35dSStefan Weil         }
658c98ac35dSStefan Weil         *pdrv = drv;
659c98ac35dSStefan Weil         return ret;
6601a396859SNicholas A. Bellinger     }
661f8ea0b00SNicholas Bellinger 
66283f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
663ea2384d3Sbellard     if (ret < 0) {
66434b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
66534b5d2c6SMax Reitz                          "format");
666c98ac35dSStefan Weil         *pdrv = NULL;
667c98ac35dSStefan Weil         return ret;
668ea2384d3Sbellard     }
669ea2384d3Sbellard 
670ea2384d3Sbellard     score_max = 0;
67184a12e66SChristoph Hellwig     drv = NULL;
6728a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
67383f64091Sbellard         if (drv1->bdrv_probe) {
674ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
675ea2384d3Sbellard             if (score > score_max) {
676ea2384d3Sbellard                 score_max = score;
677ea2384d3Sbellard                 drv = drv1;
678ea2384d3Sbellard             }
679ea2384d3Sbellard         }
68083f64091Sbellard     }
681c98ac35dSStefan Weil     if (!drv) {
68234b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
68334b5d2c6SMax Reitz                    "driver found");
684c98ac35dSStefan Weil         ret = -ENOENT;
685c98ac35dSStefan Weil     }
686c98ac35dSStefan Weil     *pdrv = drv;
687c98ac35dSStefan Weil     return ret;
688ea2384d3Sbellard }
689ea2384d3Sbellard 
69051762288SStefan Hajnoczi /**
69151762288SStefan Hajnoczi  * Set the current 'total_sectors' value
69251762288SStefan Hajnoczi  */
69351762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
69451762288SStefan Hajnoczi {
69551762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
69651762288SStefan Hajnoczi 
697396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
698396759adSNicholas Bellinger     if (bs->sg)
699396759adSNicholas Bellinger         return 0;
700396759adSNicholas Bellinger 
70151762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
70251762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
70351762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
70451762288SStefan Hajnoczi         if (length < 0) {
70551762288SStefan Hajnoczi             return length;
70651762288SStefan Hajnoczi         }
7077e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
70851762288SStefan Hajnoczi     }
70951762288SStefan Hajnoczi 
71051762288SStefan Hajnoczi     bs->total_sectors = hint;
71151762288SStefan Hajnoczi     return 0;
71251762288SStefan Hajnoczi }
71351762288SStefan Hajnoczi 
714c3993cdcSStefan Hajnoczi /**
7159e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
7169e8f1835SPaolo Bonzini  *
7179e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
7189e8f1835SPaolo Bonzini  */
7199e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
7209e8f1835SPaolo Bonzini {
7219e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
7229e8f1835SPaolo Bonzini 
7239e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
7249e8f1835SPaolo Bonzini         /* do nothing */
7259e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
7269e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
7279e8f1835SPaolo Bonzini     } else {
7289e8f1835SPaolo Bonzini         return -1;
7299e8f1835SPaolo Bonzini     }
7309e8f1835SPaolo Bonzini 
7319e8f1835SPaolo Bonzini     return 0;
7329e8f1835SPaolo Bonzini }
7339e8f1835SPaolo Bonzini 
7349e8f1835SPaolo Bonzini /**
735c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
736c3993cdcSStefan Hajnoczi  *
737c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
738c3993cdcSStefan Hajnoczi  */
739c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
740c3993cdcSStefan Hajnoczi {
741c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
742c3993cdcSStefan Hajnoczi 
743c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
744c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
74592196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
74692196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
747c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
748c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
749c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
750c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
751c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
752c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
753c3993cdcSStefan Hajnoczi         /* this is the default */
754c3993cdcSStefan Hajnoczi     } else {
755c3993cdcSStefan Hajnoczi         return -1;
756c3993cdcSStefan Hajnoczi     }
757c3993cdcSStefan Hajnoczi 
758c3993cdcSStefan Hajnoczi     return 0;
759c3993cdcSStefan Hajnoczi }
760c3993cdcSStefan Hajnoczi 
76153fec9d3SStefan Hajnoczi /**
76253fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
76353fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
76453fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
76553fec9d3SStefan Hajnoczi  */
76653fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
76753fec9d3SStefan Hajnoczi {
76853fec9d3SStefan Hajnoczi     bs->copy_on_read++;
76953fec9d3SStefan Hajnoczi }
77053fec9d3SStefan Hajnoczi 
77153fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
77253fec9d3SStefan Hajnoczi {
77353fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
77453fec9d3SStefan Hajnoczi     bs->copy_on_read--;
77553fec9d3SStefan Hajnoczi }
77653fec9d3SStefan Hajnoczi 
7777b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7787b272452SKevin Wolf {
7797b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7807b272452SKevin Wolf 
781b998875dSKevin Wolf     /* The backing file of a temporary snapshot is read-only */
782b998875dSKevin Wolf     if (flags & BDRV_O_SNAPSHOT) {
783b998875dSKevin Wolf         open_flags &= ~BDRV_O_RDWR;
784b998875dSKevin Wolf     }
785b998875dSKevin Wolf 
7867b272452SKevin Wolf     /*
7877b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7887b272452SKevin Wolf      * image.
7897b272452SKevin Wolf      */
7907b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7917b272452SKevin Wolf 
7927b272452SKevin Wolf     /*
7937b272452SKevin Wolf      * Snapshots should be writable.
7947b272452SKevin Wolf      */
7957b272452SKevin Wolf     if (bs->is_temporary) {
7967b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7977b272452SKevin Wolf     }
7987b272452SKevin Wolf 
7997b272452SKevin Wolf     return open_flags;
8007b272452SKevin Wolf }
8017b272452SKevin Wolf 
802636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8036913c0c2SBenoît Canet                                   const char *node_name,
8046913c0c2SBenoît Canet                                   Error **errp)
8056913c0c2SBenoît Canet {
8066913c0c2SBenoît Canet     if (!node_name) {
807636ea370SKevin Wolf         return;
8086913c0c2SBenoît Canet     }
8096913c0c2SBenoît Canet 
8106913c0c2SBenoît Canet     /* empty string node name is invalid */
8116913c0c2SBenoît Canet     if (node_name[0] == '\0') {
8126913c0c2SBenoît Canet         error_setg(errp, "Empty node name");
813636ea370SKevin Wolf         return;
8146913c0c2SBenoît Canet     }
8156913c0c2SBenoît Canet 
8160c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8170c5e94eeSBenoît Canet     if (bdrv_find(node_name)) {
8180c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8190c5e94eeSBenoît Canet                    node_name);
820636ea370SKevin Wolf         return;
8210c5e94eeSBenoît Canet     }
8220c5e94eeSBenoît Canet 
8236913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8246913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8256913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
826636ea370SKevin Wolf         return;
8276913c0c2SBenoît Canet     }
8286913c0c2SBenoît Canet 
8296913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8306913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8316913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
8326913c0c2SBenoît Canet }
8336913c0c2SBenoît Canet 
834b6ce07aaSKevin Wolf /*
83557915332SKevin Wolf  * Common part for opening disk images and files
836b6ad491aSKevin Wolf  *
837b6ad491aSKevin Wolf  * Removes all processed options from *options.
83857915332SKevin Wolf  */
839f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
84034b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
84157915332SKevin Wolf {
84257915332SKevin Wolf     int ret, open_flags;
843035fccdfSKevin Wolf     const char *filename;
8446913c0c2SBenoît Canet     const char *node_name = NULL;
84534b5d2c6SMax Reitz     Error *local_err = NULL;
84657915332SKevin Wolf 
84757915332SKevin Wolf     assert(drv != NULL);
8486405875cSPaolo Bonzini     assert(bs->file == NULL);
849707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
85057915332SKevin Wolf 
85145673671SKevin Wolf     if (file != NULL) {
85245673671SKevin Wolf         filename = file->filename;
85345673671SKevin Wolf     } else {
85445673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
85545673671SKevin Wolf     }
85645673671SKevin Wolf 
857765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
858765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
859765003dbSKevin Wolf                    drv->format_name);
860765003dbSKevin Wolf         return -EINVAL;
861765003dbSKevin Wolf     }
862765003dbSKevin Wolf 
86345673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
86428dcee10SStefan Hajnoczi 
8656913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
866636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
8670fb6395cSMarkus Armbruster     if (local_err) {
868636ea370SKevin Wolf         error_propagate(errp, local_err);
869636ea370SKevin Wolf         return -EINVAL;
8706913c0c2SBenoît Canet     }
8716913c0c2SBenoît Canet     qdict_del(options, "node-name");
8726913c0c2SBenoît Canet 
8735d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
8745d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
8755d186eb0SKevin Wolf      * and return immediately. */
8765d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
8775d186eb0SKevin Wolf         bdrv_swap(file, bs);
8785d186eb0SKevin Wolf         return 0;
8795d186eb0SKevin Wolf     }
8805d186eb0SKevin Wolf 
88157915332SKevin Wolf     bs->open_flags = flags;
8821b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
883c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8840d51b4deSAsias He     bs->zero_beyond_eof = true;
885b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
886b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
887b64ec4e4SFam Zheng 
888b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8898f94a6e4SKevin Wolf         error_setg(errp,
8908f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8918f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8928f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8938f94a6e4SKevin Wolf                    drv->format_name);
894b64ec4e4SFam Zheng         return -ENOTSUP;
895b64ec4e4SFam Zheng     }
89657915332SKevin Wolf 
89753fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8980ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8990ebd24e0SKevin Wolf         if (!bs->read_only) {
90053fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9010ebd24e0SKevin Wolf         } else {
9020ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
9030ebd24e0SKevin Wolf             return -EINVAL;
9040ebd24e0SKevin Wolf         }
90553fec9d3SStefan Hajnoczi     }
90653fec9d3SStefan Hajnoczi 
907c2ad1b0cSKevin Wolf     if (filename != NULL) {
90857915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
909c2ad1b0cSKevin Wolf     } else {
910c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
911c2ad1b0cSKevin Wolf     }
91257915332SKevin Wolf 
91357915332SKevin Wolf     bs->drv = drv;
9147267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
91557915332SKevin Wolf 
91603f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
917e7c63796SStefan Hajnoczi 
91866f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
91966f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9205d186eb0SKevin Wolf         assert(file == NULL);
921030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
92234b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
923f500a6d3SKevin Wolf     } else {
9242af5ef70SKevin Wolf         if (file == NULL) {
92534b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
92634b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9272af5ef70SKevin Wolf             ret = -EINVAL;
9282af5ef70SKevin Wolf             goto free_and_fail;
9292af5ef70SKevin Wolf         }
930f500a6d3SKevin Wolf         bs->file = file;
93134b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
93266f82ceeSKevin Wolf     }
93366f82ceeSKevin Wolf 
93457915332SKevin Wolf     if (ret < 0) {
93584d18f06SMarkus Armbruster         if (local_err) {
93634b5d2c6SMax Reitz             error_propagate(errp, local_err);
9372fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9382fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
93934b5d2c6SMax Reitz         } else {
94034b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
94134b5d2c6SMax Reitz         }
94257915332SKevin Wolf         goto free_and_fail;
94357915332SKevin Wolf     }
94457915332SKevin Wolf 
94551762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
94651762288SStefan Hajnoczi     if (ret < 0) {
94734b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
94851762288SStefan Hajnoczi         goto free_and_fail;
94957915332SKevin Wolf     }
95051762288SStefan Hajnoczi 
951d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
952c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
95347ea2de2SKevin Wolf     assert((bs->request_alignment != 0) || bs->sg);
954d34682cdSKevin Wolf 
95557915332SKevin Wolf #ifndef _WIN32
95657915332SKevin Wolf     if (bs->is_temporary) {
957d4cea8dfSDunrong Huang         assert(bs->filename[0] != '\0');
958d4cea8dfSDunrong Huang         unlink(bs->filename);
95957915332SKevin Wolf     }
96057915332SKevin Wolf #endif
96157915332SKevin Wolf     return 0;
96257915332SKevin Wolf 
96357915332SKevin Wolf free_and_fail:
96466f82ceeSKevin Wolf     bs->file = NULL;
9657267c094SAnthony Liguori     g_free(bs->opaque);
96657915332SKevin Wolf     bs->opaque = NULL;
96757915332SKevin Wolf     bs->drv = NULL;
96857915332SKevin Wolf     return ret;
96957915332SKevin Wolf }
97057915332SKevin Wolf 
97157915332SKevin Wolf /*
972b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
973787e4a85SKevin Wolf  *
9745acd9d81SMax Reitz  * options is an indirect pointer to a QDict of options to pass to the block
9755acd9d81SMax Reitz  * drivers, or pointer to NULL for an empty set of options. If this function
9765acd9d81SMax Reitz  * takes ownership of the QDict reference, it will set *options to NULL;
9775acd9d81SMax Reitz  * otherwise, it will contain unused/unrecognized options after this function
9785acd9d81SMax Reitz  * returns. Then, the caller is responsible for freeing it. If it intends to
9795acd9d81SMax Reitz  * reuse the QDict, QINCREF() should be called beforehand.
980b6ce07aaSKevin Wolf  */
981d4446eaeSMax Reitz static int bdrv_file_open(BlockDriverState *bs, const char *filename,
9825acd9d81SMax Reitz                           QDict **options, int flags, Error **errp)
983b338082bSbellard {
9846db95603SChristoph Hellwig     BlockDriver *drv;
985c2ad1b0cSKevin Wolf     const char *drvname;
986e3fa4bfaSKevin Wolf     bool parse_filename = false;
98734b5d2c6SMax Reitz     Error *local_err = NULL;
98883f64091Sbellard     int ret;
9893b0d4f61Sbellard 
990035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
991035fccdfSKevin Wolf     if (!filename) {
9925acd9d81SMax Reitz         filename = qdict_get_try_str(*options, "filename");
9935acd9d81SMax Reitz     } else if (filename && !qdict_haskey(*options, "filename")) {
9945acd9d81SMax Reitz         qdict_put(*options, "filename", qstring_from_str(filename));
995e3fa4bfaSKevin Wolf         parse_filename = true;
996035fccdfSKevin Wolf     } else {
99734b5d2c6SMax Reitz         error_setg(errp, "Can't specify 'file' and 'filename' options at the "
99834b5d2c6SMax Reitz                    "same time");
999035fccdfSKevin Wolf         ret = -EINVAL;
1000035fccdfSKevin Wolf         goto fail;
1001035fccdfSKevin Wolf     }
1002035fccdfSKevin Wolf 
1003c2ad1b0cSKevin Wolf     /* Find the right block driver */
10045acd9d81SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1005c2ad1b0cSKevin Wolf     if (drvname) {
10068f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
100734b5d2c6SMax Reitz         if (!drv) {
100834b5d2c6SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
100934b5d2c6SMax Reitz         }
10105acd9d81SMax Reitz         qdict_del(*options, "driver");
1011c2ad1b0cSKevin Wolf     } else if (filename) {
1012e3fa4bfaSKevin Wolf         drv = bdrv_find_protocol(filename, parse_filename);
101398289620SKevin Wolf         if (!drv) {
101434b5d2c6SMax Reitz             error_setg(errp, "Unknown protocol");
101598289620SKevin Wolf         }
1016c2ad1b0cSKevin Wolf     } else {
101734b5d2c6SMax Reitz         error_setg(errp, "Must specify either driver or file");
1018c2ad1b0cSKevin Wolf         drv = NULL;
1019c2ad1b0cSKevin Wolf     }
1020c2ad1b0cSKevin Wolf 
1021c2ad1b0cSKevin Wolf     if (!drv) {
102234b5d2c6SMax Reitz         /* errp has been set already */
1023c2ad1b0cSKevin Wolf         ret = -ENOENT;
1024c2ad1b0cSKevin Wolf         goto fail;
1025c2ad1b0cSKevin Wolf     }
1026c2ad1b0cSKevin Wolf 
1027c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
1028e3fa4bfaSKevin Wolf     if (drv->bdrv_parse_filename && parse_filename) {
10295acd9d81SMax Reitz         drv->bdrv_parse_filename(filename, *options, &local_err);
103084d18f06SMarkus Armbruster         if (local_err) {
103134b5d2c6SMax Reitz             error_propagate(errp, local_err);
10326963a30dSKevin Wolf             ret = -EINVAL;
10336963a30dSKevin Wolf             goto fail;
10346963a30dSKevin Wolf         }
1035cd5d031eSMax Reitz 
1036cd5d031eSMax Reitz         if (!drv->bdrv_needs_filename) {
10375acd9d81SMax Reitz             qdict_del(*options, "filename");
1038cd5d031eSMax Reitz         } else {
1039cd5d031eSMax Reitz             filename = qdict_get_str(*options, "filename");
1040cd5d031eSMax Reitz         }
10416963a30dSKevin Wolf     }
10426963a30dSKevin Wolf 
1043505d7583SMax Reitz     if (!drv->bdrv_file_open) {
10445acd9d81SMax Reitz         ret = bdrv_open(&bs, filename, NULL, *options, flags, drv, &local_err);
10455acd9d81SMax Reitz         *options = NULL;
1046505d7583SMax Reitz     } else {
10475acd9d81SMax Reitz         ret = bdrv_open_common(bs, NULL, *options, flags, drv, &local_err);
1048505d7583SMax Reitz     }
1049707ff828SKevin Wolf     if (ret < 0) {
105034b5d2c6SMax Reitz         error_propagate(errp, local_err);
1051707ff828SKevin Wolf         goto fail;
1052707ff828SKevin Wolf     }
1053707ff828SKevin Wolf 
105471d0770cSaliguori     bs->growable = 1;
105583f64091Sbellard     return 0;
1056707ff828SKevin Wolf 
1057707ff828SKevin Wolf fail:
1058707ff828SKevin Wolf     return ret;
10593b0d4f61Sbellard }
10603b0d4f61Sbellard 
106131ca6d07SKevin Wolf /*
106231ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
106331ca6d07SKevin Wolf  *
106431ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
106531ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
106631ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
106731ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
106831ca6d07SKevin Wolf  */
106934b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
10709156df12SPaolo Bonzini {
10711ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
10721ba4b6a5SBenoît Canet     int back_flags, ret = 0;
10739156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
107434b5d2c6SMax Reitz     Error *local_err = NULL;
10759156df12SPaolo Bonzini 
10769156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
107731ca6d07SKevin Wolf         QDECREF(options);
10781ba4b6a5SBenoît Canet         goto free_exit;
10799156df12SPaolo Bonzini     }
10809156df12SPaolo Bonzini 
108131ca6d07SKevin Wolf     /* NULL means an empty set of options */
108231ca6d07SKevin Wolf     if (options == NULL) {
108331ca6d07SKevin Wolf         options = qdict_new();
108431ca6d07SKevin Wolf     }
108531ca6d07SKevin Wolf 
10869156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
10871cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
10881cb6f506SKevin Wolf         backing_filename[0] = '\0';
10891cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
109031ca6d07SKevin Wolf         QDECREF(options);
10911ba4b6a5SBenoît Canet         goto free_exit;
1092dbecebddSFam Zheng     } else {
10931ba4b6a5SBenoît Canet         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX);
10949156df12SPaolo Bonzini     }
10959156df12SPaolo Bonzini 
10969156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
10979156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
10989156df12SPaolo Bonzini     }
10999156df12SPaolo Bonzini 
11009156df12SPaolo Bonzini     /* backing files always opened read-only */
110187a5debdSThibaut LAURENT     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
110287a5debdSThibaut LAURENT                                     BDRV_O_COPY_ON_READ);
11039156df12SPaolo Bonzini 
1104f67503e5SMax Reitz     assert(bs->backing_hd == NULL);
1105f67503e5SMax Reitz     ret = bdrv_open(&bs->backing_hd,
1106ddf5636dSMax Reitz                     *backing_filename ? backing_filename : NULL, NULL, options,
110734b5d2c6SMax Reitz                     back_flags, back_drv, &local_err);
11089156df12SPaolo Bonzini     if (ret < 0) {
11099156df12SPaolo Bonzini         bs->backing_hd = NULL;
11109156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1111b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1112b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1113b04b6b6eSFam Zheng         error_free(local_err);
11141ba4b6a5SBenoît Canet         goto free_exit;
11159156df12SPaolo Bonzini     }
1116d80ac658SPeter Feiner 
1117d80ac658SPeter Feiner     if (bs->backing_hd->file) {
111861ed2684SMax Reitz         pstrcpy(bs->backing_file, sizeof(bs->backing_file),
111961ed2684SMax Reitz                 bs->backing_hd->file->filename);
1120d80ac658SPeter Feiner     }
1121d80ac658SPeter Feiner 
1122d34682cdSKevin Wolf     /* Recalculate the BlockLimits with the backing file */
1123d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
1124d34682cdSKevin Wolf 
11251ba4b6a5SBenoît Canet free_exit:
11261ba4b6a5SBenoît Canet     g_free(backing_filename);
11271ba4b6a5SBenoît Canet     return ret;
11289156df12SPaolo Bonzini }
11299156df12SPaolo Bonzini 
1130b6ce07aaSKevin Wolf /*
1131da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1132da557aacSMax Reitz  * device's options.
1133da557aacSMax Reitz  *
1134da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1135da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1136da557aacSMax Reitz  *
1137da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1138da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1139da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1140da557aacSMax Reitz  * BlockdevRef.
1141da557aacSMax Reitz  *
1142da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1143f67503e5SMax Reitz  *
1144f67503e5SMax Reitz  * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
1145da557aacSMax Reitz  */
1146da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1147da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1148f7d9fd8cSMax Reitz                     bool allow_none, Error **errp)
1149da557aacSMax Reitz {
1150da557aacSMax Reitz     QDict *image_options;
1151da557aacSMax Reitz     int ret;
1152da557aacSMax Reitz     char *bdref_key_dot;
1153da557aacSMax Reitz     const char *reference;
1154da557aacSMax Reitz 
1155f67503e5SMax Reitz     assert(pbs);
1156f67503e5SMax Reitz     assert(*pbs == NULL);
1157f67503e5SMax Reitz 
1158da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1159da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1160da557aacSMax Reitz     g_free(bdref_key_dot);
1161da557aacSMax Reitz 
1162da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1163da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1164da557aacSMax Reitz         if (allow_none) {
1165da557aacSMax Reitz             ret = 0;
1166da557aacSMax Reitz         } else {
1167da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1168da557aacSMax Reitz                        bdref_key);
1169da557aacSMax Reitz             ret = -EINVAL;
1170da557aacSMax Reitz         }
1171da557aacSMax Reitz         goto done;
1172da557aacSMax Reitz     }
1173da557aacSMax Reitz 
1174f7d9fd8cSMax Reitz     ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
1175da557aacSMax Reitz 
1176da557aacSMax Reitz done:
1177da557aacSMax Reitz     qdict_del(options, bdref_key);
1178da557aacSMax Reitz     return ret;
1179da557aacSMax Reitz }
1180da557aacSMax Reitz 
1181b998875dSKevin Wolf void bdrv_append_temp_snapshot(BlockDriverState *bs, Error **errp)
1182b998875dSKevin Wolf {
1183b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
11841ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1185b998875dSKevin Wolf     int64_t total_size;
1186b998875dSKevin Wolf     BlockDriver *bdrv_qcow2;
1187b998875dSKevin Wolf     QEMUOptionParameter *create_options;
1188b998875dSKevin Wolf     QDict *snapshot_options;
1189b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1190b998875dSKevin Wolf     Error *local_err;
1191b998875dSKevin Wolf     int ret;
1192b998875dSKevin Wolf 
1193b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1194b998875dSKevin Wolf        instead of opening 'filename' directly */
1195b998875dSKevin Wolf 
1196b998875dSKevin Wolf     /* Get the required size from the image */
1197f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1198f187743aSKevin Wolf     if (total_size < 0) {
1199f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
12001ba4b6a5SBenoît Canet         goto out;
1201f187743aSKevin Wolf     }
1202f187743aSKevin Wolf     total_size &= BDRV_SECTOR_MASK;
1203b998875dSKevin Wolf 
1204b998875dSKevin Wolf     /* Create the temporary image */
12051ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1206b998875dSKevin Wolf     if (ret < 0) {
1207b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
12081ba4b6a5SBenoît Canet         goto out;
1209b998875dSKevin Wolf     }
1210b998875dSKevin Wolf 
1211b998875dSKevin Wolf     bdrv_qcow2 = bdrv_find_format("qcow2");
1212b998875dSKevin Wolf     create_options = parse_option_parameters("", bdrv_qcow2->create_options,
1213b998875dSKevin Wolf                                              NULL);
1214b998875dSKevin Wolf 
1215b998875dSKevin Wolf     set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
1216b998875dSKevin Wolf 
1217b998875dSKevin Wolf     ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
1218b998875dSKevin Wolf     free_option_parameters(create_options);
1219b998875dSKevin Wolf     if (ret < 0) {
1220b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1221b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1222b998875dSKevin Wolf                          error_get_pretty(local_err));
1223b998875dSKevin Wolf         error_free(local_err);
12241ba4b6a5SBenoît Canet         goto out;
1225b998875dSKevin Wolf     }
1226b998875dSKevin Wolf 
1227b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1228b998875dSKevin Wolf     snapshot_options = qdict_new();
1229b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1230b998875dSKevin Wolf               qstring_from_str("file"));
1231b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1232b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1233b998875dSKevin Wolf 
123498522f63SKevin Wolf     bs_snapshot = bdrv_new("", &error_abort);
1235b998875dSKevin Wolf     bs_snapshot->is_temporary = 1;
1236b998875dSKevin Wolf 
1237b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
1238b998875dSKevin Wolf                     bs->open_flags & ~BDRV_O_SNAPSHOT, bdrv_qcow2, &local_err);
1239b998875dSKevin Wolf     if (ret < 0) {
1240b998875dSKevin Wolf         error_propagate(errp, local_err);
12411ba4b6a5SBenoît Canet         goto out;
1242b998875dSKevin Wolf     }
1243b998875dSKevin Wolf 
1244b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
12451ba4b6a5SBenoît Canet 
12461ba4b6a5SBenoît Canet out:
12471ba4b6a5SBenoît Canet     g_free(tmp_filename);
1248b998875dSKevin Wolf }
1249b998875dSKevin Wolf 
1250da557aacSMax Reitz /*
1251b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1252de9c0cecSKevin Wolf  *
1253de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1254de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1255de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1256de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1257f67503e5SMax Reitz  *
1258f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1259f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1260ddf5636dSMax Reitz  *
1261ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1262ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1263ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1264b6ce07aaSKevin Wolf  */
1265ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename,
1266ddf5636dSMax Reitz               const char *reference, QDict *options, int flags,
1267ddf5636dSMax Reitz               BlockDriver *drv, Error **errp)
1268ea2384d3Sbellard {
1269b6ce07aaSKevin Wolf     int ret;
1270f67503e5SMax Reitz     BlockDriverState *file = NULL, *bs;
127174fe54f2SKevin Wolf     const char *drvname;
127234b5d2c6SMax Reitz     Error *local_err = NULL;
127333e3963eSbellard 
1274f67503e5SMax Reitz     assert(pbs);
1275f67503e5SMax Reitz 
1276ddf5636dSMax Reitz     if (reference) {
1277ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1278ddf5636dSMax Reitz         QDECREF(options);
1279ddf5636dSMax Reitz 
1280ddf5636dSMax Reitz         if (*pbs) {
1281ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1282ddf5636dSMax Reitz                        "another block device");
1283ddf5636dSMax Reitz             return -EINVAL;
1284ddf5636dSMax Reitz         }
1285ddf5636dSMax Reitz 
1286ddf5636dSMax Reitz         if (filename || options_non_empty) {
1287ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1288ddf5636dSMax Reitz                        "additional options or a new filename");
1289ddf5636dSMax Reitz             return -EINVAL;
1290ddf5636dSMax Reitz         }
1291ddf5636dSMax Reitz 
1292ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1293ddf5636dSMax Reitz         if (!bs) {
1294ddf5636dSMax Reitz             return -ENODEV;
1295ddf5636dSMax Reitz         }
1296ddf5636dSMax Reitz         bdrv_ref(bs);
1297ddf5636dSMax Reitz         *pbs = bs;
1298ddf5636dSMax Reitz         return 0;
1299ddf5636dSMax Reitz     }
1300ddf5636dSMax Reitz 
1301f67503e5SMax Reitz     if (*pbs) {
1302f67503e5SMax Reitz         bs = *pbs;
1303f67503e5SMax Reitz     } else {
130498522f63SKevin Wolf         bs = bdrv_new("", &error_abort);
1305f67503e5SMax Reitz     }
1306f67503e5SMax Reitz 
1307de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1308de9c0cecSKevin Wolf     if (options == NULL) {
1309de9c0cecSKevin Wolf         options = qdict_new();
1310de9c0cecSKevin Wolf     }
1311de9c0cecSKevin Wolf 
1312de9c0cecSKevin Wolf     bs->options = options;
1313b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1314de9c0cecSKevin Wolf 
13155469a2a6SMax Reitz     if (flags & BDRV_O_PROTOCOL) {
13165469a2a6SMax Reitz         assert(!drv);
13175acd9d81SMax Reitz         ret = bdrv_file_open(bs, filename, &options, flags & ~BDRV_O_PROTOCOL,
13185469a2a6SMax Reitz                              &local_err);
13195469a2a6SMax Reitz         if (!ret) {
1320eb909c7fSKevin Wolf             drv = bs->drv;
13215acd9d81SMax Reitz             goto done;
13225469a2a6SMax Reitz         } else if (bs->drv) {
13235469a2a6SMax Reitz             goto close_and_fail;
13245469a2a6SMax Reitz         } else {
13255469a2a6SMax Reitz             goto fail;
13265469a2a6SMax Reitz         }
13275469a2a6SMax Reitz     }
13285469a2a6SMax Reitz 
1329f500a6d3SKevin Wolf     /* Open image file without format layer */
1330be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1331be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1332be028adcSJeff Cody     }
1333be028adcSJeff Cody 
1334f67503e5SMax Reitz     assert(file == NULL);
1335054963f8SMax Reitz     ret = bdrv_open_image(&file, filename, options, "file",
1336f7d9fd8cSMax Reitz                           bdrv_open_flags(bs, flags | BDRV_O_UNMAP) |
1337f7d9fd8cSMax Reitz                           BDRV_O_PROTOCOL, true, &local_err);
1338f500a6d3SKevin Wolf     if (ret < 0) {
13399562f69cSMax Reitz         goto unlink_and_fail;
1340f500a6d3SKevin Wolf     }
1341f500a6d3SKevin Wolf 
1342f500a6d3SKevin Wolf     /* Find the right image format driver */
134374fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
134474fe54f2SKevin Wolf     if (drvname) {
13458f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
134674fe54f2SKevin Wolf         qdict_del(options, "driver");
134706d22aa3SKevin Wolf         if (!drv) {
134806d22aa3SKevin Wolf             error_setg(errp, "Invalid driver: '%s'", drvname);
134906d22aa3SKevin Wolf             ret = -EINVAL;
135006d22aa3SKevin Wolf             goto unlink_and_fail;
135106d22aa3SKevin Wolf         }
135274fe54f2SKevin Wolf     }
135374fe54f2SKevin Wolf 
1354f500a6d3SKevin Wolf     if (!drv) {
13552a05cbe4SMax Reitz         if (file) {
135634b5d2c6SMax Reitz             ret = find_image_format(file, filename, &drv, &local_err);
13572a05cbe4SMax Reitz         } else {
13582a05cbe4SMax Reitz             error_setg(errp, "Must specify either driver or file");
13592a05cbe4SMax Reitz             ret = -EINVAL;
13602a05cbe4SMax Reitz             goto unlink_and_fail;
13612a05cbe4SMax Reitz         }
1362f500a6d3SKevin Wolf     }
1363f500a6d3SKevin Wolf 
1364f500a6d3SKevin Wolf     if (!drv) {
1365f500a6d3SKevin Wolf         goto unlink_and_fail;
1366f500a6d3SKevin Wolf     }
1367f500a6d3SKevin Wolf 
1368b6ce07aaSKevin Wolf     /* Open the image */
136934b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1370b6ce07aaSKevin Wolf     if (ret < 0) {
13716987307cSChristoph Hellwig         goto unlink_and_fail;
13726987307cSChristoph Hellwig     }
13736987307cSChristoph Hellwig 
13742a05cbe4SMax Reitz     if (file && (bs->file != file)) {
13754f6fd349SFam Zheng         bdrv_unref(file);
1376f500a6d3SKevin Wolf         file = NULL;
1377f500a6d3SKevin Wolf     }
1378f500a6d3SKevin Wolf 
1379b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
13809156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
138131ca6d07SKevin Wolf         QDict *backing_options;
138231ca6d07SKevin Wolf 
13835726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
138434b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1385b6ce07aaSKevin Wolf         if (ret < 0) {
1386b6ad491aSKevin Wolf             goto close_and_fail;
1387b6ce07aaSKevin Wolf         }
1388b6ce07aaSKevin Wolf     }
1389b6ce07aaSKevin Wolf 
1390b998875dSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1391b998875dSKevin Wolf      * temporary snapshot afterwards. */
1392b998875dSKevin Wolf     if (flags & BDRV_O_SNAPSHOT) {
1393b998875dSKevin Wolf         bdrv_append_temp_snapshot(bs, &local_err);
1394b998875dSKevin Wolf         if (local_err) {
1395b998875dSKevin Wolf             error_propagate(errp, local_err);
1396b998875dSKevin Wolf             goto close_and_fail;
1397b998875dSKevin Wolf         }
1398b998875dSKevin Wolf     }
1399b998875dSKevin Wolf 
1400b998875dSKevin Wolf 
14015acd9d81SMax Reitz done:
1402b6ad491aSKevin Wolf     /* Check if any unknown options were used */
14035acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1404b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
14055acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
14065acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
14075acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
14085acd9d81SMax Reitz         } else {
140934b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
14105acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
14115acd9d81SMax Reitz                        bs->device_name, entry->key);
14125acd9d81SMax Reitz         }
1413b6ad491aSKevin Wolf 
1414b6ad491aSKevin Wolf         ret = -EINVAL;
1415b6ad491aSKevin Wolf         goto close_and_fail;
1416b6ad491aSKevin Wolf     }
1417b6ad491aSKevin Wolf 
1418b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
14197d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1420c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1421c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1422c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1423c3adb58fSMarkus Armbruster         error_setg(errp,
1424c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1425c3adb58fSMarkus Armbruster         ret = -EBUSY;
1426c3adb58fSMarkus Armbruster         goto close_and_fail;
1427b6ce07aaSKevin Wolf     }
1428b6ce07aaSKevin Wolf 
1429c3adb58fSMarkus Armbruster     QDECREF(options);
1430f67503e5SMax Reitz     *pbs = bs;
1431b6ce07aaSKevin Wolf     return 0;
1432b6ce07aaSKevin Wolf 
1433b6ce07aaSKevin Wolf unlink_and_fail:
1434f500a6d3SKevin Wolf     if (file != NULL) {
14354f6fd349SFam Zheng         bdrv_unref(file);
1436f500a6d3SKevin Wolf     }
1437b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1438b6ce07aaSKevin Wolf         unlink(filename);
1439b6ce07aaSKevin Wolf     }
1440de9c0cecSKevin Wolf fail:
1441de9c0cecSKevin Wolf     QDECREF(bs->options);
1442b6ad491aSKevin Wolf     QDECREF(options);
1443de9c0cecSKevin Wolf     bs->options = NULL;
1444f67503e5SMax Reitz     if (!*pbs) {
1445f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1446f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1447f67503e5SMax Reitz            since it has not really been opened yet. */
1448f67503e5SMax Reitz         bdrv_unref(bs);
1449f67503e5SMax Reitz     }
145084d18f06SMarkus Armbruster     if (local_err) {
145134b5d2c6SMax Reitz         error_propagate(errp, local_err);
145234b5d2c6SMax Reitz     }
1453b6ad491aSKevin Wolf     return ret;
1454de9c0cecSKevin Wolf 
1455b6ad491aSKevin Wolf close_and_fail:
1456f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1457f67503e5SMax Reitz     if (*pbs) {
1458b6ad491aSKevin Wolf         bdrv_close(bs);
1459f67503e5SMax Reitz     } else {
1460f67503e5SMax Reitz         bdrv_unref(bs);
1461f67503e5SMax Reitz     }
1462b6ad491aSKevin Wolf     QDECREF(options);
146384d18f06SMarkus Armbruster     if (local_err) {
146434b5d2c6SMax Reitz         error_propagate(errp, local_err);
146534b5d2c6SMax Reitz     }
1466b6ce07aaSKevin Wolf     return ret;
1467b6ce07aaSKevin Wolf }
1468b6ce07aaSKevin Wolf 
1469e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1470e971aa12SJeff Cody      bool prepared;
1471e971aa12SJeff Cody      BDRVReopenState state;
1472e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1473e971aa12SJeff Cody } BlockReopenQueueEntry;
1474e971aa12SJeff Cody 
1475e971aa12SJeff Cody /*
1476e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1477e971aa12SJeff Cody  * reopen of multiple devices.
1478e971aa12SJeff Cody  *
1479e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1480e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1481e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1482e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1483e971aa12SJeff Cody  * atomic 'set'.
1484e971aa12SJeff Cody  *
1485e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1486e971aa12SJeff Cody  *
1487e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1488e971aa12SJeff Cody  *
1489e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1490e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1491e971aa12SJeff Cody  *
1492e971aa12SJeff Cody  */
1493e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1494e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1495e971aa12SJeff Cody {
1496e971aa12SJeff Cody     assert(bs != NULL);
1497e971aa12SJeff Cody 
1498e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1499e971aa12SJeff Cody     if (bs_queue == NULL) {
1500e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1501e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1502e971aa12SJeff Cody     }
1503e971aa12SJeff Cody 
1504e971aa12SJeff Cody     if (bs->file) {
1505e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1506e971aa12SJeff Cody     }
1507e971aa12SJeff Cody 
1508e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1509e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1510e971aa12SJeff Cody 
1511e971aa12SJeff Cody     bs_entry->state.bs = bs;
1512e971aa12SJeff Cody     bs_entry->state.flags = flags;
1513e971aa12SJeff Cody 
1514e971aa12SJeff Cody     return bs_queue;
1515e971aa12SJeff Cody }
1516e971aa12SJeff Cody 
1517e971aa12SJeff Cody /*
1518e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1519e971aa12SJeff Cody  *
1520e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1521e971aa12SJeff Cody  * via bdrv_reopen_queue().
1522e971aa12SJeff Cody  *
1523e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1524e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1525e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1526e971aa12SJeff Cody  * data cleaned up.
1527e971aa12SJeff Cody  *
1528e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1529e971aa12SJeff Cody  * to all devices.
1530e971aa12SJeff Cody  *
1531e971aa12SJeff Cody  */
1532e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1533e971aa12SJeff Cody {
1534e971aa12SJeff Cody     int ret = -1;
1535e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1536e971aa12SJeff Cody     Error *local_err = NULL;
1537e971aa12SJeff Cody 
1538e971aa12SJeff Cody     assert(bs_queue != NULL);
1539e971aa12SJeff Cody 
1540e971aa12SJeff Cody     bdrv_drain_all();
1541e971aa12SJeff Cody 
1542e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1543e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1544e971aa12SJeff Cody             error_propagate(errp, local_err);
1545e971aa12SJeff Cody             goto cleanup;
1546e971aa12SJeff Cody         }
1547e971aa12SJeff Cody         bs_entry->prepared = true;
1548e971aa12SJeff Cody     }
1549e971aa12SJeff Cody 
1550e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1551e971aa12SJeff Cody      * changes
1552e971aa12SJeff Cody      */
1553e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1554e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1555e971aa12SJeff Cody     }
1556e971aa12SJeff Cody 
1557e971aa12SJeff Cody     ret = 0;
1558e971aa12SJeff Cody 
1559e971aa12SJeff Cody cleanup:
1560e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1561e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1562e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1563e971aa12SJeff Cody         }
1564e971aa12SJeff Cody         g_free(bs_entry);
1565e971aa12SJeff Cody     }
1566e971aa12SJeff Cody     g_free(bs_queue);
1567e971aa12SJeff Cody     return ret;
1568e971aa12SJeff Cody }
1569e971aa12SJeff Cody 
1570e971aa12SJeff Cody 
1571e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1572e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1573e971aa12SJeff Cody {
1574e971aa12SJeff Cody     int ret = -1;
1575e971aa12SJeff Cody     Error *local_err = NULL;
1576e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1577e971aa12SJeff Cody 
1578e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1579e971aa12SJeff Cody     if (local_err != NULL) {
1580e971aa12SJeff Cody         error_propagate(errp, local_err);
1581e971aa12SJeff Cody     }
1582e971aa12SJeff Cody     return ret;
1583e971aa12SJeff Cody }
1584e971aa12SJeff Cody 
1585e971aa12SJeff Cody 
1586e971aa12SJeff Cody /*
1587e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1588e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1589e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1590e971aa12SJeff Cody  *
1591e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1592e971aa12SJeff Cody  * flags are the new open flags
1593e971aa12SJeff Cody  * queue is the reopen queue
1594e971aa12SJeff Cody  *
1595e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1596e971aa12SJeff Cody  * as well.
1597e971aa12SJeff Cody  *
1598e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1599e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1600e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1601e971aa12SJeff Cody  *
1602e971aa12SJeff Cody  */
1603e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1604e971aa12SJeff Cody                         Error **errp)
1605e971aa12SJeff Cody {
1606e971aa12SJeff Cody     int ret = -1;
1607e971aa12SJeff Cody     Error *local_err = NULL;
1608e971aa12SJeff Cody     BlockDriver *drv;
1609e971aa12SJeff Cody 
1610e971aa12SJeff Cody     assert(reopen_state != NULL);
1611e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1612e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1613e971aa12SJeff Cody 
1614e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1615e971aa12SJeff Cody      * to r/w */
1616e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1617e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1618e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1619e971aa12SJeff Cody                   reopen_state->bs->device_name);
1620e971aa12SJeff Cody         goto error;
1621e971aa12SJeff Cody     }
1622e971aa12SJeff Cody 
1623e971aa12SJeff Cody 
1624e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1625e971aa12SJeff Cody     if (ret) {
1626e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1627e971aa12SJeff Cody                   strerror(-ret));
1628e971aa12SJeff Cody         goto error;
1629e971aa12SJeff Cody     }
1630e971aa12SJeff Cody 
1631e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1632e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1633e971aa12SJeff Cody         if (ret) {
1634e971aa12SJeff Cody             if (local_err != NULL) {
1635e971aa12SJeff Cody                 error_propagate(errp, local_err);
1636e971aa12SJeff Cody             } else {
1637d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1638e971aa12SJeff Cody                            reopen_state->bs->filename);
1639e971aa12SJeff Cody             }
1640e971aa12SJeff Cody             goto error;
1641e971aa12SJeff Cody         }
1642e971aa12SJeff Cody     } else {
1643e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1644e971aa12SJeff Cody          * handler for each supported drv. */
1645e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1646e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1647e971aa12SJeff Cody                  "reopening of file");
1648e971aa12SJeff Cody         ret = -1;
1649e971aa12SJeff Cody         goto error;
1650e971aa12SJeff Cody     }
1651e971aa12SJeff Cody 
1652e971aa12SJeff Cody     ret = 0;
1653e971aa12SJeff Cody 
1654e971aa12SJeff Cody error:
1655e971aa12SJeff Cody     return ret;
1656e971aa12SJeff Cody }
1657e971aa12SJeff Cody 
1658e971aa12SJeff Cody /*
1659e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1660e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1661e971aa12SJeff Cody  * the active BlockDriverState contents.
1662e971aa12SJeff Cody  */
1663e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1664e971aa12SJeff Cody {
1665e971aa12SJeff Cody     BlockDriver *drv;
1666e971aa12SJeff Cody 
1667e971aa12SJeff Cody     assert(reopen_state != NULL);
1668e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1669e971aa12SJeff Cody     assert(drv != NULL);
1670e971aa12SJeff Cody 
1671e971aa12SJeff Cody     /* If there are any driver level actions to take */
1672e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1673e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1674e971aa12SJeff Cody     }
1675e971aa12SJeff Cody 
1676e971aa12SJeff Cody     /* set BDS specific flags now */
1677e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1678e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1679e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1680e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1681355ef4acSKevin Wolf 
1682355ef4acSKevin Wolf     bdrv_refresh_limits(reopen_state->bs);
1683e971aa12SJeff Cody }
1684e971aa12SJeff Cody 
1685e971aa12SJeff Cody /*
1686e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1687e971aa12SJeff Cody  * reopen_state
1688e971aa12SJeff Cody  */
1689e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1690e971aa12SJeff Cody {
1691e971aa12SJeff Cody     BlockDriver *drv;
1692e971aa12SJeff Cody 
1693e971aa12SJeff Cody     assert(reopen_state != NULL);
1694e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1695e971aa12SJeff Cody     assert(drv != NULL);
1696e971aa12SJeff Cody 
1697e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1698e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1699e971aa12SJeff Cody     }
1700e971aa12SJeff Cody }
1701e971aa12SJeff Cody 
1702e971aa12SJeff Cody 
1703fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1704fc01f7e7Sbellard {
17053e914655SPaolo Bonzini     if (bs->job) {
17063e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
17073e914655SPaolo Bonzini     }
170858fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
170958fda173SStefan Hajnoczi     bdrv_flush(bs);
171058fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1711d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
17127094f12fSKevin Wolf 
17133cbc002cSPaolo Bonzini     if (bs->drv) {
1714557df6acSStefan Hajnoczi         if (bs->backing_hd) {
17154f6fd349SFam Zheng             bdrv_unref(bs->backing_hd);
1716557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1717557df6acSStefan Hajnoczi         }
1718ea2384d3Sbellard         bs->drv->bdrv_close(bs);
17197267c094SAnthony Liguori         g_free(bs->opaque);
1720ea2384d3Sbellard #ifdef _WIN32
1721ea2384d3Sbellard         if (bs->is_temporary) {
1722ea2384d3Sbellard             unlink(bs->filename);
1723ea2384d3Sbellard         }
172467b915a5Sbellard #endif
1725ea2384d3Sbellard         bs->opaque = NULL;
1726ea2384d3Sbellard         bs->drv = NULL;
172753fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1728a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1729a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
17306405875cSPaolo Bonzini         bs->total_sectors = 0;
17316405875cSPaolo Bonzini         bs->encrypted = 0;
17326405875cSPaolo Bonzini         bs->valid_key = 0;
17336405875cSPaolo Bonzini         bs->sg = 0;
17346405875cSPaolo Bonzini         bs->growable = 0;
17350d51b4deSAsias He         bs->zero_beyond_eof = false;
1736de9c0cecSKevin Wolf         QDECREF(bs->options);
1737de9c0cecSKevin Wolf         bs->options = NULL;
1738b338082bSbellard 
173966f82ceeSKevin Wolf         if (bs->file != NULL) {
17404f6fd349SFam Zheng             bdrv_unref(bs->file);
17410ac9377dSPaolo Bonzini             bs->file = NULL;
174266f82ceeSKevin Wolf         }
17439ca11154SPavel Hrdina     }
174466f82ceeSKevin Wolf 
17457d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
174698f90dbaSZhi Yong Wu 
174798f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
174898f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
174998f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
175098f90dbaSZhi Yong Wu     }
1751b338082bSbellard }
1752b338082bSbellard 
17532bc93fedSMORITA Kazutaka void bdrv_close_all(void)
17542bc93fedSMORITA Kazutaka {
17552bc93fedSMORITA Kazutaka     BlockDriverState *bs;
17562bc93fedSMORITA Kazutaka 
1757dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17582bc93fedSMORITA Kazutaka         bdrv_close(bs);
17592bc93fedSMORITA Kazutaka     }
17602bc93fedSMORITA Kazutaka }
17612bc93fedSMORITA Kazutaka 
176288266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
176388266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
176488266f5aSStefan Hajnoczi {
176588266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
176688266f5aSStefan Hajnoczi         return true;
176788266f5aSStefan Hajnoczi     }
1768cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1769cc0681c4SBenoît Canet         return true;
1770cc0681c4SBenoît Canet     }
1771cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
177288266f5aSStefan Hajnoczi         return true;
177388266f5aSStefan Hajnoczi     }
177488266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
177588266f5aSStefan Hajnoczi         return true;
177688266f5aSStefan Hajnoczi     }
177788266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
177888266f5aSStefan Hajnoczi         return true;
177988266f5aSStefan Hajnoczi     }
178088266f5aSStefan Hajnoczi     return false;
178188266f5aSStefan Hajnoczi }
178288266f5aSStefan Hajnoczi 
178388266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
178488266f5aSStefan Hajnoczi {
178588266f5aSStefan Hajnoczi     BlockDriverState *bs;
1786dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
178788266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
178888266f5aSStefan Hajnoczi             return true;
178988266f5aSStefan Hajnoczi         }
179088266f5aSStefan Hajnoczi     }
179188266f5aSStefan Hajnoczi     return false;
179288266f5aSStefan Hajnoczi }
179388266f5aSStefan Hajnoczi 
1794922453bcSStefan Hajnoczi /*
1795922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1796922453bcSStefan Hajnoczi  *
1797922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1798922453bcSStefan Hajnoczi  * after calling this function.
17994c355d53SZhi Yong Wu  *
18004c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
18014c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
18024c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
18034c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
18044c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1805922453bcSStefan Hajnoczi  */
1806922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1807922453bcSStefan Hajnoczi {
180888266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
180988266f5aSStefan Hajnoczi     bool busy = true;
1810922453bcSStefan Hajnoczi     BlockDriverState *bs;
1811922453bcSStefan Hajnoczi 
181288266f5aSStefan Hajnoczi     while (busy) {
1813dc364f4cSBenoît Canet         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
18140b06ef3bSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
18154c355d53SZhi Yong Wu         }
1816922453bcSStefan Hajnoczi 
181788266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
181888266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1819922453bcSStefan Hajnoczi     }
1820922453bcSStefan Hajnoczi }
1821922453bcSStefan Hajnoczi 
1822dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1823dc364f4cSBenoît Canet  * graph_bdrv_state list.
1824d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1825d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1826d22b2f41SRyan Harper {
1827d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1828dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1829d22b2f41SRyan Harper     }
1830d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1831dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1832dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1833dc364f4cSBenoît Canet     }
1834dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1835d22b2f41SRyan Harper }
1836d22b2f41SRyan Harper 
1837e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1838e023b2e2SPaolo Bonzini {
1839e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1840e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1841e023b2e2SPaolo Bonzini     }
1842e023b2e2SPaolo Bonzini }
1843e023b2e2SPaolo Bonzini 
18444ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
18454ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
18464ddc07caSPaolo Bonzini {
18474ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
18484ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
18494ddc07caSPaolo Bonzini 
18504ddc07caSPaolo Bonzini     /* dev info */
18514ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
18524ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
18534ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
18541b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
18554ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
18564ddc07caSPaolo Bonzini 
18574ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
18584ddc07caSPaolo Bonzini 
1859cc0681c4SBenoît Canet     /* i/o throttled req */
1860cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1861cc0681c4SBenoît Canet            &bs_src->throttle_state,
1862cc0681c4SBenoît Canet            sizeof(ThrottleState));
1863cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1864cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
18654ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
18664ddc07caSPaolo Bonzini 
18674ddc07caSPaolo Bonzini     /* r/w error */
18684ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
18694ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
18704ddc07caSPaolo Bonzini 
18714ddc07caSPaolo Bonzini     /* i/o status */
18724ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
18734ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
18744ddc07caSPaolo Bonzini 
18754ddc07caSPaolo Bonzini     /* dirty bitmap */
1876e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
18774ddc07caSPaolo Bonzini 
18789fcb0251SFam Zheng     /* reference count */
18799fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
18809fcb0251SFam Zheng 
18814ddc07caSPaolo Bonzini     /* job */
18824ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
18834ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
18844ddc07caSPaolo Bonzini 
18854ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
18864ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
18874ddc07caSPaolo Bonzini             bs_src->device_name);
1888dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
18894ddc07caSPaolo Bonzini }
18904ddc07caSPaolo Bonzini 
18914ddc07caSPaolo Bonzini /*
18924ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
18934ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
18944ddc07caSPaolo Bonzini  * actually attached to a device.
18954ddc07caSPaolo Bonzini  *
18964ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
18974ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
18984ddc07caSPaolo Bonzini  *
18994ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
19004ddc07caSPaolo Bonzini  *
19014ddc07caSPaolo Bonzini  * This function does not create any image files.
19024ddc07caSPaolo Bonzini  */
19034ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
19044ddc07caSPaolo Bonzini {
19054ddc07caSPaolo Bonzini     BlockDriverState tmp;
19064ddc07caSPaolo Bonzini 
190790ce8a06SBenoît Canet     /* The code needs to swap the node_name but simply swapping node_list won't
190890ce8a06SBenoît Canet      * work so first remove the nodes from the graph list, do the swap then
190990ce8a06SBenoît Canet      * insert them back if needed.
191090ce8a06SBenoît Canet      */
191190ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
191290ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
191390ce8a06SBenoît Canet     }
191490ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
191590ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
191690ce8a06SBenoît Canet     }
191790ce8a06SBenoît Canet 
19184ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
19194ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
1920e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
19214ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
19224ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
19234ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
19244ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1925cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
19264ddc07caSPaolo Bonzini 
19274ddc07caSPaolo Bonzini     tmp = *bs_new;
19284ddc07caSPaolo Bonzini     *bs_new = *bs_old;
19294ddc07caSPaolo Bonzini     *bs_old = tmp;
19304ddc07caSPaolo Bonzini 
19314ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
19324ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
19334ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
19344ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
19354ddc07caSPaolo Bonzini 
19364ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
19374ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
19384ddc07caSPaolo Bonzini 
19394ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
19404ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
19414ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
19424ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
19434ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1944cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
19454ddc07caSPaolo Bonzini 
194690ce8a06SBenoît Canet     /* insert the nodes back into the graph node list if needed */
194790ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
194890ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
194990ce8a06SBenoît Canet     }
195090ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
195190ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
195290ce8a06SBenoît Canet     }
195390ce8a06SBenoît Canet 
19544ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
19554ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
19564ddc07caSPaolo Bonzini }
19574ddc07caSPaolo Bonzini 
19588802d1fdSJeff Cody /*
19598802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
19608802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
19618802d1fdSJeff Cody  *
19628802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
19638802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
19648802d1fdSJeff Cody  *
1965f6801b83SJeff Cody  * bs_new is required to be anonymous.
1966f6801b83SJeff Cody  *
19678802d1fdSJeff Cody  * This function does not create any image files.
19688802d1fdSJeff Cody  */
19698802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
19708802d1fdSJeff Cody {
19714ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
19728802d1fdSJeff Cody 
19738802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
19748802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
19754ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
19764ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
19774ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
19784ddc07caSPaolo Bonzini             bs_new->filename);
19794ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
19804ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
19818802d1fdSJeff Cody }
19828802d1fdSJeff Cody 
19834f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
1984b338082bSbellard {
1985fa879d62SMarkus Armbruster     assert(!bs->dev);
19863e914655SPaolo Bonzini     assert(!bs->job);
19873e914655SPaolo Bonzini     assert(!bs->in_use);
19884f6fd349SFam Zheng     assert(!bs->refcnt);
1989e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
199018846deeSMarkus Armbruster 
1991e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1992e1b5c52eSStefan Hajnoczi 
19931b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1994d22b2f41SRyan Harper     bdrv_make_anon(bs);
199534c6f050Saurel32 
19967267c094SAnthony Liguori     g_free(bs);
1997fc01f7e7Sbellard }
1998fc01f7e7Sbellard 
1999fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
2000fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
200118846deeSMarkus Armbruster {
2002fa879d62SMarkus Armbruster     if (bs->dev) {
200318846deeSMarkus Armbruster         return -EBUSY;
200418846deeSMarkus Armbruster     }
2005fa879d62SMarkus Armbruster     bs->dev = dev;
200628a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
200718846deeSMarkus Armbruster     return 0;
200818846deeSMarkus Armbruster }
200918846deeSMarkus Armbruster 
2010fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
2011fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
201218846deeSMarkus Armbruster {
2013fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
2014fa879d62SMarkus Armbruster         abort();
2015fa879d62SMarkus Armbruster     }
2016fa879d62SMarkus Armbruster }
2017fa879d62SMarkus Armbruster 
2018fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
2019fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
2020fa879d62SMarkus Armbruster {
2021fa879d62SMarkus Armbruster     assert(bs->dev == dev);
2022fa879d62SMarkus Armbruster     bs->dev = NULL;
20230e49de52SMarkus Armbruster     bs->dev_ops = NULL;
20240e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
20251b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
202618846deeSMarkus Armbruster }
202718846deeSMarkus Armbruster 
2028fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
2029fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
203018846deeSMarkus Armbruster {
2031fa879d62SMarkus Armbruster     return bs->dev;
203218846deeSMarkus Armbruster }
203318846deeSMarkus Armbruster 
20340e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
20350e49de52SMarkus Armbruster                       void *opaque)
20360e49de52SMarkus Armbruster {
20370e49de52SMarkus Armbruster     bs->dev_ops = ops;
20380e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
20390e49de52SMarkus Armbruster }
20400e49de52SMarkus Armbruster 
204132c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
204232c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
20431ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
2044329c0a48SLuiz Capitulino {
2045329c0a48SLuiz Capitulino     QObject *data;
2046329c0a48SLuiz Capitulino     const char *action_str;
2047329c0a48SLuiz Capitulino 
2048329c0a48SLuiz Capitulino     switch (action) {
2049329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
2050329c0a48SLuiz Capitulino         action_str = "report";
2051329c0a48SLuiz Capitulino         break;
2052329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
2053329c0a48SLuiz Capitulino         action_str = "ignore";
2054329c0a48SLuiz Capitulino         break;
2055329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
2056329c0a48SLuiz Capitulino         action_str = "stop";
2057329c0a48SLuiz Capitulino         break;
2058329c0a48SLuiz Capitulino     default:
2059329c0a48SLuiz Capitulino         abort();
2060329c0a48SLuiz Capitulino     }
2061329c0a48SLuiz Capitulino 
2062329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
2063329c0a48SLuiz Capitulino                               bdrv->device_name,
2064329c0a48SLuiz Capitulino                               action_str,
2065329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
206632c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
2067329c0a48SLuiz Capitulino 
2068329c0a48SLuiz Capitulino     qobject_decref(data);
2069329c0a48SLuiz Capitulino }
2070329c0a48SLuiz Capitulino 
20716f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
20726f382ed2SLuiz Capitulino {
20736f382ed2SLuiz Capitulino     QObject *data;
20746f382ed2SLuiz Capitulino 
20756f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
20766f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
20776f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
20786f382ed2SLuiz Capitulino 
20796f382ed2SLuiz Capitulino     qobject_decref(data);
20806f382ed2SLuiz Capitulino }
20816f382ed2SLuiz Capitulino 
20827d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
20830e49de52SMarkus Armbruster {
2084145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
20856f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
20867d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
20876f382ed2SLuiz Capitulino         if (tray_was_closed) {
20886f382ed2SLuiz Capitulino             /* tray open */
20896f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
20906f382ed2SLuiz Capitulino         }
20916f382ed2SLuiz Capitulino         if (load) {
20926f382ed2SLuiz Capitulino             /* tray close */
20936f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
20946f382ed2SLuiz Capitulino         }
2095145feb17SMarkus Armbruster     }
2096145feb17SMarkus Armbruster }
2097145feb17SMarkus Armbruster 
20982c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
20992c6942faSMarkus Armbruster {
21002c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
21012c6942faSMarkus Armbruster }
21022c6942faSMarkus Armbruster 
2103025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2104025ccaa7SPaolo Bonzini {
2105025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2106025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2107025ccaa7SPaolo Bonzini     }
2108025ccaa7SPaolo Bonzini }
2109025ccaa7SPaolo Bonzini 
2110e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2111e4def80bSMarkus Armbruster {
2112e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2113e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
2114e4def80bSMarkus Armbruster     }
2115e4def80bSMarkus Armbruster     return false;
2116e4def80bSMarkus Armbruster }
2117e4def80bSMarkus Armbruster 
2118145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
2119145feb17SMarkus Armbruster {
2120145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
2121145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
21220e49de52SMarkus Armbruster     }
21230e49de52SMarkus Armbruster }
21240e49de52SMarkus Armbruster 
2125f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2126f107639aSMarkus Armbruster {
2127f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2128f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2129f107639aSMarkus Armbruster     }
2130f107639aSMarkus Armbruster     return false;
2131f107639aSMarkus Armbruster }
2132f107639aSMarkus Armbruster 
2133e97fc193Saliguori /*
2134e97fc193Saliguori  * Run consistency checks on an image
2135e97fc193Saliguori  *
2136e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2137a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2138e076f338SKevin Wolf  * check are stored in res.
2139e97fc193Saliguori  */
21404534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2141e97fc193Saliguori {
2142e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2143e97fc193Saliguori         return -ENOTSUP;
2144e97fc193Saliguori     }
2145e97fc193Saliguori 
2146e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
21474534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2148e97fc193Saliguori }
2149e97fc193Saliguori 
21508a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
21518a426614SKevin Wolf 
215233e3963eSbellard /* commit COW file into the raw image */
215333e3963eSbellard int bdrv_commit(BlockDriverState *bs)
215433e3963eSbellard {
215519cb3738Sbellard     BlockDriver *drv = bs->drv;
215672706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
21578a426614SKevin Wolf     int n, ro, open_flags;
21580bce597dSJeff Cody     int ret = 0;
215972706ea4SJeff Cody     uint8_t *buf = NULL;
2160c2cba3d9SJim Meyering     char filename[PATH_MAX];
216133e3963eSbellard 
216219cb3738Sbellard     if (!drv)
216319cb3738Sbellard         return -ENOMEDIUM;
216433e3963eSbellard 
21654dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
21664dca4b63SNaphtali Sprei         return -ENOTSUP;
21674dca4b63SNaphtali Sprei     }
21684dca4b63SNaphtali Sprei 
21692d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
21702d3735d3SStefan Hajnoczi         return -EBUSY;
21712d3735d3SStefan Hajnoczi     }
21722d3735d3SStefan Hajnoczi 
21734dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2174c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2175c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
21764dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
21774dca4b63SNaphtali Sprei 
21784dca4b63SNaphtali Sprei     if (ro) {
21790bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
21800bce597dSJeff Cody             return -EACCES;
21814dca4b63SNaphtali Sprei         }
2182ea2384d3Sbellard     }
2183ea2384d3Sbellard 
218472706ea4SJeff Cody     length = bdrv_getlength(bs);
218572706ea4SJeff Cody     if (length < 0) {
218672706ea4SJeff Cody         ret = length;
218772706ea4SJeff Cody         goto ro_cleanup;
218872706ea4SJeff Cody     }
218972706ea4SJeff Cody 
219072706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
219172706ea4SJeff Cody     if (backing_length < 0) {
219272706ea4SJeff Cody         ret = backing_length;
219372706ea4SJeff Cody         goto ro_cleanup;
219472706ea4SJeff Cody     }
219572706ea4SJeff Cody 
219672706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
219772706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
219872706ea4SJeff Cody      * we must return an error */
219972706ea4SJeff Cody     if (length > backing_length) {
220072706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
220172706ea4SJeff Cody         if (ret < 0) {
220272706ea4SJeff Cody             goto ro_cleanup;
220372706ea4SJeff Cody         }
220472706ea4SJeff Cody     }
220572706ea4SJeff Cody 
220672706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
22077267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
22088a426614SKevin Wolf 
22098a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2210d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2211d663640cSPaolo Bonzini         if (ret < 0) {
2212d663640cSPaolo Bonzini             goto ro_cleanup;
2213d663640cSPaolo Bonzini         }
2214d663640cSPaolo Bonzini         if (ret) {
2215dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2216dabfa6ccSKevin Wolf             if (ret < 0) {
22174dca4b63SNaphtali Sprei                 goto ro_cleanup;
221833e3963eSbellard             }
221933e3963eSbellard 
2220dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2221dabfa6ccSKevin Wolf             if (ret < 0) {
22224dca4b63SNaphtali Sprei                 goto ro_cleanup;
222333e3963eSbellard             }
222433e3963eSbellard         }
222533e3963eSbellard     }
222695389c86Sbellard 
22271d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
22281d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2229dabfa6ccSKevin Wolf         if (ret < 0) {
2230dabfa6ccSKevin Wolf             goto ro_cleanup;
2231dabfa6ccSKevin Wolf         }
22321d44952fSChristoph Hellwig         bdrv_flush(bs);
22331d44952fSChristoph Hellwig     }
223495389c86Sbellard 
22353f5075aeSChristoph Hellwig     /*
22363f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
22373f5075aeSChristoph Hellwig      * stable on disk.
22383f5075aeSChristoph Hellwig      */
2239dabfa6ccSKevin Wolf     if (bs->backing_hd) {
22403f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2241dabfa6ccSKevin Wolf     }
22424dca4b63SNaphtali Sprei 
2243dabfa6ccSKevin Wolf     ret = 0;
22444dca4b63SNaphtali Sprei ro_cleanup:
22457267c094SAnthony Liguori     g_free(buf);
22464dca4b63SNaphtali Sprei 
22474dca4b63SNaphtali Sprei     if (ro) {
22480bce597dSJeff Cody         /* ignoring error return here */
22490bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
22504dca4b63SNaphtali Sprei     }
22514dca4b63SNaphtali Sprei 
22521d44952fSChristoph Hellwig     return ret;
225333e3963eSbellard }
225433e3963eSbellard 
2255e8877497SStefan Hajnoczi int bdrv_commit_all(void)
22566ab4b5abSMarkus Armbruster {
22576ab4b5abSMarkus Armbruster     BlockDriverState *bs;
22586ab4b5abSMarkus Armbruster 
2259dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2260272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2261e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2262e8877497SStefan Hajnoczi             if (ret < 0) {
2263e8877497SStefan Hajnoczi                 return ret;
22646ab4b5abSMarkus Armbruster             }
22656ab4b5abSMarkus Armbruster         }
2266272d2d8eSJeff Cody     }
2267e8877497SStefan Hajnoczi     return 0;
2268e8877497SStefan Hajnoczi }
22696ab4b5abSMarkus Armbruster 
2270dbffbdcfSStefan Hajnoczi /**
2271dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2272dbffbdcfSStefan Hajnoczi  *
2273dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2274dbffbdcfSStefan Hajnoczi  */
2275dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2276dbffbdcfSStefan Hajnoczi {
22772dbafdc0SKevin Wolf     if (req->serialising) {
22782dbafdc0SKevin Wolf         req->bs->serialising_in_flight--;
22792dbafdc0SKevin Wolf     }
22802dbafdc0SKevin Wolf 
2281dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2282f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2283dbffbdcfSStefan Hajnoczi }
2284dbffbdcfSStefan Hajnoczi 
2285dbffbdcfSStefan Hajnoczi /**
2286dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2287dbffbdcfSStefan Hajnoczi  */
2288dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2289dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2290793ed47aSKevin Wolf                                   int64_t offset,
2291793ed47aSKevin Wolf                                   unsigned int bytes, bool is_write)
2292dbffbdcfSStefan Hajnoczi {
2293dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2294dbffbdcfSStefan Hajnoczi         .bs = bs,
2295793ed47aSKevin Wolf         .offset         = offset,
2296793ed47aSKevin Wolf         .bytes          = bytes,
2297dbffbdcfSStefan Hajnoczi         .is_write       = is_write,
22985f8b6491SStefan Hajnoczi         .co             = qemu_coroutine_self(),
22992dbafdc0SKevin Wolf         .serialising    = false,
23007327145fSKevin Wolf         .overlap_offset = offset,
23017327145fSKevin Wolf         .overlap_bytes  = bytes,
2302dbffbdcfSStefan Hajnoczi     };
2303dbffbdcfSStefan Hajnoczi 
2304f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2305f4658285SStefan Hajnoczi 
2306dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2307dbffbdcfSStefan Hajnoczi }
2308dbffbdcfSStefan Hajnoczi 
2309e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
23102dbafdc0SKevin Wolf {
23117327145fSKevin Wolf     int64_t overlap_offset = req->offset & ~(align - 1);
2312e96126ffSKevin Wolf     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
23137327145fSKevin Wolf                                - overlap_offset;
23147327145fSKevin Wolf 
23152dbafdc0SKevin Wolf     if (!req->serialising) {
23162dbafdc0SKevin Wolf         req->bs->serialising_in_flight++;
23172dbafdc0SKevin Wolf         req->serialising = true;
23182dbafdc0SKevin Wolf     }
23197327145fSKevin Wolf 
23207327145fSKevin Wolf     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
23217327145fSKevin Wolf     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
23222dbafdc0SKevin Wolf }
23232dbafdc0SKevin Wolf 
2324d83947acSStefan Hajnoczi /**
2325d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2326d83947acSStefan Hajnoczi  */
2327343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2328d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2329d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2330d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2331d83947acSStefan Hajnoczi {
2332d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2333d83947acSStefan Hajnoczi 
2334d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2335d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2336d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2337d83947acSStefan Hajnoczi     } else {
2338d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2339d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2340d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2341d83947acSStefan Hajnoczi                                             nb_sectors, c);
2342d83947acSStefan Hajnoczi     }
2343d83947acSStefan Hajnoczi }
2344d83947acSStefan Hajnoczi 
23457327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs)
2346793ed47aSKevin Wolf {
2347793ed47aSKevin Wolf     BlockDriverInfo bdi;
23487327145fSKevin Wolf     int ret;
2349793ed47aSKevin Wolf 
23507327145fSKevin Wolf     ret = bdrv_get_info(bs, &bdi);
23517327145fSKevin Wolf     if (ret < 0 || bdi.cluster_size == 0) {
23527327145fSKevin Wolf         return bs->request_alignment;
2353793ed47aSKevin Wolf     } else {
23547327145fSKevin Wolf         return bdi.cluster_size;
2355793ed47aSKevin Wolf     }
2356793ed47aSKevin Wolf }
2357793ed47aSKevin Wolf 
2358f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2359793ed47aSKevin Wolf                                      int64_t offset, unsigned int bytes)
2360793ed47aSKevin Wolf {
2361d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
23627327145fSKevin Wolf     if (offset >= req->overlap_offset + req->overlap_bytes) {
2363d83947acSStefan Hajnoczi         return false;
2364d83947acSStefan Hajnoczi     }
2365d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
23667327145fSKevin Wolf     if (req->overlap_offset >= offset + bytes) {
2367d83947acSStefan Hajnoczi         return false;
2368d83947acSStefan Hajnoczi     }
2369d83947acSStefan Hajnoczi     return true;
2370f4658285SStefan Hajnoczi }
2371f4658285SStefan Hajnoczi 
237228de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
2373f4658285SStefan Hajnoczi {
23742dbafdc0SKevin Wolf     BlockDriverState *bs = self->bs;
2375f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2376f4658285SStefan Hajnoczi     bool retry;
237728de2dcdSKevin Wolf     bool waited = false;
2378f4658285SStefan Hajnoczi 
23792dbafdc0SKevin Wolf     if (!bs->serialising_in_flight) {
238028de2dcdSKevin Wolf         return false;
23812dbafdc0SKevin Wolf     }
23822dbafdc0SKevin Wolf 
2383f4658285SStefan Hajnoczi     do {
2384f4658285SStefan Hajnoczi         retry = false;
2385f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
23862dbafdc0SKevin Wolf             if (req == self || (!req->serialising && !self->serialising)) {
238765afd211SKevin Wolf                 continue;
238865afd211SKevin Wolf             }
23897327145fSKevin Wolf             if (tracked_request_overlaps(req, self->overlap_offset,
23907327145fSKevin Wolf                                          self->overlap_bytes))
23917327145fSKevin Wolf             {
23925f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
23935f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
23945f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
23955f8b6491SStefan Hajnoczi                  */
23965f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
23975f8b6491SStefan Hajnoczi 
23986460440fSKevin Wolf                 /* If the request is already (indirectly) waiting for us, or
23996460440fSKevin Wolf                  * will wait for us as soon as it wakes up, then just go on
24006460440fSKevin Wolf                  * (instead of producing a deadlock in the former case). */
24016460440fSKevin Wolf                 if (!req->waiting_for) {
24026460440fSKevin Wolf                     self->waiting_for = req;
2403f4658285SStefan Hajnoczi                     qemu_co_queue_wait(&req->wait_queue);
24046460440fSKevin Wolf                     self->waiting_for = NULL;
2405f4658285SStefan Hajnoczi                     retry = true;
240628de2dcdSKevin Wolf                     waited = true;
2407f4658285SStefan Hajnoczi                     break;
2408f4658285SStefan Hajnoczi                 }
2409f4658285SStefan Hajnoczi             }
24106460440fSKevin Wolf         }
2411f4658285SStefan Hajnoczi     } while (retry);
241228de2dcdSKevin Wolf 
241328de2dcdSKevin Wolf     return waited;
2414f4658285SStefan Hajnoczi }
2415f4658285SStefan Hajnoczi 
2416756e6736SKevin Wolf /*
2417756e6736SKevin Wolf  * Return values:
2418756e6736SKevin Wolf  * 0        - success
2419756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2420756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2421756e6736SKevin Wolf  *            image file header
2422756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2423756e6736SKevin Wolf  */
2424756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2425756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2426756e6736SKevin Wolf {
2427756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2428469ef350SPaolo Bonzini     int ret;
2429756e6736SKevin Wolf 
24305f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
24315f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
24325f377794SPaolo Bonzini         return -EINVAL;
24335f377794SPaolo Bonzini     }
24345f377794SPaolo Bonzini 
2435756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2436469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2437756e6736SKevin Wolf     } else {
2438469ef350SPaolo Bonzini         ret = -ENOTSUP;
2439756e6736SKevin Wolf     }
2440469ef350SPaolo Bonzini 
2441469ef350SPaolo Bonzini     if (ret == 0) {
2442469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2443469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2444469ef350SPaolo Bonzini     }
2445469ef350SPaolo Bonzini     return ret;
2446756e6736SKevin Wolf }
2447756e6736SKevin Wolf 
24486ebdcee2SJeff Cody /*
24496ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
24506ebdcee2SJeff Cody  *
24516ebdcee2SJeff Cody  * active is the current topmost image.
24526ebdcee2SJeff Cody  *
24536ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
24546ebdcee2SJeff Cody  * or if active == bs.
24556ebdcee2SJeff Cody  */
24566ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
24576ebdcee2SJeff Cody                                     BlockDriverState *bs)
24586ebdcee2SJeff Cody {
24596ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
24606ebdcee2SJeff Cody     BlockDriverState *intermediate;
24616ebdcee2SJeff Cody 
24626ebdcee2SJeff Cody     assert(active != NULL);
24636ebdcee2SJeff Cody     assert(bs != NULL);
24646ebdcee2SJeff Cody 
24656ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
24666ebdcee2SJeff Cody      */
24676ebdcee2SJeff Cody     if (active == bs) {
24686ebdcee2SJeff Cody         return NULL;
24696ebdcee2SJeff Cody     }
24706ebdcee2SJeff Cody 
24716ebdcee2SJeff Cody     intermediate = active;
24726ebdcee2SJeff Cody     while (intermediate->backing_hd) {
24736ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
24746ebdcee2SJeff Cody             overlay = intermediate;
24756ebdcee2SJeff Cody             break;
24766ebdcee2SJeff Cody         }
24776ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
24786ebdcee2SJeff Cody     }
24796ebdcee2SJeff Cody 
24806ebdcee2SJeff Cody     return overlay;
24816ebdcee2SJeff Cody }
24826ebdcee2SJeff Cody 
24836ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
24846ebdcee2SJeff Cody     BlockDriverState *bs;
24856ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
24866ebdcee2SJeff Cody } BlkIntermediateStates;
24876ebdcee2SJeff Cody 
24886ebdcee2SJeff Cody 
24896ebdcee2SJeff Cody /*
24906ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
24916ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
24926ebdcee2SJeff Cody  *
24936ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
24946ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
24956ebdcee2SJeff Cody  *
24966ebdcee2SJeff Cody  * E.g., this will convert the following chain:
24976ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
24986ebdcee2SJeff Cody  *
24996ebdcee2SJeff Cody  * to
25006ebdcee2SJeff Cody  *
25016ebdcee2SJeff Cody  * bottom <- base <- active
25026ebdcee2SJeff Cody  *
25036ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25046ebdcee2SJeff Cody  *
25056ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25066ebdcee2SJeff Cody  *
25076ebdcee2SJeff Cody  * to
25086ebdcee2SJeff Cody  *
25096ebdcee2SJeff Cody  * base <- active
25106ebdcee2SJeff Cody  *
25116ebdcee2SJeff Cody  * Error conditions:
25126ebdcee2SJeff Cody  *  if active == top, that is considered an error
25136ebdcee2SJeff Cody  *
25146ebdcee2SJeff Cody  */
25156ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
25166ebdcee2SJeff Cody                            BlockDriverState *base)
25176ebdcee2SJeff Cody {
25186ebdcee2SJeff Cody     BlockDriverState *intermediate;
25196ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
25206ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
25216ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
25226ebdcee2SJeff Cody     int ret = -EIO;
25236ebdcee2SJeff Cody 
25246ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
25256ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
25266ebdcee2SJeff Cody 
25276ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
25286ebdcee2SJeff Cody         goto exit;
25296ebdcee2SJeff Cody     }
25306ebdcee2SJeff Cody 
25316ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
25326ebdcee2SJeff Cody 
25336ebdcee2SJeff Cody     if (new_top_bs == NULL) {
25346ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
25356ebdcee2SJeff Cody         goto exit;
25366ebdcee2SJeff Cody     }
25376ebdcee2SJeff Cody 
25386ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
25396ebdcee2SJeff Cody      * to do, no intermediate images */
25406ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
25416ebdcee2SJeff Cody         ret = 0;
25426ebdcee2SJeff Cody         goto exit;
25436ebdcee2SJeff Cody     }
25446ebdcee2SJeff Cody 
25456ebdcee2SJeff Cody     intermediate = top;
25466ebdcee2SJeff Cody 
25476ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
25486ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
25496ebdcee2SJeff Cody      */
25506ebdcee2SJeff Cody     while (intermediate) {
25516ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
25526ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
25536ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
25546ebdcee2SJeff Cody 
25556ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
25566ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
25576ebdcee2SJeff Cody             break;
25586ebdcee2SJeff Cody         }
25596ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
25606ebdcee2SJeff Cody     }
25616ebdcee2SJeff Cody     if (base_bs == NULL) {
25626ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
25636ebdcee2SJeff Cody          * unravel everything, and exit with error */
25646ebdcee2SJeff Cody         goto exit;
25656ebdcee2SJeff Cody     }
25666ebdcee2SJeff Cody 
25676ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
25686ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
25696ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
25706ebdcee2SJeff Cody     if (ret) {
25716ebdcee2SJeff Cody         goto exit;
25726ebdcee2SJeff Cody     }
25736ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
25746ebdcee2SJeff Cody 
2575355ef4acSKevin Wolf     bdrv_refresh_limits(new_top_bs);
25766ebdcee2SJeff Cody 
25776ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25786ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
25796ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
25804f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
25816ebdcee2SJeff Cody     }
25826ebdcee2SJeff Cody     ret = 0;
25836ebdcee2SJeff Cody 
25846ebdcee2SJeff Cody exit:
25856ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25866ebdcee2SJeff Cody         g_free(intermediate_state);
25876ebdcee2SJeff Cody     }
25886ebdcee2SJeff Cody     return ret;
25896ebdcee2SJeff Cody }
25906ebdcee2SJeff Cody 
25916ebdcee2SJeff Cody 
259271d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
259371d0770cSaliguori                                    size_t size)
259471d0770cSaliguori {
259571d0770cSaliguori     int64_t len;
259671d0770cSaliguori 
25971dd3a447SKevin Wolf     if (size > INT_MAX) {
25981dd3a447SKevin Wolf         return -EIO;
25991dd3a447SKevin Wolf     }
26001dd3a447SKevin Wolf 
260171d0770cSaliguori     if (!bdrv_is_inserted(bs))
260271d0770cSaliguori         return -ENOMEDIUM;
260371d0770cSaliguori 
260471d0770cSaliguori     if (bs->growable)
260571d0770cSaliguori         return 0;
260671d0770cSaliguori 
260771d0770cSaliguori     len = bdrv_getlength(bs);
260871d0770cSaliguori 
2609fbb7b4e0SKevin Wolf     if (offset < 0)
2610fbb7b4e0SKevin Wolf         return -EIO;
2611fbb7b4e0SKevin Wolf 
2612fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
261371d0770cSaliguori         return -EIO;
261471d0770cSaliguori 
261571d0770cSaliguori     return 0;
261671d0770cSaliguori }
261771d0770cSaliguori 
261871d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
261971d0770cSaliguori                               int nb_sectors)
262071d0770cSaliguori {
262154db38a4SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
26228f4754edSKevin Wolf         return -EIO;
26238f4754edSKevin Wolf     }
26248f4754edSKevin Wolf 
2625eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2626eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
262771d0770cSaliguori }
262871d0770cSaliguori 
26291c9805a3SStefan Hajnoczi typedef struct RwCo {
26301c9805a3SStefan Hajnoczi     BlockDriverState *bs;
2631775aa8b6SKevin Wolf     int64_t offset;
26321c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
26331c9805a3SStefan Hajnoczi     bool is_write;
26341c9805a3SStefan Hajnoczi     int ret;
26354105eaaaSPeter Lieven     BdrvRequestFlags flags;
26361c9805a3SStefan Hajnoczi } RwCo;
26371c9805a3SStefan Hajnoczi 
26381c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2639fc01f7e7Sbellard {
26401c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2641fc01f7e7Sbellard 
26421c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
2643775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2644775aa8b6SKevin Wolf                                       rwco->qiov->size, rwco->qiov,
26454105eaaaSPeter Lieven                                       rwco->flags);
26461c9805a3SStefan Hajnoczi     } else {
2647775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2648775aa8b6SKevin Wolf                                        rwco->qiov->size, rwco->qiov,
26494105eaaaSPeter Lieven                                        rwco->flags);
26501c9805a3SStefan Hajnoczi     }
26511c9805a3SStefan Hajnoczi }
2652e7a8a783SKevin Wolf 
26531c9805a3SStefan Hajnoczi /*
26548d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
26551c9805a3SStefan Hajnoczi  */
2656775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
26574105eaaaSPeter Lieven                         QEMUIOVector *qiov, bool is_write,
26584105eaaaSPeter Lieven                         BdrvRequestFlags flags)
26591c9805a3SStefan Hajnoczi {
26601c9805a3SStefan Hajnoczi     Coroutine *co;
26611c9805a3SStefan Hajnoczi     RwCo rwco = {
26621c9805a3SStefan Hajnoczi         .bs = bs,
2663775aa8b6SKevin Wolf         .offset = offset,
26648d3b1a2dSKevin Wolf         .qiov = qiov,
26651c9805a3SStefan Hajnoczi         .is_write = is_write,
26661c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
26674105eaaaSPeter Lieven         .flags = flags,
26681c9805a3SStefan Hajnoczi     };
26691c9805a3SStefan Hajnoczi 
2670498e386cSZhi Yong Wu     /**
2671498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2672498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2673498e386cSZhi Yong Wu      * if it has been enabled.
2674498e386cSZhi Yong Wu      */
2675498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2676498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2677498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2678498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2679498e386cSZhi Yong Wu     }
2680498e386cSZhi Yong Wu 
26811c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
26821c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
26831c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
26841c9805a3SStefan Hajnoczi     } else {
26851c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
26861c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
26871c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
26881c9805a3SStefan Hajnoczi             qemu_aio_wait();
26891c9805a3SStefan Hajnoczi         }
26901c9805a3SStefan Hajnoczi     }
26911c9805a3SStefan Hajnoczi     return rwco.ret;
2692e7a8a783SKevin Wolf }
2693e7a8a783SKevin Wolf 
26948d3b1a2dSKevin Wolf /*
26958d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
26968d3b1a2dSKevin Wolf  */
26978d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
26984105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
26998d3b1a2dSKevin Wolf {
27008d3b1a2dSKevin Wolf     QEMUIOVector qiov;
27018d3b1a2dSKevin Wolf     struct iovec iov = {
27028d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
27038d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
27048d3b1a2dSKevin Wolf     };
27058d3b1a2dSKevin Wolf 
2706da15ee51SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
2707da15ee51SKevin Wolf         return -EINVAL;
2708da15ee51SKevin Wolf     }
2709da15ee51SKevin Wolf 
27108d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2711775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2712775aa8b6SKevin Wolf                         &qiov, is_write, flags);
27138d3b1a2dSKevin Wolf }
27148d3b1a2dSKevin Wolf 
27151c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
27161c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
27171c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
27181c9805a3SStefan Hajnoczi {
27194105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
272083f64091Sbellard }
2721fc01f7e7Sbellard 
272207d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
272307d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
272407d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
272507d27a44SMarkus Armbruster {
272607d27a44SMarkus Armbruster     bool enabled;
272707d27a44SMarkus Armbruster     int ret;
272807d27a44SMarkus Armbruster 
272907d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
273007d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
27314e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
273207d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
273307d27a44SMarkus Armbruster     return ret;
273407d27a44SMarkus Armbruster }
273507d27a44SMarkus Armbruster 
273619cb3738Sbellard /* Return < 0 if error. Important errors are:
273719cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
273819cb3738Sbellard   -ENOMEDIUM   No media inserted.
273919cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
274019cb3738Sbellard   -EACCES      Trying to write a read-only device
274119cb3738Sbellard */
2742fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2743fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2744fc01f7e7Sbellard {
27454105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
274683f64091Sbellard }
274783f64091Sbellard 
2748aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2749aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
27504105eaaaSPeter Lieven {
27514105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2752aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
27538d3b1a2dSKevin Wolf }
27548d3b1a2dSKevin Wolf 
2755d75cbb5eSPeter Lieven /*
2756d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2757d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2758d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2759d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2760d75cbb5eSPeter Lieven  *
2761d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2762d75cbb5eSPeter Lieven  */
2763d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2764d75cbb5eSPeter Lieven {
27659ce10c0bSKevin Wolf     int64_t target_size;
2766d75cbb5eSPeter Lieven     int64_t ret, nb_sectors, sector_num = 0;
2767d75cbb5eSPeter Lieven     int n;
2768d75cbb5eSPeter Lieven 
27699ce10c0bSKevin Wolf     target_size = bdrv_getlength(bs);
27709ce10c0bSKevin Wolf     if (target_size < 0) {
27719ce10c0bSKevin Wolf         return target_size;
27729ce10c0bSKevin Wolf     }
27739ce10c0bSKevin Wolf     target_size /= BDRV_SECTOR_SIZE;
27749ce10c0bSKevin Wolf 
2775d75cbb5eSPeter Lieven     for (;;) {
2776d75cbb5eSPeter Lieven         nb_sectors = target_size - sector_num;
2777d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2778d75cbb5eSPeter Lieven             return 0;
2779d75cbb5eSPeter Lieven         }
2780d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2781d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2782d75cbb5eSPeter Lieven         }
2783d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
27843d94ce60SPeter Lieven         if (ret < 0) {
27853d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
27863d94ce60SPeter Lieven                          sector_num, strerror(-ret));
27873d94ce60SPeter Lieven             return ret;
27883d94ce60SPeter Lieven         }
2789d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2790d75cbb5eSPeter Lieven             sector_num += n;
2791d75cbb5eSPeter Lieven             continue;
2792d75cbb5eSPeter Lieven         }
2793d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2794d75cbb5eSPeter Lieven         if (ret < 0) {
2795d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2796d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2797d75cbb5eSPeter Lieven             return ret;
2798d75cbb5eSPeter Lieven         }
2799d75cbb5eSPeter Lieven         sector_num += n;
2800d75cbb5eSPeter Lieven     }
2801d75cbb5eSPeter Lieven }
2802d75cbb5eSPeter Lieven 
2803a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
280483f64091Sbellard {
2805a3ef6571SKevin Wolf     QEMUIOVector qiov;
2806a3ef6571SKevin Wolf     struct iovec iov = {
2807a3ef6571SKevin Wolf         .iov_base = (void *)buf,
2808a3ef6571SKevin Wolf         .iov_len = bytes,
2809a3ef6571SKevin Wolf     };
28109a8c4cceSKevin Wolf     int ret;
281183f64091Sbellard 
2812a3ef6571SKevin Wolf     if (bytes < 0) {
2813a3ef6571SKevin Wolf         return -EINVAL;
281483f64091Sbellard     }
281583f64091Sbellard 
2816a3ef6571SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2817a3ef6571SKevin Wolf     ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
2818a3ef6571SKevin Wolf     if (ret < 0) {
28199a8c4cceSKevin Wolf         return ret;
282083f64091Sbellard     }
282183f64091Sbellard 
2822a3ef6571SKevin Wolf     return bytes;
282383f64091Sbellard }
282483f64091Sbellard 
28258d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
282683f64091Sbellard {
28279a8c4cceSKevin Wolf     int ret;
282883f64091Sbellard 
28298407d5d7SKevin Wolf     ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
28308d3b1a2dSKevin Wolf     if (ret < 0) {
28319a8c4cceSKevin Wolf         return ret;
28328d3b1a2dSKevin Wolf     }
28338d3b1a2dSKevin Wolf 
28348d3b1a2dSKevin Wolf     return qiov->size;
28358d3b1a2dSKevin Wolf }
28368d3b1a2dSKevin Wolf 
28378d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
28388407d5d7SKevin Wolf                 const void *buf, int bytes)
28398d3b1a2dSKevin Wolf {
28408d3b1a2dSKevin Wolf     QEMUIOVector qiov;
28418d3b1a2dSKevin Wolf     struct iovec iov = {
28428d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
28438407d5d7SKevin Wolf         .iov_len    = bytes,
28448d3b1a2dSKevin Wolf     };
28458d3b1a2dSKevin Wolf 
28468407d5d7SKevin Wolf     if (bytes < 0) {
28478407d5d7SKevin Wolf         return -EINVAL;
28488407d5d7SKevin Wolf     }
28498407d5d7SKevin Wolf 
28508d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
28518d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
285283f64091Sbellard }
285383f64091Sbellard 
2854f08145feSKevin Wolf /*
2855f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2856f08145feSKevin Wolf  * request (acts as a barrier)
2857f08145feSKevin Wolf  *
2858f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2859f08145feSKevin Wolf  */
2860f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2861f08145feSKevin Wolf     const void *buf, int count)
2862f08145feSKevin Wolf {
2863f08145feSKevin Wolf     int ret;
2864f08145feSKevin Wolf 
2865f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2866f08145feSKevin Wolf     if (ret < 0) {
2867f08145feSKevin Wolf         return ret;
2868f08145feSKevin Wolf     }
2869f08145feSKevin Wolf 
2870f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2871f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2872f08145feSKevin Wolf         bdrv_flush(bs);
2873f08145feSKevin Wolf     }
2874f08145feSKevin Wolf 
2875f08145feSKevin Wolf     return 0;
2876f08145feSKevin Wolf }
2877f08145feSKevin Wolf 
2878470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2879ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2880ab185921SStefan Hajnoczi {
2881ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2882ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2883ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2884ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2885ab185921SStefan Hajnoczi      */
2886ab185921SStefan Hajnoczi     void *bounce_buffer;
2887ab185921SStefan Hajnoczi 
288879c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2889ab185921SStefan Hajnoczi     struct iovec iov;
2890ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2891ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2892ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2893ab185921SStefan Hajnoczi     size_t skip_bytes;
2894ab185921SStefan Hajnoczi     int ret;
2895ab185921SStefan Hajnoczi 
2896ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2897ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2898ab185921SStefan Hajnoczi      */
2899343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2900ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2901ab185921SStefan Hajnoczi 
2902470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2903ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2904ab185921SStefan Hajnoczi 
2905ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2906ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2907ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2908ab185921SStefan Hajnoczi 
290979c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2910ab185921SStefan Hajnoczi                              &bounce_qiov);
2911ab185921SStefan Hajnoczi     if (ret < 0) {
2912ab185921SStefan Hajnoczi         goto err;
2913ab185921SStefan Hajnoczi     }
2914ab185921SStefan Hajnoczi 
291579c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
291679c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2917621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2918aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
291979c053bdSStefan Hajnoczi     } else {
2920f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2921f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2922f05fa4adSPaolo Bonzini          */
292379c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2924ab185921SStefan Hajnoczi                                   &bounce_qiov);
292579c053bdSStefan Hajnoczi     }
292679c053bdSStefan Hajnoczi 
2927ab185921SStefan Hajnoczi     if (ret < 0) {
2928ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2929ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2930ab185921SStefan Hajnoczi          * Simply report it in all cases.
2931ab185921SStefan Hajnoczi          */
2932ab185921SStefan Hajnoczi         goto err;
2933ab185921SStefan Hajnoczi     }
2934ab185921SStefan Hajnoczi 
2935ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
293603396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2937ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2938ab185921SStefan Hajnoczi 
2939ab185921SStefan Hajnoczi err:
2940ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2941ab185921SStefan Hajnoczi     return ret;
2942ab185921SStefan Hajnoczi }
2943ab185921SStefan Hajnoczi 
2944c5fbe571SStefan Hajnoczi /*
2945d0c7f642SKevin Wolf  * Forwards an already correctly aligned request to the BlockDriver. This
2946d0c7f642SKevin Wolf  * handles copy on read and zeroing after EOF; any other features must be
2947d0c7f642SKevin Wolf  * implemented by the caller.
2948c5fbe571SStefan Hajnoczi  */
2949d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
295065afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
2951ec746e10SKevin Wolf     int64_t align, QEMUIOVector *qiov, int flags)
2952da1fa91dSKevin Wolf {
2953da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2954dbffbdcfSStefan Hajnoczi     int ret;
2955da1fa91dSKevin Wolf 
2956d0c7f642SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
2957d0c7f642SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
2958da1fa91dSKevin Wolf 
2959d0c7f642SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2960d0c7f642SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
2961d0c7f642SKevin Wolf 
2962d0c7f642SKevin Wolf     /* Handle Copy on Read and associated serialisation */
2963470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
29647327145fSKevin Wolf         /* If we touch the same cluster it counts as an overlap.  This
29657327145fSKevin Wolf          * guarantees that allocating writes will be serialized and not race
29667327145fSKevin Wolf          * with each other for the same cluster.  For example, in copy-on-read
29677327145fSKevin Wolf          * it ensures that the CoR read and write operations are atomic and
29687327145fSKevin Wolf          * guest writes cannot interleave between them. */
29697327145fSKevin Wolf         mark_request_serialising(req, bdrv_get_cluster_size(bs));
2970470c0504SStefan Hajnoczi     }
2971470c0504SStefan Hajnoczi 
29722dbafdc0SKevin Wolf     wait_serialising_requests(req);
2973f4658285SStefan Hajnoczi 
2974470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2975ab185921SStefan Hajnoczi         int pnum;
2976ab185921SStefan Hajnoczi 
2977bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2978ab185921SStefan Hajnoczi         if (ret < 0) {
2979ab185921SStefan Hajnoczi             goto out;
2980ab185921SStefan Hajnoczi         }
2981ab185921SStefan Hajnoczi 
2982ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2983470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2984ab185921SStefan Hajnoczi             goto out;
2985ab185921SStefan Hajnoczi         }
2986ab185921SStefan Hajnoczi     }
2987ab185921SStefan Hajnoczi 
2988d0c7f642SKevin Wolf     /* Forward the request to the BlockDriver */
2989893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2990dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2991893a8f62SMORITA Kazutaka     } else {
2992893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2993893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2994893a8f62SMORITA Kazutaka 
2995893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2996893a8f62SMORITA Kazutaka         if (len < 0) {
2997893a8f62SMORITA Kazutaka             ret = len;
2998893a8f62SMORITA Kazutaka             goto out;
2999893a8f62SMORITA Kazutaka         }
3000893a8f62SMORITA Kazutaka 
3001d055a1feSFam Zheng         total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
30025f5bcd80SKevin Wolf         max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
30035f5bcd80SKevin Wolf                                   align >> BDRV_SECTOR_BITS);
3004893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
3005893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
3006893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
3007893a8f62SMORITA Kazutaka         } else {
3008893a8f62SMORITA Kazutaka             ret = 0;
3009893a8f62SMORITA Kazutaka         }
3010893a8f62SMORITA Kazutaka 
3011893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
3012893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
3013893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
3014893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
3015893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
3016893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
3017893a8f62SMORITA Kazutaka         }
3018893a8f62SMORITA Kazutaka     }
3019ab185921SStefan Hajnoczi 
3020ab185921SStefan Hajnoczi out:
3021dbffbdcfSStefan Hajnoczi     return ret;
3022da1fa91dSKevin Wolf }
3023da1fa91dSKevin Wolf 
3024d0c7f642SKevin Wolf /*
3025d0c7f642SKevin Wolf  * Handle a read request in coroutine context
3026d0c7f642SKevin Wolf  */
30271b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
30281b0288aeSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3029d0c7f642SKevin Wolf     BdrvRequestFlags flags)
3030d0c7f642SKevin Wolf {
3031d0c7f642SKevin Wolf     BlockDriver *drv = bs->drv;
303265afd211SKevin Wolf     BdrvTrackedRequest req;
303365afd211SKevin Wolf 
30341b0288aeSKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
30351b0288aeSKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
30361b0288aeSKevin Wolf     uint8_t *head_buf = NULL;
30371b0288aeSKevin Wolf     uint8_t *tail_buf = NULL;
30381b0288aeSKevin Wolf     QEMUIOVector local_qiov;
30391b0288aeSKevin Wolf     bool use_local_qiov = false;
3040d0c7f642SKevin Wolf     int ret;
3041d0c7f642SKevin Wolf 
3042d0c7f642SKevin Wolf     if (!drv) {
3043d0c7f642SKevin Wolf         return -ENOMEDIUM;
3044d0c7f642SKevin Wolf     }
30451b0288aeSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3046d0c7f642SKevin Wolf         return -EIO;
3047d0c7f642SKevin Wolf     }
3048d0c7f642SKevin Wolf 
3049d0c7f642SKevin Wolf     if (bs->copy_on_read) {
3050d0c7f642SKevin Wolf         flags |= BDRV_REQ_COPY_ON_READ;
3051d0c7f642SKevin Wolf     }
3052d0c7f642SKevin Wolf 
3053d0c7f642SKevin Wolf     /* throttling disk I/O */
3054d0c7f642SKevin Wolf     if (bs->io_limits_enabled) {
3055d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, false);
3056d0c7f642SKevin Wolf     }
3057d0c7f642SKevin Wolf 
30581b0288aeSKevin Wolf     /* Align read if necessary by padding qiov */
30591b0288aeSKevin Wolf     if (offset & (align - 1)) {
30601b0288aeSKevin Wolf         head_buf = qemu_blockalign(bs, align);
30611b0288aeSKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
30621b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
30631b0288aeSKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30641b0288aeSKevin Wolf         use_local_qiov = true;
30651b0288aeSKevin Wolf 
30661b0288aeSKevin Wolf         bytes += offset & (align - 1);
30671b0288aeSKevin Wolf         offset = offset & ~(align - 1);
30681b0288aeSKevin Wolf     }
30691b0288aeSKevin Wolf 
30701b0288aeSKevin Wolf     if ((offset + bytes) & (align - 1)) {
30711b0288aeSKevin Wolf         if (!use_local_qiov) {
30721b0288aeSKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
30731b0288aeSKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30741b0288aeSKevin Wolf             use_local_qiov = true;
30751b0288aeSKevin Wolf         }
30761b0288aeSKevin Wolf         tail_buf = qemu_blockalign(bs, align);
30771b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf,
30781b0288aeSKevin Wolf                        align - ((offset + bytes) & (align - 1)));
30791b0288aeSKevin Wolf 
30801b0288aeSKevin Wolf         bytes = ROUND_UP(bytes, align);
30811b0288aeSKevin Wolf     }
30821b0288aeSKevin Wolf 
308365afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, false);
3084ec746e10SKevin Wolf     ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
30851b0288aeSKevin Wolf                               use_local_qiov ? &local_qiov : qiov,
30861b0288aeSKevin Wolf                               flags);
308765afd211SKevin Wolf     tracked_request_end(&req);
30881b0288aeSKevin Wolf 
30891b0288aeSKevin Wolf     if (use_local_qiov) {
30901b0288aeSKevin Wolf         qemu_iovec_destroy(&local_qiov);
30911b0288aeSKevin Wolf         qemu_vfree(head_buf);
30921b0288aeSKevin Wolf         qemu_vfree(tail_buf);
30931b0288aeSKevin Wolf     }
30941b0288aeSKevin Wolf 
3095d0c7f642SKevin Wolf     return ret;
3096d0c7f642SKevin Wolf }
3097d0c7f642SKevin Wolf 
30981b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
30991b0288aeSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
31001b0288aeSKevin Wolf     BdrvRequestFlags flags)
31011b0288aeSKevin Wolf {
31021b0288aeSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
31031b0288aeSKevin Wolf         return -EINVAL;
31041b0288aeSKevin Wolf     }
31051b0288aeSKevin Wolf 
31061b0288aeSKevin Wolf     return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
31071b0288aeSKevin Wolf                              nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
31081b0288aeSKevin Wolf }
31091b0288aeSKevin Wolf 
3110c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
3111da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
3112da1fa91dSKevin Wolf {
3113c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
3114da1fa91dSKevin Wolf 
3115470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3116470c0504SStefan Hajnoczi }
3117470c0504SStefan Hajnoczi 
3118470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3119470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3120470c0504SStefan Hajnoczi {
3121470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3122470c0504SStefan Hajnoczi 
3123470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3124470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
3125c5fbe571SStefan Hajnoczi }
3126c5fbe571SStefan Hajnoczi 
3127c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
3128c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
3129c31cb707SPeter Lieven  */
3130c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
3131c31cb707SPeter Lieven 
3132f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
3133aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
3134f08f2ddaSStefan Hajnoczi {
3135f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3136f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3137c31cb707SPeter Lieven     struct iovec iov = {0};
3138c31cb707SPeter Lieven     int ret = 0;
3139f08f2ddaSStefan Hajnoczi 
3140c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3141c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3142621f0589SKevin Wolf 
3143c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3144c31cb707SPeter Lieven         int num = nb_sectors;
3145c31cb707SPeter Lieven 
3146b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3147b8d71c09SPaolo Bonzini          * to be aligned.
3148b8d71c09SPaolo Bonzini          */
3149b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3150b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3151b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3152b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3153c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3154c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3155b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3156b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3157b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3158b8d71c09SPaolo Bonzini                  */
3159b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3160b8d71c09SPaolo Bonzini             }
3161c31cb707SPeter Lieven         }
3162c31cb707SPeter Lieven 
3163c31cb707SPeter Lieven         /* limit request size */
3164c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3165c31cb707SPeter Lieven             num = max_write_zeroes;
3166c31cb707SPeter Lieven         }
3167c31cb707SPeter Lieven 
3168c31cb707SPeter Lieven         ret = -ENOTSUP;
3169f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3170f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3171c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3172f08f2ddaSStefan Hajnoczi         }
3173f08f2ddaSStefan Hajnoczi 
3174c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3175f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3176c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3177c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3178b8d71c09SPaolo Bonzini                 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
3179b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3180c31cb707SPeter Lieven             }
3181f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3182f08f2ddaSStefan Hajnoczi 
3183c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3184b8d71c09SPaolo Bonzini 
3185b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3186b8d71c09SPaolo Bonzini              * all future requests.
3187b8d71c09SPaolo Bonzini              */
3188b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3189b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3190b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3191b8d71c09SPaolo Bonzini             }
3192c31cb707SPeter Lieven         }
3193c31cb707SPeter Lieven 
3194c31cb707SPeter Lieven         sector_num += num;
3195c31cb707SPeter Lieven         nb_sectors -= num;
3196c31cb707SPeter Lieven     }
3197f08f2ddaSStefan Hajnoczi 
3198f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3199f08f2ddaSStefan Hajnoczi     return ret;
3200f08f2ddaSStefan Hajnoczi }
3201f08f2ddaSStefan Hajnoczi 
3202c5fbe571SStefan Hajnoczi /*
3203b404f720SKevin Wolf  * Forwards an already correctly aligned write request to the BlockDriver.
3204c5fbe571SStefan Hajnoczi  */
3205b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
320665afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
320765afd211SKevin Wolf     QEMUIOVector *qiov, int flags)
3208c5fbe571SStefan Hajnoczi {
3209c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
321028de2dcdSKevin Wolf     bool waited;
32116b7cb247SStefan Hajnoczi     int ret;
3212da1fa91dSKevin Wolf 
3213b404f720SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3214b404f720SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3215da1fa91dSKevin Wolf 
3216b404f720SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3217b404f720SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3218cc0681c4SBenoît Canet 
321928de2dcdSKevin Wolf     waited = wait_serialising_requests(req);
322028de2dcdSKevin Wolf     assert(!waited || !req->serialising);
3221af91f9a7SKevin Wolf     assert(req->overlap_offset <= offset);
3222af91f9a7SKevin Wolf     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
3223244eadefSKevin Wolf 
322465afd211SKevin Wolf     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
3225d616b224SStefan Hajnoczi 
3226d616b224SStefan Hajnoczi     if (ret < 0) {
3227d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3228d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
32299e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
3230aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3231f08f2ddaSStefan Hajnoczi     } else {
32329e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
32336b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3234f08f2ddaSStefan Hajnoczi     }
32359e1cb96dSKevin Wolf     BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
32366b7cb247SStefan Hajnoczi 
3237f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3238f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3239f05fa4adSPaolo Bonzini     }
3240f05fa4adSPaolo Bonzini 
32411755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3242da1fa91dSKevin Wolf 
3243da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
3244da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
3245da1fa91dSKevin Wolf     }
3246df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3247df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3248df2a6f29SPaolo Bonzini     }
3249da1fa91dSKevin Wolf 
32506b7cb247SStefan Hajnoczi     return ret;
3251da1fa91dSKevin Wolf }
3252da1fa91dSKevin Wolf 
3253b404f720SKevin Wolf /*
3254b404f720SKevin Wolf  * Handle a write request in coroutine context
3255b404f720SKevin Wolf  */
32566601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
32576601553eSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3258b404f720SKevin Wolf     BdrvRequestFlags flags)
3259b404f720SKevin Wolf {
326065afd211SKevin Wolf     BdrvTrackedRequest req;
32613b8242e0SKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
32623b8242e0SKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
32633b8242e0SKevin Wolf     uint8_t *head_buf = NULL;
32643b8242e0SKevin Wolf     uint8_t *tail_buf = NULL;
32653b8242e0SKevin Wolf     QEMUIOVector local_qiov;
32663b8242e0SKevin Wolf     bool use_local_qiov = false;
3267b404f720SKevin Wolf     int ret;
3268b404f720SKevin Wolf 
3269b404f720SKevin Wolf     if (!bs->drv) {
3270b404f720SKevin Wolf         return -ENOMEDIUM;
3271b404f720SKevin Wolf     }
3272b404f720SKevin Wolf     if (bs->read_only) {
3273b404f720SKevin Wolf         return -EACCES;
3274b404f720SKevin Wolf     }
32756601553eSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3276b404f720SKevin Wolf         return -EIO;
3277b404f720SKevin Wolf     }
3278b404f720SKevin Wolf 
3279b404f720SKevin Wolf     /* throttling disk I/O */
3280b404f720SKevin Wolf     if (bs->io_limits_enabled) {
3281d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, true);
3282b404f720SKevin Wolf     }
3283b404f720SKevin Wolf 
32843b8242e0SKevin Wolf     /*
32853b8242e0SKevin Wolf      * Align write if necessary by performing a read-modify-write cycle.
32863b8242e0SKevin Wolf      * Pad qiov with the read parts and be sure to have a tracked request not
32873b8242e0SKevin Wolf      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
32883b8242e0SKevin Wolf      */
328965afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, true);
32903b8242e0SKevin Wolf 
32913b8242e0SKevin Wolf     if (offset & (align - 1)) {
32923b8242e0SKevin Wolf         QEMUIOVector head_qiov;
32933b8242e0SKevin Wolf         struct iovec head_iov;
32943b8242e0SKevin Wolf 
32953b8242e0SKevin Wolf         mark_request_serialising(&req, align);
32963b8242e0SKevin Wolf         wait_serialising_requests(&req);
32973b8242e0SKevin Wolf 
32983b8242e0SKevin Wolf         head_buf = qemu_blockalign(bs, align);
32993b8242e0SKevin Wolf         head_iov = (struct iovec) {
33003b8242e0SKevin Wolf             .iov_base   = head_buf,
33013b8242e0SKevin Wolf             .iov_len    = align,
33023b8242e0SKevin Wolf         };
33033b8242e0SKevin Wolf         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
33043b8242e0SKevin Wolf 
33059e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
33063b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
33073b8242e0SKevin Wolf                                   align, &head_qiov, 0);
33083b8242e0SKevin Wolf         if (ret < 0) {
33093b8242e0SKevin Wolf             goto fail;
33103b8242e0SKevin Wolf         }
33119e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
33123b8242e0SKevin Wolf 
33133b8242e0SKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
33143b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
33153b8242e0SKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
33163b8242e0SKevin Wolf         use_local_qiov = true;
33173b8242e0SKevin Wolf 
33183b8242e0SKevin Wolf         bytes += offset & (align - 1);
33193b8242e0SKevin Wolf         offset = offset & ~(align - 1);
33203b8242e0SKevin Wolf     }
33213b8242e0SKevin Wolf 
33223b8242e0SKevin Wolf     if ((offset + bytes) & (align - 1)) {
33233b8242e0SKevin Wolf         QEMUIOVector tail_qiov;
33243b8242e0SKevin Wolf         struct iovec tail_iov;
33253b8242e0SKevin Wolf         size_t tail_bytes;
332628de2dcdSKevin Wolf         bool waited;
33273b8242e0SKevin Wolf 
33283b8242e0SKevin Wolf         mark_request_serialising(&req, align);
332928de2dcdSKevin Wolf         waited = wait_serialising_requests(&req);
333028de2dcdSKevin Wolf         assert(!waited || !use_local_qiov);
33313b8242e0SKevin Wolf 
33323b8242e0SKevin Wolf         tail_buf = qemu_blockalign(bs, align);
33333b8242e0SKevin Wolf         tail_iov = (struct iovec) {
33343b8242e0SKevin Wolf             .iov_base   = tail_buf,
33353b8242e0SKevin Wolf             .iov_len    = align,
33363b8242e0SKevin Wolf         };
33373b8242e0SKevin Wolf         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
33383b8242e0SKevin Wolf 
33399e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
33403b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
33413b8242e0SKevin Wolf                                   align, &tail_qiov, 0);
33423b8242e0SKevin Wolf         if (ret < 0) {
33433b8242e0SKevin Wolf             goto fail;
33443b8242e0SKevin Wolf         }
33459e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
33463b8242e0SKevin Wolf 
33473b8242e0SKevin Wolf         if (!use_local_qiov) {
33483b8242e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
33493b8242e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
33503b8242e0SKevin Wolf             use_local_qiov = true;
33513b8242e0SKevin Wolf         }
33523b8242e0SKevin Wolf 
33533b8242e0SKevin Wolf         tail_bytes = (offset + bytes) & (align - 1);
33543b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
33553b8242e0SKevin Wolf 
33563b8242e0SKevin Wolf         bytes = ROUND_UP(bytes, align);
33573b8242e0SKevin Wolf     }
33583b8242e0SKevin Wolf 
33593b8242e0SKevin Wolf     ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
33603b8242e0SKevin Wolf                                use_local_qiov ? &local_qiov : qiov,
33613b8242e0SKevin Wolf                                flags);
33623b8242e0SKevin Wolf 
33633b8242e0SKevin Wolf fail:
336465afd211SKevin Wolf     tracked_request_end(&req);
3365b404f720SKevin Wolf 
33663b8242e0SKevin Wolf     if (use_local_qiov) {
33673b8242e0SKevin Wolf         qemu_iovec_destroy(&local_qiov);
336899c4a85cSKevin Wolf     }
33693b8242e0SKevin Wolf     qemu_vfree(head_buf);
33703b8242e0SKevin Wolf     qemu_vfree(tail_buf);
33713b8242e0SKevin Wolf 
3372b404f720SKevin Wolf     return ret;
3373b404f720SKevin Wolf }
3374b404f720SKevin Wolf 
33756601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
33766601553eSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
33776601553eSKevin Wolf     BdrvRequestFlags flags)
33786601553eSKevin Wolf {
33796601553eSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
33806601553eSKevin Wolf         return -EINVAL;
33816601553eSKevin Wolf     }
33826601553eSKevin Wolf 
33836601553eSKevin Wolf     return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
33846601553eSKevin Wolf                               nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
33856601553eSKevin Wolf }
33866601553eSKevin Wolf 
3387c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3388c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3389c5fbe571SStefan Hajnoczi {
3390c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3391c5fbe571SStefan Hajnoczi 
3392f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3393f08f2ddaSStefan Hajnoczi }
3394f08f2ddaSStefan Hajnoczi 
3395f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3396aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3397aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3398f08f2ddaSStefan Hajnoczi {
339994d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3400f08f2ddaSStefan Hajnoczi 
3401d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3402d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3403d32f35cbSPeter Lieven     }
3404d32f35cbSPeter Lieven 
3405f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3406aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3407c5fbe571SStefan Hajnoczi }
3408c5fbe571SStefan Hajnoczi 
340983f64091Sbellard /**
341083f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
341183f64091Sbellard  */
341283f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
341383f64091Sbellard {
341483f64091Sbellard     BlockDriver *drv = bs->drv;
341551762288SStefan Hajnoczi     int ret;
341683f64091Sbellard     if (!drv)
341719cb3738Sbellard         return -ENOMEDIUM;
341883f64091Sbellard     if (!drv->bdrv_truncate)
341983f64091Sbellard         return -ENOTSUP;
342059f2689dSNaphtali Sprei     if (bs->read_only)
342159f2689dSNaphtali Sprei         return -EACCES;
34228591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
34238591675fSMarcelo Tosatti         return -EBUSY;
342451762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
342551762288SStefan Hajnoczi     if (ret == 0) {
342651762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3427145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
342851762288SStefan Hajnoczi     }
342951762288SStefan Hajnoczi     return ret;
343083f64091Sbellard }
343183f64091Sbellard 
343283f64091Sbellard /**
34334a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
34344a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
34354a1d5e1fSFam Zheng  */
34364a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
34374a1d5e1fSFam Zheng {
34384a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
34394a1d5e1fSFam Zheng     if (!drv) {
34404a1d5e1fSFam Zheng         return -ENOMEDIUM;
34414a1d5e1fSFam Zheng     }
34424a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
34434a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
34444a1d5e1fSFam Zheng     }
34454a1d5e1fSFam Zheng     if (bs->file) {
34464a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
34474a1d5e1fSFam Zheng     }
34484a1d5e1fSFam Zheng     return -ENOTSUP;
34494a1d5e1fSFam Zheng }
34504a1d5e1fSFam Zheng 
34514a1d5e1fSFam Zheng /**
345283f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
345383f64091Sbellard  */
345483f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
345583f64091Sbellard {
345683f64091Sbellard     BlockDriver *drv = bs->drv;
345783f64091Sbellard     if (!drv)
345819cb3738Sbellard         return -ENOMEDIUM;
345951762288SStefan Hajnoczi 
3460b94a2610SKevin Wolf     if (drv->has_variable_length) {
3461b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3462b94a2610SKevin Wolf         if (ret < 0) {
3463b94a2610SKevin Wolf             return ret;
3464fc01f7e7Sbellard         }
346546a4e4e6SStefan Hajnoczi     }
346646a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
346746a4e4e6SStefan Hajnoczi }
3468fc01f7e7Sbellard 
346919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
347096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3471fc01f7e7Sbellard {
347219cb3738Sbellard     int64_t length;
347319cb3738Sbellard     length = bdrv_getlength(bs);
347419cb3738Sbellard     if (length < 0)
347519cb3738Sbellard         length = 0;
347619cb3738Sbellard     else
34776ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
347819cb3738Sbellard     *nb_sectors_ptr = length;
3479fc01f7e7Sbellard }
3480cf98951bSbellard 
3481ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3482ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3483abd7f68dSMarkus Armbruster {
3484abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3485abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3486abd7f68dSMarkus Armbruster }
3487abd7f68dSMarkus Armbruster 
34881ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3489abd7f68dSMarkus Armbruster {
3490abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3491abd7f68dSMarkus Armbruster }
3492abd7f68dSMarkus Armbruster 
34933e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
34943e1caa5fSPaolo Bonzini {
34953e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
34963e1caa5fSPaolo Bonzini 
34973e1caa5fSPaolo Bonzini     switch (on_err) {
34983e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
34993e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
35003e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
35013e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
35023e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
35033e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
35043e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
35053e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
35063e1caa5fSPaolo Bonzini     default:
35073e1caa5fSPaolo Bonzini         abort();
35083e1caa5fSPaolo Bonzini     }
35093e1caa5fSPaolo Bonzini }
35103e1caa5fSPaolo Bonzini 
35113e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
35123e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
35133e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
35143e1caa5fSPaolo Bonzini  */
35153e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
35163e1caa5fSPaolo Bonzini                        bool is_read, int error)
35173e1caa5fSPaolo Bonzini {
35183e1caa5fSPaolo Bonzini     assert(error >= 0);
351932c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
35203e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
35213e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
35223e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
35233e1caa5fSPaolo Bonzini     }
35243e1caa5fSPaolo Bonzini }
35253e1caa5fSPaolo Bonzini 
3526b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3527b338082bSbellard {
3528b338082bSbellard     return bs->read_only;
3529b338082bSbellard }
3530b338082bSbellard 
3531985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3532985a03b0Sths {
3533985a03b0Sths     return bs->sg;
3534985a03b0Sths }
3535985a03b0Sths 
3536e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3537e900a7b7SChristoph Hellwig {
3538e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3539e900a7b7SChristoph Hellwig }
3540e900a7b7SChristoph Hellwig 
3541425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3542425b0148SPaolo Bonzini {
3543425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
354455b110f2SJeff Cody 
354555b110f2SJeff Cody     /* so a reopen() will preserve wce */
354655b110f2SJeff Cody     if (wce) {
354755b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
354855b110f2SJeff Cody     } else {
354955b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
355055b110f2SJeff Cody     }
3551425b0148SPaolo Bonzini }
3552425b0148SPaolo Bonzini 
3553ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3554ea2384d3Sbellard {
3555ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3556ea2384d3Sbellard         return 1;
3557ea2384d3Sbellard     return bs->encrypted;
3558ea2384d3Sbellard }
3559ea2384d3Sbellard 
3560c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3561c0f4ce77Saliguori {
3562c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3563c0f4ce77Saliguori 
3564c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3565c0f4ce77Saliguori         return 1;
3566c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3567c0f4ce77Saliguori }
3568c0f4ce77Saliguori 
3569ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3570ea2384d3Sbellard {
3571ea2384d3Sbellard     int ret;
3572ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3573ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3574ea2384d3Sbellard         if (ret < 0)
3575ea2384d3Sbellard             return ret;
3576ea2384d3Sbellard         if (!bs->encrypted)
3577ea2384d3Sbellard             return 0;
3578ea2384d3Sbellard     }
3579fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3580fd04a2aeSShahar Havivi         return -EINVAL;
3581fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3582fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3583fd04a2aeSShahar Havivi     }
3584c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3585bb5fc20fSaliguori     if (ret < 0) {
3586bb5fc20fSaliguori         bs->valid_key = 0;
3587bb5fc20fSaliguori     } else if (!bs->valid_key) {
3588bb5fc20fSaliguori         bs->valid_key = 1;
3589bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
35907d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3591bb5fc20fSaliguori     }
3592c0f4ce77Saliguori     return ret;
3593ea2384d3Sbellard }
3594ea2384d3Sbellard 
3595f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3596ea2384d3Sbellard {
3597f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3598ea2384d3Sbellard }
3599ea2384d3Sbellard 
3600ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3601ea2384d3Sbellard                          void *opaque)
3602ea2384d3Sbellard {
3603ea2384d3Sbellard     BlockDriver *drv;
3604*e855e4fbSJeff Cody     int count = 0;
3605*e855e4fbSJeff Cody     const char **formats = NULL;
3606ea2384d3Sbellard 
36078a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3608*e855e4fbSJeff Cody         if (drv->format_name) {
3609*e855e4fbSJeff Cody             bool found = false;
3610*e855e4fbSJeff Cody             int i = count;
3611*e855e4fbSJeff Cody             while (formats && i && !found) {
3612*e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
3613*e855e4fbSJeff Cody             }
3614*e855e4fbSJeff Cody 
3615*e855e4fbSJeff Cody             if (!found) {
3616*e855e4fbSJeff Cody                 formats = g_realloc(formats, (count + 1) * sizeof(char *));
3617*e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
3618ea2384d3Sbellard                 it(opaque, drv->format_name);
3619ea2384d3Sbellard             }
3620ea2384d3Sbellard         }
3621*e855e4fbSJeff Cody     }
3622*e855e4fbSJeff Cody     g_free(formats);
3623*e855e4fbSJeff Cody }
3624ea2384d3Sbellard 
3625dc364f4cSBenoît Canet /* This function is to find block backend bs */
3626b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3627b338082bSbellard {
3628b338082bSbellard     BlockDriverState *bs;
3629b338082bSbellard 
3630dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
36311b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3632b338082bSbellard             return bs;
3633b338082bSbellard         }
36341b7bdbc1SStefan Hajnoczi     }
3635b338082bSbellard     return NULL;
3636b338082bSbellard }
3637b338082bSbellard 
3638dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3639dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3640dc364f4cSBenoît Canet {
3641dc364f4cSBenoît Canet     BlockDriverState *bs;
3642dc364f4cSBenoît Canet 
3643dc364f4cSBenoît Canet     assert(node_name);
3644dc364f4cSBenoît Canet 
3645dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3646dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3647dc364f4cSBenoît Canet             return bs;
3648dc364f4cSBenoît Canet         }
3649dc364f4cSBenoît Canet     }
3650dc364f4cSBenoît Canet     return NULL;
3651dc364f4cSBenoît Canet }
3652dc364f4cSBenoît Canet 
3653c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3654c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3655c13163fbSBenoît Canet {
3656c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3657c13163fbSBenoît Canet     BlockDriverState *bs;
3658c13163fbSBenoît Canet 
3659c13163fbSBenoît Canet     list = NULL;
3660c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3661c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3662c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3663c13163fbSBenoît Canet         entry->next = list;
3664c13163fbSBenoît Canet         list = entry;
3665c13163fbSBenoît Canet     }
3666c13163fbSBenoît Canet 
3667c13163fbSBenoît Canet     return list;
3668c13163fbSBenoît Canet }
3669c13163fbSBenoît Canet 
367012d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
367112d3ba82SBenoît Canet                                  const char *node_name,
367212d3ba82SBenoît Canet                                  Error **errp)
367312d3ba82SBenoît Canet {
367412d3ba82SBenoît Canet     BlockDriverState *bs = NULL;
367512d3ba82SBenoît Canet 
367612d3ba82SBenoît Canet     if (device) {
367712d3ba82SBenoît Canet         bs = bdrv_find(device);
367812d3ba82SBenoît Canet 
3679dd67fa50SBenoît Canet         if (bs) {
368012d3ba82SBenoît Canet             return bs;
368112d3ba82SBenoît Canet         }
3682dd67fa50SBenoît Canet     }
368312d3ba82SBenoît Canet 
3684dd67fa50SBenoît Canet     if (node_name) {
368512d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
368612d3ba82SBenoît Canet 
3687dd67fa50SBenoît Canet         if (bs) {
3688dd67fa50SBenoît Canet             return bs;
3689dd67fa50SBenoît Canet         }
369012d3ba82SBenoît Canet     }
369112d3ba82SBenoît Canet 
3692dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
3693dd67fa50SBenoît Canet                      device ? device : "",
3694dd67fa50SBenoît Canet                      node_name ? node_name : "");
3695dd67fa50SBenoît Canet     return NULL;
369612d3ba82SBenoît Canet }
369712d3ba82SBenoît Canet 
36982f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
36992f399b0aSMarkus Armbruster {
37002f399b0aSMarkus Armbruster     if (!bs) {
37012f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
37022f399b0aSMarkus Armbruster     }
3703dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
37042f399b0aSMarkus Armbruster }
37052f399b0aSMarkus Armbruster 
370651de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
370781d0912dSbellard {
370881d0912dSbellard     BlockDriverState *bs;
370981d0912dSbellard 
3710dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
371151de9760Saliguori         it(opaque, bs);
371281d0912dSbellard     }
371381d0912dSbellard }
371481d0912dSbellard 
3715ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3716ea2384d3Sbellard {
3717ea2384d3Sbellard     return bs->device_name;
3718ea2384d3Sbellard }
3719ea2384d3Sbellard 
3720c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3721c8433287SMarkus Armbruster {
3722c8433287SMarkus Armbruster     return bs->open_flags;
3723c8433287SMarkus Armbruster }
3724c8433287SMarkus Armbruster 
3725f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3726c6ca28d6Saliguori {
3727c6ca28d6Saliguori     BlockDriverState *bs;
3728f0f0fdfeSKevin Wolf     int result = 0;
3729c6ca28d6Saliguori 
3730dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3731f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3732f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3733f0f0fdfeSKevin Wolf             result = ret;
3734c6ca28d6Saliguori         }
37351b7bdbc1SStefan Hajnoczi     }
3736c6ca28d6Saliguori 
3737f0f0fdfeSKevin Wolf     return result;
3738f0f0fdfeSKevin Wolf }
3739f0f0fdfeSKevin Wolf 
37403ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
37413ac21627SPeter Lieven {
37423ac21627SPeter Lieven     return 1;
37433ac21627SPeter Lieven }
37443ac21627SPeter Lieven 
3745f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3746f2feebbdSKevin Wolf {
3747f2feebbdSKevin Wolf     assert(bs->drv);
3748f2feebbdSKevin Wolf 
374911212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
375011212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
375111212d8fSPaolo Bonzini     if (bs->backing_hd) {
375211212d8fSPaolo Bonzini         return 0;
375311212d8fSPaolo Bonzini     }
3754336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3755336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3756f2feebbdSKevin Wolf     }
3757f2feebbdSKevin Wolf 
37583ac21627SPeter Lieven     /* safe default */
37593ac21627SPeter Lieven     return 0;
3760f2feebbdSKevin Wolf }
3761f2feebbdSKevin Wolf 
37624ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
37634ce78691SPeter Lieven {
37644ce78691SPeter Lieven     BlockDriverInfo bdi;
37654ce78691SPeter Lieven 
37664ce78691SPeter Lieven     if (bs->backing_hd) {
37674ce78691SPeter Lieven         return false;
37684ce78691SPeter Lieven     }
37694ce78691SPeter Lieven 
37704ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
37714ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
37724ce78691SPeter Lieven     }
37734ce78691SPeter Lieven 
37744ce78691SPeter Lieven     return false;
37754ce78691SPeter Lieven }
37764ce78691SPeter Lieven 
37774ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
37784ce78691SPeter Lieven {
37794ce78691SPeter Lieven     BlockDriverInfo bdi;
37804ce78691SPeter Lieven 
37814ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
37824ce78691SPeter Lieven         return false;
37834ce78691SPeter Lieven     }
37844ce78691SPeter Lieven 
37854ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
37864ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
37874ce78691SPeter Lieven     }
37884ce78691SPeter Lieven 
37894ce78691SPeter Lieven     return false;
37904ce78691SPeter Lieven }
37914ce78691SPeter Lieven 
3792b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3793376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3794b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3795376ae3f1SStefan Hajnoczi     int64_t sector_num;
3796376ae3f1SStefan Hajnoczi     int nb_sectors;
3797376ae3f1SStefan Hajnoczi     int *pnum;
3798b6b8a333SPaolo Bonzini     int64_t ret;
3799376ae3f1SStefan Hajnoczi     bool done;
3800b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3801376ae3f1SStefan Hajnoczi 
3802f58c7b35Sths /*
3803f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3804f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3805f58c7b35Sths  * hence all their sectors are reported as allocated.
3806f58c7b35Sths  *
3807bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3808bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3809bd9533e3SStefan Hajnoczi  *
3810f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3811f58c7b35Sths  * the specified sector) that are known to be in the same
3812f58c7b35Sths  * allocated/unallocated state.
3813f58c7b35Sths  *
3814bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3815bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3816f58c7b35Sths  */
3817b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3818bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3819060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3820f58c7b35Sths {
3821617ccb46SPaolo Bonzini     int64_t length;
3822f58c7b35Sths     int64_t n;
38235daa74a6SPaolo Bonzini     int64_t ret, ret2;
3824bd9533e3SStefan Hajnoczi 
3825617ccb46SPaolo Bonzini     length = bdrv_getlength(bs);
3826617ccb46SPaolo Bonzini     if (length < 0) {
3827617ccb46SPaolo Bonzini         return length;
3828617ccb46SPaolo Bonzini     }
3829617ccb46SPaolo Bonzini 
3830617ccb46SPaolo Bonzini     if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
38316aebab14SStefan Hajnoczi         *pnum = 0;
38326aebab14SStefan Hajnoczi         return 0;
38336aebab14SStefan Hajnoczi     }
3834bd9533e3SStefan Hajnoczi 
38356aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3836bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3837bd9533e3SStefan Hajnoczi         nb_sectors = n;
3838bd9533e3SStefan Hajnoczi     }
3839bd9533e3SStefan Hajnoczi 
3840b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3841bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3842918e92d7SPaolo Bonzini         ret = BDRV_BLOCK_DATA;
3843918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3844918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3845918e92d7SPaolo Bonzini         }
3846918e92d7SPaolo Bonzini         return ret;
38476aebab14SStefan Hajnoczi     }
38486aebab14SStefan Hajnoczi 
3849415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3850415b5b01SPaolo Bonzini     if (ret < 0) {
38513e0a233dSPeter Lieven         *pnum = 0;
3852415b5b01SPaolo Bonzini         return ret;
3853415b5b01SPaolo Bonzini     }
3854415b5b01SPaolo Bonzini 
385592bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
385692bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
385792bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
385892bc50a5SPeter Lieven                                      *pnum, pnum);
385992bc50a5SPeter Lieven     }
386092bc50a5SPeter Lieven 
3861c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3862c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
3863415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
38641f9db224SPeter Lieven         } else if (bs->backing_hd) {
3865f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
3866f0ad5712SPaolo Bonzini             int64_t length2 = bdrv_getlength(bs2);
3867f0ad5712SPaolo Bonzini             if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3868f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3869f0ad5712SPaolo Bonzini             }
3870f0ad5712SPaolo Bonzini         }
3871415b5b01SPaolo Bonzini     }
38725daa74a6SPaolo Bonzini 
38735daa74a6SPaolo Bonzini     if (bs->file &&
38745daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
38755daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
38765daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
38775daa74a6SPaolo Bonzini                                         *pnum, pnum);
38785daa74a6SPaolo Bonzini         if (ret2 >= 0) {
38795daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
38805daa74a6SPaolo Bonzini              * is useful but not necessary.
38815daa74a6SPaolo Bonzini              */
38825daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
38835daa74a6SPaolo Bonzini         }
38845daa74a6SPaolo Bonzini     }
38855daa74a6SPaolo Bonzini 
3886415b5b01SPaolo Bonzini     return ret;
3887060f51c9SStefan Hajnoczi }
3888060f51c9SStefan Hajnoczi 
3889b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3890b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3891060f51c9SStefan Hajnoczi {
3892b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3893060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3894060f51c9SStefan Hajnoczi 
3895b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3896060f51c9SStefan Hajnoczi                                          data->pnum);
3897060f51c9SStefan Hajnoczi     data->done = true;
3898060f51c9SStefan Hajnoczi }
3899060f51c9SStefan Hajnoczi 
3900060f51c9SStefan Hajnoczi /*
3901b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3902060f51c9SStefan Hajnoczi  *
3903b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
3904060f51c9SStefan Hajnoczi  */
3905b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3906b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
3907060f51c9SStefan Hajnoczi {
3908376ae3f1SStefan Hajnoczi     Coroutine *co;
3909b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
3910376ae3f1SStefan Hajnoczi         .bs = bs,
3911376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3912376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3913376ae3f1SStefan Hajnoczi         .pnum = pnum,
3914376ae3f1SStefan Hajnoczi         .done = false,
3915376ae3f1SStefan Hajnoczi     };
3916376ae3f1SStefan Hajnoczi 
3917bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
3918bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
3919b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
3920bdad13b9SPaolo Bonzini     } else {
3921b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
3922376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
3923376ae3f1SStefan Hajnoczi         while (!data.done) {
3924376ae3f1SStefan Hajnoczi             qemu_aio_wait();
3925376ae3f1SStefan Hajnoczi         }
3926bdad13b9SPaolo Bonzini     }
3927376ae3f1SStefan Hajnoczi     return data.ret;
3928376ae3f1SStefan Hajnoczi }
3929f58c7b35Sths 
3930b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
3931b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
3932b6b8a333SPaolo Bonzini {
39334333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
39344333bb71SPaolo Bonzini     if (ret < 0) {
39354333bb71SPaolo Bonzini         return ret;
39364333bb71SPaolo Bonzini     }
39374333bb71SPaolo Bonzini     return
39384333bb71SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) ||
39394333bb71SPaolo Bonzini         ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
3940b6b8a333SPaolo Bonzini }
3941b6b8a333SPaolo Bonzini 
3942188a7bbfSPaolo Bonzini /*
3943188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3944188a7bbfSPaolo Bonzini  *
3945188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3946188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3947188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3948188a7bbfSPaolo Bonzini  *
3949188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3950188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3951188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3952188a7bbfSPaolo Bonzini  *
3953188a7bbfSPaolo Bonzini  */
39544f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
3955188a7bbfSPaolo Bonzini                             BlockDriverState *base,
3956188a7bbfSPaolo Bonzini                             int64_t sector_num,
3957188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
3958188a7bbfSPaolo Bonzini {
3959188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3960188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3961188a7bbfSPaolo Bonzini 
3962188a7bbfSPaolo Bonzini     intermediate = top;
3963188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3964188a7bbfSPaolo Bonzini         int pnum_inter;
3965bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
3966188a7bbfSPaolo Bonzini                                 &pnum_inter);
3967188a7bbfSPaolo Bonzini         if (ret < 0) {
3968188a7bbfSPaolo Bonzini             return ret;
3969188a7bbfSPaolo Bonzini         } else if (ret) {
3970188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3971188a7bbfSPaolo Bonzini             return 1;
3972188a7bbfSPaolo Bonzini         }
3973188a7bbfSPaolo Bonzini 
3974188a7bbfSPaolo Bonzini         /*
3975188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3976188a7bbfSPaolo Bonzini          * might have
3977188a7bbfSPaolo Bonzini          *
3978188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3979188a7bbfSPaolo Bonzini          */
398063ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
398163ba17d3SVishvananda Ishaya             (intermediate == top ||
398263ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3983188a7bbfSPaolo Bonzini             n = pnum_inter;
3984188a7bbfSPaolo Bonzini         }
3985188a7bbfSPaolo Bonzini 
3986188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3987188a7bbfSPaolo Bonzini     }
3988188a7bbfSPaolo Bonzini 
3989188a7bbfSPaolo Bonzini     *pnum = n;
3990188a7bbfSPaolo Bonzini     return 0;
3991188a7bbfSPaolo Bonzini }
3992188a7bbfSPaolo Bonzini 
3993045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3994045df330Saliguori {
3995045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3996045df330Saliguori         return bs->backing_file;
3997045df330Saliguori     else if (bs->encrypted)
3998045df330Saliguori         return bs->filename;
3999045df330Saliguori     else
4000045df330Saliguori         return NULL;
4001045df330Saliguori }
4002045df330Saliguori 
400383f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
400483f64091Sbellard                                char *filename, int filename_size)
400583f64091Sbellard {
400683f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
400783f64091Sbellard }
400883f64091Sbellard 
4009faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
4010faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
4011faea38e7Sbellard {
4012faea38e7Sbellard     BlockDriver *drv = bs->drv;
4013faea38e7Sbellard     if (!drv)
401419cb3738Sbellard         return -ENOMEDIUM;
4015faea38e7Sbellard     if (!drv->bdrv_write_compressed)
4016faea38e7Sbellard         return -ENOTSUP;
4017fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
4018fbb7b4e0SKevin Wolf         return -EIO;
40197cd1e32aSlirans@il.ibm.com 
4020e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
40217cd1e32aSlirans@il.ibm.com 
4022faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
4023faea38e7Sbellard }
4024faea38e7Sbellard 
4025faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4026faea38e7Sbellard {
4027faea38e7Sbellard     BlockDriver *drv = bs->drv;
4028faea38e7Sbellard     if (!drv)
402919cb3738Sbellard         return -ENOMEDIUM;
4030faea38e7Sbellard     if (!drv->bdrv_get_info)
4031faea38e7Sbellard         return -ENOTSUP;
4032faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
4033faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
4034faea38e7Sbellard }
4035faea38e7Sbellard 
4036eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
4037eae041feSMax Reitz {
4038eae041feSMax Reitz     BlockDriver *drv = bs->drv;
4039eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
4040eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
4041eae041feSMax Reitz     }
4042eae041feSMax Reitz     return NULL;
4043eae041feSMax Reitz }
4044eae041feSMax Reitz 
404545566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
404645566e9cSChristoph Hellwig                       int64_t pos, int size)
4047178e08a5Saliguori {
4048cf8074b3SKevin Wolf     QEMUIOVector qiov;
4049cf8074b3SKevin Wolf     struct iovec iov = {
4050cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
4051cf8074b3SKevin Wolf         .iov_len    = size,
4052cf8074b3SKevin Wolf     };
4053cf8074b3SKevin Wolf 
4054cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
4055cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
4056cf8074b3SKevin Wolf }
4057cf8074b3SKevin Wolf 
4058cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
4059cf8074b3SKevin Wolf {
4060178e08a5Saliguori     BlockDriver *drv = bs->drv;
4061cf8074b3SKevin Wolf 
4062cf8074b3SKevin Wolf     if (!drv) {
4063178e08a5Saliguori         return -ENOMEDIUM;
4064cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
4065cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
4066cf8074b3SKevin Wolf     } else if (bs->file) {
4067cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
4068cf8074b3SKevin Wolf     }
4069cf8074b3SKevin Wolf 
40707cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4071178e08a5Saliguori }
4072178e08a5Saliguori 
407345566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
407445566e9cSChristoph Hellwig                       int64_t pos, int size)
4075178e08a5Saliguori {
4076178e08a5Saliguori     BlockDriver *drv = bs->drv;
4077178e08a5Saliguori     if (!drv)
4078178e08a5Saliguori         return -ENOMEDIUM;
40797cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
408045566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
40817cdb1f6dSMORITA Kazutaka     if (bs->file)
40827cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
40837cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4084178e08a5Saliguori }
4085178e08a5Saliguori 
40868b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
40878b9b0cc2SKevin Wolf {
4088bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
40898b9b0cc2SKevin Wolf         return;
40908b9b0cc2SKevin Wolf     }
40918b9b0cc2SKevin Wolf 
4092bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
409341c695c7SKevin Wolf }
40948b9b0cc2SKevin Wolf 
409541c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
409641c695c7SKevin Wolf                           const char *tag)
409741c695c7SKevin Wolf {
409841c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
409941c695c7SKevin Wolf         bs = bs->file;
410041c695c7SKevin Wolf     }
410141c695c7SKevin Wolf 
410241c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
410341c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
410441c695c7SKevin Wolf     }
410541c695c7SKevin Wolf 
410641c695c7SKevin Wolf     return -ENOTSUP;
410741c695c7SKevin Wolf }
410841c695c7SKevin Wolf 
41094cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
41104cc70e93SFam Zheng {
41114cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
41124cc70e93SFam Zheng         bs = bs->file;
41134cc70e93SFam Zheng     }
41144cc70e93SFam Zheng 
41154cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
41164cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
41174cc70e93SFam Zheng     }
41184cc70e93SFam Zheng 
41194cc70e93SFam Zheng     return -ENOTSUP;
41204cc70e93SFam Zheng }
41214cc70e93SFam Zheng 
412241c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
412341c695c7SKevin Wolf {
4124938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
412541c695c7SKevin Wolf         bs = bs->file;
412641c695c7SKevin Wolf     }
412741c695c7SKevin Wolf 
412841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
412941c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
413041c695c7SKevin Wolf     }
413141c695c7SKevin Wolf 
413241c695c7SKevin Wolf     return -ENOTSUP;
413341c695c7SKevin Wolf }
413441c695c7SKevin Wolf 
413541c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
413641c695c7SKevin Wolf {
413741c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
413841c695c7SKevin Wolf         bs = bs->file;
413941c695c7SKevin Wolf     }
414041c695c7SKevin Wolf 
414141c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
414241c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
414341c695c7SKevin Wolf     }
414441c695c7SKevin Wolf 
414541c695c7SKevin Wolf     return false;
41468b9b0cc2SKevin Wolf }
41478b9b0cc2SKevin Wolf 
4148199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
4149199630b6SBlue Swirl {
4150199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4151199630b6SBlue Swirl }
4152199630b6SBlue Swirl 
4153b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
4154b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
4155b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
4156b1b1d783SJeff Cody  * the CWD rather than the chain. */
4157e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4158e8a6bb9cSMarcelo Tosatti         const char *backing_file)
4159e8a6bb9cSMarcelo Tosatti {
4160b1b1d783SJeff Cody     char *filename_full = NULL;
4161b1b1d783SJeff Cody     char *backing_file_full = NULL;
4162b1b1d783SJeff Cody     char *filename_tmp = NULL;
4163b1b1d783SJeff Cody     int is_protocol = 0;
4164b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
4165b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
4166b1b1d783SJeff Cody 
4167b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
4168e8a6bb9cSMarcelo Tosatti         return NULL;
4169e8a6bb9cSMarcelo Tosatti     }
4170e8a6bb9cSMarcelo Tosatti 
4171b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
4172b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
4173b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
4174b1b1d783SJeff Cody 
4175b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
4176b1b1d783SJeff Cody 
4177b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4178b1b1d783SJeff Cody 
4179b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
4180b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
4181b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4182b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4183b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4184b1b1d783SJeff Cody                 break;
4185b1b1d783SJeff Cody             }
4186e8a6bb9cSMarcelo Tosatti         } else {
4187b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
4188b1b1d783SJeff Cody              * image's filename path */
4189b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4190b1b1d783SJeff Cody                          backing_file);
4191b1b1d783SJeff Cody 
4192b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
4193b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
4194b1b1d783SJeff Cody                 continue;
4195b1b1d783SJeff Cody             }
4196b1b1d783SJeff Cody 
4197b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
4198b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
4199b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4200b1b1d783SJeff Cody                          curr_bs->backing_file);
4201b1b1d783SJeff Cody 
4202b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
4203b1b1d783SJeff Cody                 continue;
4204b1b1d783SJeff Cody             }
4205b1b1d783SJeff Cody 
4206b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
4207b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4208b1b1d783SJeff Cody                 break;
4209b1b1d783SJeff Cody             }
4210e8a6bb9cSMarcelo Tosatti         }
4211e8a6bb9cSMarcelo Tosatti     }
4212e8a6bb9cSMarcelo Tosatti 
4213b1b1d783SJeff Cody     g_free(filename_full);
4214b1b1d783SJeff Cody     g_free(backing_file_full);
4215b1b1d783SJeff Cody     g_free(filename_tmp);
4216b1b1d783SJeff Cody     return retval;
4217e8a6bb9cSMarcelo Tosatti }
4218e8a6bb9cSMarcelo Tosatti 
4219f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
4220f198fd1cSBenoît Canet {
4221f198fd1cSBenoît Canet     if (!bs->drv) {
4222f198fd1cSBenoît Canet         return 0;
4223f198fd1cSBenoît Canet     }
4224f198fd1cSBenoît Canet 
4225f198fd1cSBenoît Canet     if (!bs->backing_hd) {
4226f198fd1cSBenoît Canet         return 0;
4227f198fd1cSBenoît Canet     }
4228f198fd1cSBenoît Canet 
4229f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4230f198fd1cSBenoît Canet }
4231f198fd1cSBenoît Canet 
423279fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
423379fac568SJeff Cody {
423479fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
423579fac568SJeff Cody 
423679fac568SJeff Cody     if (!bs) {
423779fac568SJeff Cody         return NULL;
423879fac568SJeff Cody     }
423979fac568SJeff Cody 
424079fac568SJeff Cody     curr_bs = bs;
424179fac568SJeff Cody 
424279fac568SJeff Cody     while (curr_bs->backing_hd) {
424379fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
424479fac568SJeff Cody     }
424579fac568SJeff Cody     return curr_bs;
424679fac568SJeff Cody }
424779fac568SJeff Cody 
4248ea2384d3Sbellard /**************************************************************/
424983f64091Sbellard /* async I/Os */
4250ea2384d3Sbellard 
42513b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
4252f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
425383f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
4254ea2384d3Sbellard {
4255bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4256bbf0a440SStefan Hajnoczi 
4257d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
42588c5873d6SStefan Hajnoczi                                  cb, opaque, false);
425983f64091Sbellard }
426083f64091Sbellard 
4261f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4262f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
426383f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
42647674e7bfSbellard {
4265bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4266bbf0a440SStefan Hajnoczi 
4267d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
42688c5873d6SStefan Hajnoczi                                  cb, opaque, true);
426983f64091Sbellard }
427083f64091Sbellard 
4271d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4272d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4273d5ef94d4SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
4274d5ef94d4SPaolo Bonzini {
4275d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4276d5ef94d4SPaolo Bonzini 
4277d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4278d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4279d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4280d5ef94d4SPaolo Bonzini }
4281d5ef94d4SPaolo Bonzini 
428240b4f539SKevin Wolf 
428340b4f539SKevin Wolf typedef struct MultiwriteCB {
428440b4f539SKevin Wolf     int error;
428540b4f539SKevin Wolf     int num_requests;
428640b4f539SKevin Wolf     int num_callbacks;
428740b4f539SKevin Wolf     struct {
428840b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
428940b4f539SKevin Wolf         void *opaque;
429040b4f539SKevin Wolf         QEMUIOVector *free_qiov;
429140b4f539SKevin Wolf     } callbacks[];
429240b4f539SKevin Wolf } MultiwriteCB;
429340b4f539SKevin Wolf 
429440b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
429540b4f539SKevin Wolf {
429640b4f539SKevin Wolf     int i;
429740b4f539SKevin Wolf 
429840b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
429940b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
43001e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
43011e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
43021e1ea48dSStefan Hajnoczi         }
43037267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
430440b4f539SKevin Wolf     }
430540b4f539SKevin Wolf }
430640b4f539SKevin Wolf 
430740b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
430840b4f539SKevin Wolf {
430940b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
431040b4f539SKevin Wolf 
43116d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
43126d519a5fSStefan Hajnoczi 
4313cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
431440b4f539SKevin Wolf         mcb->error = ret;
431540b4f539SKevin Wolf     }
431640b4f539SKevin Wolf 
431740b4f539SKevin Wolf     mcb->num_requests--;
431840b4f539SKevin Wolf     if (mcb->num_requests == 0) {
431940b4f539SKevin Wolf         multiwrite_user_cb(mcb);
43207267c094SAnthony Liguori         g_free(mcb);
432140b4f539SKevin Wolf     }
432240b4f539SKevin Wolf }
432340b4f539SKevin Wolf 
432440b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
432540b4f539SKevin Wolf {
432677be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
432777be4366SChristoph Hellwig 
432877be4366SChristoph Hellwig     /*
432977be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
433077be4366SChristoph Hellwig      * here as that could overflow the return value.
433177be4366SChristoph Hellwig      */
433277be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
433377be4366SChristoph Hellwig         return 1;
433477be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
433577be4366SChristoph Hellwig         return -1;
433677be4366SChristoph Hellwig     } else {
433777be4366SChristoph Hellwig         return 0;
433877be4366SChristoph Hellwig     }
433940b4f539SKevin Wolf }
434040b4f539SKevin Wolf 
434140b4f539SKevin Wolf /*
434240b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
434340b4f539SKevin Wolf  * requests that remain after merging.
434440b4f539SKevin Wolf  */
434540b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
434640b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
434740b4f539SKevin Wolf {
434840b4f539SKevin Wolf     int i, outidx;
434940b4f539SKevin Wolf 
435040b4f539SKevin Wolf     // Sort requests by start sector
435140b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
435240b4f539SKevin Wolf 
435340b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
435440b4f539SKevin Wolf     // filling up gaps with zero sectors.
435540b4f539SKevin Wolf     outidx = 0;
435640b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
435740b4f539SKevin Wolf         int merge = 0;
435840b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
435940b4f539SKevin Wolf 
4360b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
436140b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
436240b4f539SKevin Wolf             merge = 1;
436340b4f539SKevin Wolf         }
436440b4f539SKevin Wolf 
4365e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4366e2a305fbSChristoph Hellwig             merge = 0;
4367e2a305fbSChristoph Hellwig         }
4368e2a305fbSChristoph Hellwig 
436940b4f539SKevin Wolf         if (merge) {
437040b4f539SKevin Wolf             size_t size;
43717267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
437240b4f539SKevin Wolf             qemu_iovec_init(qiov,
437340b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
437440b4f539SKevin Wolf 
437540b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
437640b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
437740b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
43781b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
437940b4f539SKevin Wolf 
4380b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4381b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
438240b4f539SKevin Wolf 
438340b4f539SKevin Wolf             // Add the second request
43841b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
438540b4f539SKevin Wolf 
4386cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
438740b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
438840b4f539SKevin Wolf 
438940b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
439040b4f539SKevin Wolf         } else {
439140b4f539SKevin Wolf             outidx++;
439240b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
439340b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
439440b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
439540b4f539SKevin Wolf         }
439640b4f539SKevin Wolf     }
439740b4f539SKevin Wolf 
439840b4f539SKevin Wolf     return outidx + 1;
439940b4f539SKevin Wolf }
440040b4f539SKevin Wolf 
440140b4f539SKevin Wolf /*
440240b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
440340b4f539SKevin Wolf  *
440440b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
440540b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
440640b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
440740b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
440840b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
440940b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
441040b4f539SKevin Wolf  *
441140b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
441240b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
441340b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
441440b4f539SKevin Wolf  */
441540b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
441640b4f539SKevin Wolf {
441740b4f539SKevin Wolf     MultiwriteCB *mcb;
441840b4f539SKevin Wolf     int i;
441940b4f539SKevin Wolf 
4420301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4421301db7c2SRyan Harper     if (bs->drv == NULL) {
4422301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4423301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4424301db7c2SRyan Harper         }
4425301db7c2SRyan Harper         return -1;
4426301db7c2SRyan Harper     }
4427301db7c2SRyan Harper 
442840b4f539SKevin Wolf     if (num_reqs == 0) {
442940b4f539SKevin Wolf         return 0;
443040b4f539SKevin Wolf     }
443140b4f539SKevin Wolf 
443240b4f539SKevin Wolf     // Create MultiwriteCB structure
44337267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
443440b4f539SKevin Wolf     mcb->num_requests = 0;
443540b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
443640b4f539SKevin Wolf 
443740b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
443840b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
443940b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
444040b4f539SKevin Wolf     }
444140b4f539SKevin Wolf 
444240b4f539SKevin Wolf     // Check for mergable requests
444340b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
444440b4f539SKevin Wolf 
44456d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
44466d519a5fSStefan Hajnoczi 
4447df9309fbSPaolo Bonzini     /* Run the aio requests. */
4448df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
444940b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4450d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4451d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4452d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4453d20d9b7cSPaolo Bonzini                               true);
445440b4f539SKevin Wolf     }
445540b4f539SKevin Wolf 
445640b4f539SKevin Wolf     return 0;
445740b4f539SKevin Wolf }
445840b4f539SKevin Wolf 
445983f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
446083f64091Sbellard {
4461d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
446283f64091Sbellard }
446383f64091Sbellard 
446483f64091Sbellard /**************************************************************/
446583f64091Sbellard /* async block device emulation */
446683f64091Sbellard 
4467c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4468c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4469c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4470c16b5a2cSChristoph Hellwig     int ret;
4471c16b5a2cSChristoph Hellwig     /* vector translation state */
4472c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4473c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4474c16b5a2cSChristoph Hellwig     int is_write;
4475c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4476c16b5a2cSChristoph Hellwig 
4477c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4478c16b5a2cSChristoph Hellwig {
4479b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
4480b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
44816a7ad299SDor Laor     qemu_bh_delete(acb->bh);
448236afc451SAvi Kivity     acb->bh = NULL;
4483c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
4484c16b5a2cSChristoph Hellwig }
4485c16b5a2cSChristoph Hellwig 
4486d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4487c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4488c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
4489c16b5a2cSChristoph Hellwig };
4490c16b5a2cSChristoph Hellwig 
449183f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4492beac80cdSbellard {
4493ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4494f141eafeSaliguori 
4495f141eafeSaliguori     if (!acb->is_write)
449603396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4497ceb42de8Saliguori     qemu_vfree(acb->bounce);
4498ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
44996a7ad299SDor Laor     qemu_bh_delete(acb->bh);
450036afc451SAvi Kivity     acb->bh = NULL;
4501ce1a14dcSpbrook     qemu_aio_release(acb);
4502beac80cdSbellard }
4503beac80cdSbellard 
4504f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4505f141eafeSaliguori                                             int64_t sector_num,
4506f141eafeSaliguori                                             QEMUIOVector *qiov,
4507f141eafeSaliguori                                             int nb_sectors,
4508f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4509f141eafeSaliguori                                             void *opaque,
4510f141eafeSaliguori                                             int is_write)
4511f141eafeSaliguori 
4512ea2384d3Sbellard {
4513ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
451483f64091Sbellard 
4515d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4516f141eafeSaliguori     acb->is_write = is_write;
4517f141eafeSaliguori     acb->qiov = qiov;
4518e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
4519ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4520f141eafeSaliguori 
4521f141eafeSaliguori     if (is_write) {
4522d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
45231ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4524f141eafeSaliguori     } else {
45251ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4526f141eafeSaliguori     }
4527f141eafeSaliguori 
4528ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4529f141eafeSaliguori 
4530ce1a14dcSpbrook     return &acb->common;
45317a6cba61Spbrook }
45327a6cba61Spbrook 
4533f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4534f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4535ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
453683f64091Sbellard {
4537f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
453883f64091Sbellard }
453983f64091Sbellard 
4540f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4541f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4542f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4543f141eafeSaliguori {
4544f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4545f141eafeSaliguori }
4546f141eafeSaliguori 
454768485420SKevin Wolf 
454868485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
454968485420SKevin Wolf     BlockDriverAIOCB common;
455068485420SKevin Wolf     BlockRequest req;
455168485420SKevin Wolf     bool is_write;
4552d318aea9SKevin Wolf     bool *done;
455368485420SKevin Wolf     QEMUBH* bh;
455468485420SKevin Wolf } BlockDriverAIOCBCoroutine;
455568485420SKevin Wolf 
455668485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
455768485420SKevin Wolf {
4558d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
4559d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4560d318aea9SKevin Wolf     bool done = false;
4561d318aea9SKevin Wolf 
4562d318aea9SKevin Wolf     acb->done = &done;
4563d318aea9SKevin Wolf     while (!done) {
4564d318aea9SKevin Wolf         qemu_aio_wait();
4565d318aea9SKevin Wolf     }
456668485420SKevin Wolf }
456768485420SKevin Wolf 
4568d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
456968485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
457068485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
457168485420SKevin Wolf };
457268485420SKevin Wolf 
457335246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
457468485420SKevin Wolf {
457568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
457668485420SKevin Wolf 
457768485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4578d318aea9SKevin Wolf 
4579d318aea9SKevin Wolf     if (acb->done) {
4580d318aea9SKevin Wolf         *acb->done = true;
4581d318aea9SKevin Wolf     }
4582d318aea9SKevin Wolf 
458368485420SKevin Wolf     qemu_bh_delete(acb->bh);
458468485420SKevin Wolf     qemu_aio_release(acb);
458568485420SKevin Wolf }
458668485420SKevin Wolf 
4587b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4588b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4589b2a61371SStefan Hajnoczi {
4590b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4591b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4592b2a61371SStefan Hajnoczi 
4593b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4594b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4595d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4596b2a61371SStefan Hajnoczi     } else {
4597b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4598d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4599b2a61371SStefan Hajnoczi     }
4600b2a61371SStefan Hajnoczi 
460135246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4602b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4603b2a61371SStefan Hajnoczi }
4604b2a61371SStefan Hajnoczi 
460568485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
460668485420SKevin Wolf                                                int64_t sector_num,
460768485420SKevin Wolf                                                QEMUIOVector *qiov,
460868485420SKevin Wolf                                                int nb_sectors,
4609d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
461068485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
461168485420SKevin Wolf                                                void *opaque,
46128c5873d6SStefan Hajnoczi                                                bool is_write)
461368485420SKevin Wolf {
461468485420SKevin Wolf     Coroutine *co;
461568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
461668485420SKevin Wolf 
4617d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
461868485420SKevin Wolf     acb->req.sector = sector_num;
461968485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
462068485420SKevin Wolf     acb->req.qiov = qiov;
4621d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
462268485420SKevin Wolf     acb->is_write = is_write;
4623d318aea9SKevin Wolf     acb->done = NULL;
462468485420SKevin Wolf 
46258c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
462668485420SKevin Wolf     qemu_coroutine_enter(co, acb);
462768485420SKevin Wolf 
462868485420SKevin Wolf     return &acb->common;
462968485420SKevin Wolf }
463068485420SKevin Wolf 
463107f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4632b2e12bc6SChristoph Hellwig {
463307f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
463407f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4635b2e12bc6SChristoph Hellwig 
463607f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
463707f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4638b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4639b2e12bc6SChristoph Hellwig }
4640b2e12bc6SChristoph Hellwig 
464107f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4642016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4643016f5cf6SAlexander Graf {
464407f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4645016f5cf6SAlexander Graf 
464607f07615SPaolo Bonzini     Coroutine *co;
464707f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4648016f5cf6SAlexander Graf 
4649d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4650d318aea9SKevin Wolf     acb->done = NULL;
4651d318aea9SKevin Wolf 
465207f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
465307f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4654016f5cf6SAlexander Graf 
4655016f5cf6SAlexander Graf     return &acb->common;
4656016f5cf6SAlexander Graf }
4657016f5cf6SAlexander Graf 
46584265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
46594265d620SPaolo Bonzini {
46604265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
46614265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
46624265d620SPaolo Bonzini 
46634265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
46644265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
46654265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
46664265d620SPaolo Bonzini }
46674265d620SPaolo Bonzini 
46684265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
46694265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
46704265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
46714265d620SPaolo Bonzini {
46724265d620SPaolo Bonzini     Coroutine *co;
46734265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
46744265d620SPaolo Bonzini 
46754265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
46764265d620SPaolo Bonzini 
4677d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
46784265d620SPaolo Bonzini     acb->req.sector = sector_num;
46794265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4680d318aea9SKevin Wolf     acb->done = NULL;
46814265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
46824265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
46834265d620SPaolo Bonzini 
46844265d620SPaolo Bonzini     return &acb->common;
46854265d620SPaolo Bonzini }
46864265d620SPaolo Bonzini 
4687ea2384d3Sbellard void bdrv_init(void)
4688ea2384d3Sbellard {
46895efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4690ea2384d3Sbellard }
4691ce1a14dcSpbrook 
4692eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4693eb852011SMarkus Armbruster {
4694eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4695eb852011SMarkus Armbruster     bdrv_init();
4696eb852011SMarkus Armbruster }
4697eb852011SMarkus Armbruster 
4698d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
46996bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
47006bbff9a0Saliguori {
4701ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4702ce1a14dcSpbrook 
4703d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4704d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4705ce1a14dcSpbrook     acb->bs = bs;
4706ce1a14dcSpbrook     acb->cb = cb;
4707ce1a14dcSpbrook     acb->opaque = opaque;
4708ce1a14dcSpbrook     return acb;
4709ce1a14dcSpbrook }
4710ce1a14dcSpbrook 
4711ce1a14dcSpbrook void qemu_aio_release(void *p)
4712ce1a14dcSpbrook {
4713d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4714d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4715ce1a14dcSpbrook }
471619cb3738Sbellard 
471719cb3738Sbellard /**************************************************************/
4718f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4719f9f05dc5SKevin Wolf 
4720f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4721f9f05dc5SKevin Wolf     Coroutine *coroutine;
4722f9f05dc5SKevin Wolf     int ret;
4723f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4724f9f05dc5SKevin Wolf 
4725f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4726f9f05dc5SKevin Wolf {
4727f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4728f9f05dc5SKevin Wolf 
4729f9f05dc5SKevin Wolf     co->ret = ret;
4730f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4731f9f05dc5SKevin Wolf }
4732f9f05dc5SKevin Wolf 
4733f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4734f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4735f9f05dc5SKevin Wolf                                       bool is_write)
4736f9f05dc5SKevin Wolf {
4737f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4738f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4739f9f05dc5SKevin Wolf     };
4740f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4741f9f05dc5SKevin Wolf 
4742f9f05dc5SKevin Wolf     if (is_write) {
4743a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4744f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4745f9f05dc5SKevin Wolf     } else {
4746a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4747f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4748f9f05dc5SKevin Wolf     }
4749f9f05dc5SKevin Wolf 
475059370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4751f9f05dc5SKevin Wolf     if (!acb) {
4752f9f05dc5SKevin Wolf         return -EIO;
4753f9f05dc5SKevin Wolf     }
4754f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4755f9f05dc5SKevin Wolf 
4756f9f05dc5SKevin Wolf     return co.ret;
4757f9f05dc5SKevin Wolf }
4758f9f05dc5SKevin Wolf 
4759f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4760f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4761f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4762f9f05dc5SKevin Wolf {
4763f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4764f9f05dc5SKevin Wolf }
4765f9f05dc5SKevin Wolf 
4766f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4767f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4768f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4769f9f05dc5SKevin Wolf {
4770f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4771f9f05dc5SKevin Wolf }
4772f9f05dc5SKevin Wolf 
477307f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4774e7a8a783SKevin Wolf {
477507f07615SPaolo Bonzini     RwCo *rwco = opaque;
477607f07615SPaolo Bonzini 
477707f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
477807f07615SPaolo Bonzini }
477907f07615SPaolo Bonzini 
478007f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
478107f07615SPaolo Bonzini {
4782eb489bb1SKevin Wolf     int ret;
4783eb489bb1SKevin Wolf 
478429cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
478507f07615SPaolo Bonzini         return 0;
4786eb489bb1SKevin Wolf     }
4787eb489bb1SKevin Wolf 
4788ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4789bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4790eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4791eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4792eb489bb1SKevin Wolf         if (ret < 0) {
4793eb489bb1SKevin Wolf             return ret;
4794eb489bb1SKevin Wolf         }
4795eb489bb1SKevin Wolf     }
4796eb489bb1SKevin Wolf 
4797ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4798ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4799d4c82329SKevin Wolf         goto flush_parent;
4800ca716364SKevin Wolf     }
4801ca716364SKevin Wolf 
4802bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4803eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
480429cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
480507f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
480607f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4807e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4808e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4809e7a8a783SKevin Wolf         };
4810e7a8a783SKevin Wolf 
481107f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
481207f07615SPaolo Bonzini         if (acb == NULL) {
481329cdb251SPaolo Bonzini             ret = -EIO;
481407f07615SPaolo Bonzini         } else {
4815e7a8a783SKevin Wolf             qemu_coroutine_yield();
481629cdb251SPaolo Bonzini             ret = co.ret;
4817e7a8a783SKevin Wolf         }
481807f07615SPaolo Bonzini     } else {
481907f07615SPaolo Bonzini         /*
482007f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
482107f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
482207f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
482307f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
482407f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
482507f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
482607f07615SPaolo Bonzini          * mode.
482707f07615SPaolo Bonzini          *
482807f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
482907f07615SPaolo Bonzini          */
483029cdb251SPaolo Bonzini         ret = 0;
483107f07615SPaolo Bonzini     }
483229cdb251SPaolo Bonzini     if (ret < 0) {
483329cdb251SPaolo Bonzini         return ret;
483429cdb251SPaolo Bonzini     }
483529cdb251SPaolo Bonzini 
483629cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
483729cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
483829cdb251SPaolo Bonzini      */
4839d4c82329SKevin Wolf flush_parent:
484029cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
484107f07615SPaolo Bonzini }
484207f07615SPaolo Bonzini 
48435a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
48440f15423cSAnthony Liguori {
48455a8a30dbSKevin Wolf     Error *local_err = NULL;
48465a8a30dbSKevin Wolf     int ret;
48475a8a30dbSKevin Wolf 
48483456a8d1SKevin Wolf     if (!bs->drv)  {
48493456a8d1SKevin Wolf         return;
48500f15423cSAnthony Liguori     }
48513456a8d1SKevin Wolf 
48523456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
48535a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
48543456a8d1SKevin Wolf     } else if (bs->file) {
48555a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs->file, &local_err);
48565a8a30dbSKevin Wolf     }
48575a8a30dbSKevin Wolf     if (local_err) {
48585a8a30dbSKevin Wolf         error_propagate(errp, local_err);
48595a8a30dbSKevin Wolf         return;
48603456a8d1SKevin Wolf     }
48613456a8d1SKevin Wolf 
48625a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
48635a8a30dbSKevin Wolf     if (ret < 0) {
48645a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
48655a8a30dbSKevin Wolf         return;
48665a8a30dbSKevin Wolf     }
48670f15423cSAnthony Liguori }
48680f15423cSAnthony Liguori 
48695a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
48700f15423cSAnthony Liguori {
48710f15423cSAnthony Liguori     BlockDriverState *bs;
48725a8a30dbSKevin Wolf     Error *local_err = NULL;
48730f15423cSAnthony Liguori 
4874dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
48755a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
48765a8a30dbSKevin Wolf         if (local_err) {
48775a8a30dbSKevin Wolf             error_propagate(errp, local_err);
48785a8a30dbSKevin Wolf             return;
48795a8a30dbSKevin Wolf         }
48800f15423cSAnthony Liguori     }
48810f15423cSAnthony Liguori }
48820f15423cSAnthony Liguori 
488307789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
488407789269SBenoît Canet {
488507789269SBenoît Canet     BlockDriverState *bs;
488607789269SBenoît Canet 
4887dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
488807789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
488907789269SBenoît Canet     }
489007789269SBenoît Canet }
489107789269SBenoît Canet 
489207f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
489307f07615SPaolo Bonzini {
489407f07615SPaolo Bonzini     Coroutine *co;
489507f07615SPaolo Bonzini     RwCo rwco = {
489607f07615SPaolo Bonzini         .bs = bs,
489707f07615SPaolo Bonzini         .ret = NOT_DONE,
489807f07615SPaolo Bonzini     };
489907f07615SPaolo Bonzini 
490007f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
490107f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
490207f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
490307f07615SPaolo Bonzini     } else {
490407f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
490507f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
490607f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
490707f07615SPaolo Bonzini             qemu_aio_wait();
490807f07615SPaolo Bonzini         }
490907f07615SPaolo Bonzini     }
491007f07615SPaolo Bonzini 
491107f07615SPaolo Bonzini     return rwco.ret;
491207f07615SPaolo Bonzini }
4913e7a8a783SKevin Wolf 
4914775aa8b6SKevin Wolf typedef struct DiscardCo {
4915775aa8b6SKevin Wolf     BlockDriverState *bs;
4916775aa8b6SKevin Wolf     int64_t sector_num;
4917775aa8b6SKevin Wolf     int nb_sectors;
4918775aa8b6SKevin Wolf     int ret;
4919775aa8b6SKevin Wolf } DiscardCo;
49204265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
49214265d620SPaolo Bonzini {
4922775aa8b6SKevin Wolf     DiscardCo *rwco = opaque;
49234265d620SPaolo Bonzini 
49244265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
49254265d620SPaolo Bonzini }
49264265d620SPaolo Bonzini 
49276f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
49286f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
49296f14da52SPeter Lieven  */
49306f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
49316f14da52SPeter Lieven 
49324265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
49334265d620SPaolo Bonzini                                  int nb_sectors)
49344265d620SPaolo Bonzini {
4935d51e9fe5SPaolo Bonzini     int max_discard;
4936d51e9fe5SPaolo Bonzini 
49374265d620SPaolo Bonzini     if (!bs->drv) {
49384265d620SPaolo Bonzini         return -ENOMEDIUM;
49394265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
49404265d620SPaolo Bonzini         return -EIO;
49414265d620SPaolo Bonzini     } else if (bs->read_only) {
49424265d620SPaolo Bonzini         return -EROFS;
4943df702c9bSPaolo Bonzini     }
4944df702c9bSPaolo Bonzini 
49458f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
4946df702c9bSPaolo Bonzini 
49479e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
49489e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
49499e8f1835SPaolo Bonzini         return 0;
49509e8f1835SPaolo Bonzini     }
49519e8f1835SPaolo Bonzini 
4952d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
4953d51e9fe5SPaolo Bonzini         return 0;
4954d51e9fe5SPaolo Bonzini     }
49556f14da52SPeter Lieven 
4956d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
49576f14da52SPeter Lieven     while (nb_sectors > 0) {
49586f14da52SPeter Lieven         int ret;
49596f14da52SPeter Lieven         int num = nb_sectors;
49606f14da52SPeter Lieven 
49616f14da52SPeter Lieven         /* align request */
49626f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
49636f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
49646f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
49656f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
49666f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
49676f14da52SPeter Lieven             }
49686f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
49696f14da52SPeter Lieven         }
49706f14da52SPeter Lieven 
49716f14da52SPeter Lieven         /* limit request size */
49726f14da52SPeter Lieven         if (num > max_discard) {
49736f14da52SPeter Lieven             num = max_discard;
49746f14da52SPeter Lieven         }
49756f14da52SPeter Lieven 
4976d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
49776f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
4978d51e9fe5SPaolo Bonzini         } else {
49794265d620SPaolo Bonzini             BlockDriverAIOCB *acb;
49804265d620SPaolo Bonzini             CoroutineIOCompletion co = {
49814265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
49824265d620SPaolo Bonzini             };
49834265d620SPaolo Bonzini 
49844265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
49854265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
49864265d620SPaolo Bonzini             if (acb == NULL) {
49874265d620SPaolo Bonzini                 return -EIO;
49884265d620SPaolo Bonzini             } else {
49894265d620SPaolo Bonzini                 qemu_coroutine_yield();
4990d51e9fe5SPaolo Bonzini                 ret = co.ret;
49914265d620SPaolo Bonzini             }
4992d51e9fe5SPaolo Bonzini         }
49937ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
4994d51e9fe5SPaolo Bonzini             return ret;
4995d51e9fe5SPaolo Bonzini         }
4996d51e9fe5SPaolo Bonzini 
4997d51e9fe5SPaolo Bonzini         sector_num += num;
4998d51e9fe5SPaolo Bonzini         nb_sectors -= num;
4999d51e9fe5SPaolo Bonzini     }
50004265d620SPaolo Bonzini     return 0;
50014265d620SPaolo Bonzini }
50024265d620SPaolo Bonzini 
50034265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
50044265d620SPaolo Bonzini {
50054265d620SPaolo Bonzini     Coroutine *co;
5006775aa8b6SKevin Wolf     DiscardCo rwco = {
50074265d620SPaolo Bonzini         .bs = bs,
50084265d620SPaolo Bonzini         .sector_num = sector_num,
50094265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
50104265d620SPaolo Bonzini         .ret = NOT_DONE,
50114265d620SPaolo Bonzini     };
50124265d620SPaolo Bonzini 
50134265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
50144265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
50154265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
50164265d620SPaolo Bonzini     } else {
50174265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
50184265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
50194265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
50204265d620SPaolo Bonzini             qemu_aio_wait();
50214265d620SPaolo Bonzini         }
50224265d620SPaolo Bonzini     }
50234265d620SPaolo Bonzini 
50244265d620SPaolo Bonzini     return rwco.ret;
50254265d620SPaolo Bonzini }
50264265d620SPaolo Bonzini 
5027f9f05dc5SKevin Wolf /**************************************************************/
502819cb3738Sbellard /* removable device support */
502919cb3738Sbellard 
503019cb3738Sbellard /**
503119cb3738Sbellard  * Return TRUE if the media is present
503219cb3738Sbellard  */
503319cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
503419cb3738Sbellard {
503519cb3738Sbellard     BlockDriver *drv = bs->drv;
5036a1aff5bfSMarkus Armbruster 
503719cb3738Sbellard     if (!drv)
503819cb3738Sbellard         return 0;
503919cb3738Sbellard     if (!drv->bdrv_is_inserted)
5040a1aff5bfSMarkus Armbruster         return 1;
5041a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
504219cb3738Sbellard }
504319cb3738Sbellard 
504419cb3738Sbellard /**
50458e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
50468e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
504719cb3738Sbellard  */
504819cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
504919cb3738Sbellard {
505019cb3738Sbellard     BlockDriver *drv = bs->drv;
505119cb3738Sbellard 
50528e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
50538e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
50548e49ca46SMarkus Armbruster     }
50558e49ca46SMarkus Armbruster     return -ENOTSUP;
505619cb3738Sbellard }
505719cb3738Sbellard 
505819cb3738Sbellard /**
505919cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
506019cb3738Sbellard  */
5061f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
506219cb3738Sbellard {
506319cb3738Sbellard     BlockDriver *drv = bs->drv;
506419cb3738Sbellard 
5065822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
5066822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
506719cb3738Sbellard     }
50686f382ed2SLuiz Capitulino 
50696f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
50706f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
50716f382ed2SLuiz Capitulino     }
507219cb3738Sbellard }
507319cb3738Sbellard 
507419cb3738Sbellard /**
507519cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
507619cb3738Sbellard  * to eject it manually).
507719cb3738Sbellard  */
5078025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
507919cb3738Sbellard {
508019cb3738Sbellard     BlockDriver *drv = bs->drv;
508119cb3738Sbellard 
5082025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
5083b8c6d095SStefan Hajnoczi 
5084025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
5085025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
508619cb3738Sbellard     }
508719cb3738Sbellard }
5088985a03b0Sths 
5089985a03b0Sths /* needed for generic scsi interface */
5090985a03b0Sths 
5091985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
5092985a03b0Sths {
5093985a03b0Sths     BlockDriver *drv = bs->drv;
5094985a03b0Sths 
5095985a03b0Sths     if (drv && drv->bdrv_ioctl)
5096985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
5097985a03b0Sths     return -ENOTSUP;
5098985a03b0Sths }
50997d780669Saliguori 
5100221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
5101221f715dSaliguori         unsigned long int req, void *buf,
51027d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
51037d780669Saliguori {
5104221f715dSaliguori     BlockDriver *drv = bs->drv;
51057d780669Saliguori 
5106221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
5107221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
5108221f715dSaliguori     return NULL;
51097d780669Saliguori }
5110e268ca52Saliguori 
51111b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
51127b6f9300SMarkus Armbruster {
51131b7fd729SPaolo Bonzini     bs->guest_block_size = align;
51147b6f9300SMarkus Armbruster }
51157cd1e32aSlirans@il.ibm.com 
5116e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
5117e268ca52Saliguori {
5118339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
5119e268ca52Saliguori }
51207cd1e32aSlirans@il.ibm.com 
5121c53b1c51SStefan Hajnoczi /*
5122c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
5123c53b1c51SStefan Hajnoczi  */
5124c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5125c53b1c51SStefan Hajnoczi {
5126c53b1c51SStefan Hajnoczi     int i;
5127339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
5128c53b1c51SStefan Hajnoczi 
5129c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
5130339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
5131c53b1c51SStefan Hajnoczi             return false;
5132c53b1c51SStefan Hajnoczi         }
5133339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
51341ff735bdSKevin Wolf             return false;
51351ff735bdSKevin Wolf         }
5136c53b1c51SStefan Hajnoczi     }
5137c53b1c51SStefan Hajnoczi 
5138c53b1c51SStefan Hajnoczi     return true;
5139c53b1c51SStefan Hajnoczi }
5140c53b1c51SStefan Hajnoczi 
5141b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity,
5142b8afb520SFam Zheng                                           Error **errp)
51437cd1e32aSlirans@il.ibm.com {
51447cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
5145e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5146a55eb92cSJan Kiszka 
514750717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
514850717e94SPaolo Bonzini 
514950717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
5150e4654d2dSFam Zheng     assert(granularity);
5151b8afb520SFam Zheng     bitmap_size = bdrv_getlength(bs);
5152b8afb520SFam Zheng     if (bitmap_size < 0) {
5153b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
5154b8afb520SFam Zheng         errno = -bitmap_size;
5155b8afb520SFam Zheng         return NULL;
5156b8afb520SFam Zheng     }
5157b8afb520SFam Zheng     bitmap_size >>= BDRV_SECTOR_BITS;
5158e4654d2dSFam Zheng     bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
5159e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5160e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5161e4654d2dSFam Zheng     return bitmap;
5162e4654d2dSFam Zheng }
5163e4654d2dSFam Zheng 
5164e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5165e4654d2dSFam Zheng {
5166e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
5167e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5168e4654d2dSFam Zheng         if (bm == bitmap) {
5169e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
5170e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
5171e4654d2dSFam Zheng             g_free(bitmap);
5172e4654d2dSFam Zheng             return;
51737cd1e32aSlirans@il.ibm.com         }
51747cd1e32aSlirans@il.ibm.com     }
51757cd1e32aSlirans@il.ibm.com }
51767cd1e32aSlirans@il.ibm.com 
517721b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
517821b56835SFam Zheng {
517921b56835SFam Zheng     BdrvDirtyBitmap *bm;
518021b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
518121b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
518221b56835SFam Zheng 
518321b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
518421b56835SFam Zheng         BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
518521b56835SFam Zheng         BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
518621b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
518721b56835SFam Zheng         info->granularity =
518821b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
518921b56835SFam Zheng         entry->value = info;
519021b56835SFam Zheng         *plist = entry;
519121b56835SFam Zheng         plist = &entry->next;
519221b56835SFam Zheng     }
519321b56835SFam Zheng 
519421b56835SFam Zheng     return list;
519521b56835SFam Zheng }
519621b56835SFam Zheng 
5197e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
51987cd1e32aSlirans@il.ibm.com {
5199e4654d2dSFam Zheng     if (bitmap) {
5200e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
52017cd1e32aSlirans@il.ibm.com     } else {
52027cd1e32aSlirans@il.ibm.com         return 0;
52037cd1e32aSlirans@il.ibm.com     }
52047cd1e32aSlirans@il.ibm.com }
52057cd1e32aSlirans@il.ibm.com 
5206e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
5207e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
52081755da16SPaolo Bonzini {
5209e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
52101755da16SPaolo Bonzini }
52111755da16SPaolo Bonzini 
52121755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
52131755da16SPaolo Bonzini                     int nr_sectors)
52141755da16SPaolo Bonzini {
5215e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5216e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5217e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5218e4654d2dSFam Zheng     }
52191755da16SPaolo Bonzini }
52201755da16SPaolo Bonzini 
5221e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
52227cd1e32aSlirans@il.ibm.com {
5223e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5224e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5225e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5226e4654d2dSFam Zheng     }
52277cd1e32aSlirans@il.ibm.com }
5228aaa0eb75SLiran Schour 
5229e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5230aaa0eb75SLiran Schour {
5231e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
5232aaa0eb75SLiran Schour }
5233f88e1a42SJes Sorensen 
52349fcb0251SFam Zheng /* Get a reference to bs */
52359fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
52369fcb0251SFam Zheng {
52379fcb0251SFam Zheng     bs->refcnt++;
52389fcb0251SFam Zheng }
52399fcb0251SFam Zheng 
52409fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
52419fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
52429fcb0251SFam Zheng  * deleted. */
52439fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
52449fcb0251SFam Zheng {
52459fcb0251SFam Zheng     assert(bs->refcnt > 0);
52469fcb0251SFam Zheng     if (--bs->refcnt == 0) {
52479fcb0251SFam Zheng         bdrv_delete(bs);
52489fcb0251SFam Zheng     }
52499fcb0251SFam Zheng }
52509fcb0251SFam Zheng 
5251db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
5252db593f25SMarcelo Tosatti {
5253db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
5254db593f25SMarcelo Tosatti     bs->in_use = in_use;
5255db593f25SMarcelo Tosatti }
5256db593f25SMarcelo Tosatti 
5257db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
5258db593f25SMarcelo Tosatti {
5259db593f25SMarcelo Tosatti     return bs->in_use;
5260db593f25SMarcelo Tosatti }
5261db593f25SMarcelo Tosatti 
526228a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
526328a7282aSLuiz Capitulino {
5264d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
526558e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
526628a7282aSLuiz Capitulino }
526728a7282aSLuiz Capitulino 
526828a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
526928a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
527028a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
527128a7282aSLuiz Capitulino {
5272d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
527392aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
527492aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
527592aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
527628a7282aSLuiz Capitulino }
527728a7282aSLuiz Capitulino 
527828a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
527928a7282aSLuiz Capitulino {
5280d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
528128a7282aSLuiz Capitulino }
528228a7282aSLuiz Capitulino 
528328a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
528428a7282aSLuiz Capitulino {
528528a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
528658e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
52873bd293c3SPaolo Bonzini         if (bs->job) {
52883bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
52893bd293c3SPaolo Bonzini         }
529028a7282aSLuiz Capitulino     }
529128a7282aSLuiz Capitulino }
529228a7282aSLuiz Capitulino 
529328a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
529428a7282aSLuiz Capitulino {
52953e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
52963e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
529758e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
529858e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
529928a7282aSLuiz Capitulino     }
530028a7282aSLuiz Capitulino }
530128a7282aSLuiz Capitulino 
5302a597e79cSChristoph Hellwig void
5303a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
5304a597e79cSChristoph Hellwig         enum BlockAcctType type)
5305a597e79cSChristoph Hellwig {
5306a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
5307a597e79cSChristoph Hellwig 
5308a597e79cSChristoph Hellwig     cookie->bytes = bytes;
5309c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
5310a597e79cSChristoph Hellwig     cookie->type = type;
5311a597e79cSChristoph Hellwig }
5312a597e79cSChristoph Hellwig 
5313a597e79cSChristoph Hellwig void
5314a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
5315a597e79cSChristoph Hellwig {
5316a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
5317a597e79cSChristoph Hellwig 
5318a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
5319a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
5320c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
5321a597e79cSChristoph Hellwig }
5322a597e79cSChristoph Hellwig 
5323d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5324f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5325f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5326f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5327f88e1a42SJes Sorensen {
5328f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
5329d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
5330f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
533196df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5332cc84d90fSMax Reitz     Error *local_err = NULL;
5333f88e1a42SJes Sorensen     int ret = 0;
5334f88e1a42SJes Sorensen 
5335f88e1a42SJes Sorensen     /* Find driver and parse its options */
5336f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5337f88e1a42SJes Sorensen     if (!drv) {
533871c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5339d92ada22SLuiz Capitulino         return;
5340f88e1a42SJes Sorensen     }
5341f88e1a42SJes Sorensen 
534298289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5343f88e1a42SJes Sorensen     if (!proto_drv) {
534471c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5345d92ada22SLuiz Capitulino         return;
5346f88e1a42SJes Sorensen     }
5347f88e1a42SJes Sorensen 
5348f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5349f88e1a42SJes Sorensen                                               drv->create_options);
5350f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5351f88e1a42SJes Sorensen                                               proto_drv->create_options);
5352f88e1a42SJes Sorensen 
5353f88e1a42SJes Sorensen     /* Create parameter list with default values */
5354f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
5355f88e1a42SJes Sorensen 
5356f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
5357f88e1a42SJes Sorensen 
5358f88e1a42SJes Sorensen     /* Parse -o options */
5359f88e1a42SJes Sorensen     if (options) {
5360f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
5361f88e1a42SJes Sorensen         if (param == NULL) {
536271c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
5363f88e1a42SJes Sorensen             goto out;
5364f88e1a42SJes Sorensen         }
5365f88e1a42SJes Sorensen     }
5366f88e1a42SJes Sorensen 
5367f88e1a42SJes Sorensen     if (base_filename) {
5368f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
5369f88e1a42SJes Sorensen                                  base_filename)) {
537071c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
537171c79813SLuiz Capitulino                        fmt);
5372f88e1a42SJes Sorensen             goto out;
5373f88e1a42SJes Sorensen         }
5374f88e1a42SJes Sorensen     }
5375f88e1a42SJes Sorensen 
5376f88e1a42SJes Sorensen     if (base_fmt) {
5377f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
537871c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
537971c79813SLuiz Capitulino                              "format '%s'", fmt);
5380f88e1a42SJes Sorensen             goto out;
5381f88e1a42SJes Sorensen         }
5382f88e1a42SJes Sorensen     }
5383f88e1a42SJes Sorensen 
5384792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
5385792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
5386792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
538771c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
538871c79813SLuiz Capitulino                              "same filename as the backing file");
5389792da93aSJes Sorensen             goto out;
5390792da93aSJes Sorensen         }
5391792da93aSJes Sorensen     }
5392792da93aSJes Sorensen 
5393f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
5394f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
539596df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
539696df67d1SStefan Hajnoczi         if (!backing_drv) {
539771c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
539871c79813SLuiz Capitulino                        backing_fmt->value.s);
5399f88e1a42SJes Sorensen             goto out;
5400f88e1a42SJes Sorensen         }
5401f88e1a42SJes Sorensen     }
5402f88e1a42SJes Sorensen 
5403f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5404f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
5405d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
5406d220894eSKevin Wolf     if (size && size->value.n == -1) {
5407f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
540866f6b814SMax Reitz             BlockDriverState *bs;
5409f88e1a42SJes Sorensen             uint64_t size;
5410f88e1a42SJes Sorensen             char buf[32];
541163090dacSPaolo Bonzini             int back_flags;
541263090dacSPaolo Bonzini 
541363090dacSPaolo Bonzini             /* backing files always opened read-only */
541463090dacSPaolo Bonzini             back_flags =
541563090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5416f88e1a42SJes Sorensen 
5417f67503e5SMax Reitz             bs = NULL;
5418ddf5636dSMax Reitz             ret = bdrv_open(&bs, backing_file->value.s, NULL, NULL, back_flags,
5419cc84d90fSMax Reitz                             backing_drv, &local_err);
5420f88e1a42SJes Sorensen             if (ret < 0) {
5421cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
5422cc84d90fSMax Reitz                                  backing_file->value.s,
5423cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5424cc84d90fSMax Reitz                 error_free(local_err);
5425cc84d90fSMax Reitz                 local_err = NULL;
5426f88e1a42SJes Sorensen                 goto out;
5427f88e1a42SJes Sorensen             }
5428f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
5429f88e1a42SJes Sorensen             size *= 512;
5430f88e1a42SJes Sorensen 
5431f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
5432f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
543366f6b814SMax Reitz 
543466f6b814SMax Reitz             bdrv_unref(bs);
5435f88e1a42SJes Sorensen         } else {
543671c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5437f88e1a42SJes Sorensen             goto out;
5438f88e1a42SJes Sorensen         }
5439f88e1a42SJes Sorensen     }
5440f88e1a42SJes Sorensen 
5441f382d43aSMiroslav Rezanina     if (!quiet) {
5442f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
5443f88e1a42SJes Sorensen         print_option_parameters(param);
5444f88e1a42SJes Sorensen         puts("");
5445f382d43aSMiroslav Rezanina     }
5446cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, param, &local_err);
5447cc84d90fSMax Reitz     if (ret == -EFBIG) {
5448cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5449cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5450cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5451f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
5452f3f4d2c0SKevin Wolf         if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
5453f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5454f3f4d2c0SKevin Wolf         }
5455cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5456cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5457cc84d90fSMax Reitz         error_free(local_err);
5458cc84d90fSMax Reitz         local_err = NULL;
5459f88e1a42SJes Sorensen     }
5460f88e1a42SJes Sorensen 
5461f88e1a42SJes Sorensen out:
5462f88e1a42SJes Sorensen     free_option_parameters(create_options);
5463f88e1a42SJes Sorensen     free_option_parameters(param);
5464f88e1a42SJes Sorensen 
546584d18f06SMarkus Armbruster     if (local_err) {
5466cc84d90fSMax Reitz         error_propagate(errp, local_err);
5467cc84d90fSMax Reitz     }
5468f88e1a42SJes Sorensen }
546985d126f3SStefan Hajnoczi 
547085d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
547185d126f3SStefan Hajnoczi {
547285d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
547385d126f3SStefan Hajnoczi     return qemu_get_aio_context();
547485d126f3SStefan Hajnoczi }
5475d616b224SStefan Hajnoczi 
5476d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5477d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5478d616b224SStefan Hajnoczi {
5479d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5480d616b224SStefan Hajnoczi }
54816f176b48SMax Reitz 
54826f176b48SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
54836f176b48SMax Reitz {
54846f176b48SMax Reitz     if (bs->drv->bdrv_amend_options == NULL) {
54856f176b48SMax Reitz         return -ENOTSUP;
54866f176b48SMax Reitz     }
54876f176b48SMax Reitz     return bs->drv->bdrv_amend_options(bs, options);
54886f176b48SMax Reitz }
5489f6186f49SBenoît Canet 
5490b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
5491b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
5492b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
5493b5042a36SBenoît Canet  * node graph.
5494212a5a8fSBenoît Canet  */
5495212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5496212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5497f6186f49SBenoît Canet {
5498b5042a36SBenoît Canet     /* return false if basic checks fails */
5499b5042a36SBenoît Canet     if (!bs || !bs->drv) {
5500b5042a36SBenoît Canet         return false;
5501b5042a36SBenoît Canet     }
5502b5042a36SBenoît Canet 
5503b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
5504b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
5505b5042a36SBenoît Canet      */
5506b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
5507b5042a36SBenoît Canet         return bs == candidate;
5508b5042a36SBenoît Canet     }
5509b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
5510b5042a36SBenoît Canet 
5511b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
5512b5042a36SBenoît Canet      * the node graph.
5513b5042a36SBenoît Canet      */
5514b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
5515212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5516212a5a8fSBenoît Canet     }
5517212a5a8fSBenoît Canet 
5518b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
5519b5042a36SBenoît Canet      */
5520b5042a36SBenoît Canet     return false;
5521212a5a8fSBenoît Canet }
5522212a5a8fSBenoît Canet 
5523212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5524212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5525212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5526212a5a8fSBenoît Canet  */
5527212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5528212a5a8fSBenoît Canet {
5529212a5a8fSBenoît Canet     BlockDriverState *bs;
5530212a5a8fSBenoît Canet 
5531212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5532212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5533212a5a8fSBenoît Canet         bool perm;
5534212a5a8fSBenoît Canet 
5535b5042a36SBenoît Canet         /* try to recurse in this top level bs */
5536e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
5537212a5a8fSBenoît Canet 
5538212a5a8fSBenoît Canet         /* candidate is the first non filter */
5539212a5a8fSBenoît Canet         if (perm) {
5540212a5a8fSBenoît Canet             return true;
5541212a5a8fSBenoît Canet         }
5542212a5a8fSBenoît Canet     }
5543212a5a8fSBenoît Canet 
5544212a5a8fSBenoît Canet     return false;
5545f6186f49SBenoît Canet }
5546