xref: /openbmc/qemu/block.c (revision 77485434206bbbfbb7f6a446866f6a327b062d5e)
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"
27737e150eSPaolo Bonzini #include "block/block_int.h"
28737e150eSPaolo Bonzini #include "block/blockjob.h"
291de7afc9SPaolo Bonzini #include "qemu/module.h"
307b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
31bfb197e0SMarkus Armbruster #include "sysemu/block-backend.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"
38a5ee7bd4SWenchao Xia #include "qapi-event.h"
39fc01f7e7Sbellard 
4071e72a19SJuan Quintela #ifdef CONFIG_BSD
417674e7bfSbellard #include <sys/types.h>
427674e7bfSbellard #include <sys/stat.h>
437674e7bfSbellard #include <sys/ioctl.h>
4472cf2d4fSBlue Swirl #include <sys/queue.h>
45c5e97233Sblueswir1 #ifndef __DragonFly__
467674e7bfSbellard #include <sys/disk.h>
477674e7bfSbellard #endif
48c5e97233Sblueswir1 #endif
497674e7bfSbellard 
5049dc768dSaliguori #ifdef _WIN32
5149dc768dSaliguori #include <windows.h>
5249dc768dSaliguori #endif
5349dc768dSaliguori 
54e4654d2dSFam Zheng struct BdrvDirtyBitmap {
55e4654d2dSFam Zheng     HBitmap *bitmap;
56e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
57e4654d2dSFam Zheng };
58e4654d2dSFam Zheng 
591c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
601c9805a3SStefan Hajnoczi 
617c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
62f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque);
647c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
65f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66097310b5SMarkus Armbruster         BlockCompletionFunc *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);
797c84b1b8SMarkus Armbruster static BlockAIOCB *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,
84097310b5SMarkus Armbruster                                          BlockCompletionFunc *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,
18213af91ebSStefan Hajnoczi                   bdrv_get_aio_context(bs),
183cc0681c4SBenoît Canet                   QEMU_CLOCK_VIRTUAL,
184cc0681c4SBenoît Canet                   bdrv_throttle_read_timer_cb,
185cc0681c4SBenoît Canet                   bdrv_throttle_write_timer_cb,
186cc0681c4SBenoît Canet                   bs);
1870563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1880563e191SZhi Yong Wu }
1890563e191SZhi Yong Wu 
190cc0681c4SBenoît Canet /* This function makes an IO wait if needed
191cc0681c4SBenoît Canet  *
192cc0681c4SBenoît Canet  * @nb_sectors: the number of sectors of the IO
193cc0681c4SBenoît Canet  * @is_write:   is the IO a write
19498f90dbaSZhi Yong Wu  */
195cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs,
196d5103588SKevin Wolf                                      unsigned int bytes,
197cc0681c4SBenoît Canet                                      bool is_write)
198cc0681c4SBenoît Canet {
199cc0681c4SBenoît Canet     /* does this io must wait */
200cc0681c4SBenoît Canet     bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
20198f90dbaSZhi Yong Wu 
202cc0681c4SBenoît Canet     /* if must wait or any request of this type throttled queue the IO */
203cc0681c4SBenoît Canet     if (must_wait ||
204cc0681c4SBenoît Canet         !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
205cc0681c4SBenoît Canet         qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
20698f90dbaSZhi Yong Wu     }
20798f90dbaSZhi Yong Wu 
208cc0681c4SBenoît Canet     /* the IO will be executed, do the accounting */
209d5103588SKevin Wolf     throttle_account(&bs->throttle_state, is_write, bytes);
210d5103588SKevin Wolf 
211cc0681c4SBenoît Canet 
212cc0681c4SBenoît Canet     /* if the next request must wait -> do nothing */
213cc0681c4SBenoît Canet     if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
214cc0681c4SBenoît Canet         return;
215cc0681c4SBenoît Canet     }
216cc0681c4SBenoît Canet 
217cc0681c4SBenoît Canet     /* else queue next request for execution */
218cc0681c4SBenoît Canet     qemu_co_queue_next(&bs->throttled_reqs[is_write]);
21998f90dbaSZhi Yong Wu }
22098f90dbaSZhi Yong Wu 
221339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
222339064d5SKevin Wolf {
223339064d5SKevin Wolf     if (!bs || !bs->drv) {
224339064d5SKevin Wolf         /* 4k should be on the safe side */
225339064d5SKevin Wolf         return 4096;
226339064d5SKevin Wolf     }
227339064d5SKevin Wolf 
228339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
229339064d5SKevin Wolf }
230339064d5SKevin Wolf 
2319e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
2329e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2339e0b22f4SStefan Hajnoczi {
234947995c0SPaolo Bonzini     const char *p;
235947995c0SPaolo Bonzini 
2369e0b22f4SStefan Hajnoczi #ifdef _WIN32
2379e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2389e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2399e0b22f4SStefan Hajnoczi         return 0;
2409e0b22f4SStefan Hajnoczi     }
241947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
242947995c0SPaolo Bonzini #else
243947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2449e0b22f4SStefan Hajnoczi #endif
2459e0b22f4SStefan Hajnoczi 
246947995c0SPaolo Bonzini     return *p == ':';
2479e0b22f4SStefan Hajnoczi }
2489e0b22f4SStefan Hajnoczi 
24983f64091Sbellard int path_is_absolute(const char *path)
25083f64091Sbellard {
25121664424Sbellard #ifdef _WIN32
25221664424Sbellard     /* specific case for names like: "\\.\d:" */
253f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
25421664424Sbellard         return 1;
255f53f4da9SPaolo Bonzini     }
256f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2573b9f94e1Sbellard #else
258f53f4da9SPaolo Bonzini     return (*path == '/');
2593b9f94e1Sbellard #endif
26083f64091Sbellard }
26183f64091Sbellard 
26283f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
26383f64091Sbellard    path to it by considering it is relative to base_path. URL are
26483f64091Sbellard    supported. */
26583f64091Sbellard void path_combine(char *dest, int dest_size,
26683f64091Sbellard                   const char *base_path,
26783f64091Sbellard                   const char *filename)
26883f64091Sbellard {
26983f64091Sbellard     const char *p, *p1;
27083f64091Sbellard     int len;
27183f64091Sbellard 
27283f64091Sbellard     if (dest_size <= 0)
27383f64091Sbellard         return;
27483f64091Sbellard     if (path_is_absolute(filename)) {
27583f64091Sbellard         pstrcpy(dest, dest_size, filename);
27683f64091Sbellard     } else {
27783f64091Sbellard         p = strchr(base_path, ':');
27883f64091Sbellard         if (p)
27983f64091Sbellard             p++;
28083f64091Sbellard         else
28183f64091Sbellard             p = base_path;
2823b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2833b9f94e1Sbellard #ifdef _WIN32
2843b9f94e1Sbellard         {
2853b9f94e1Sbellard             const char *p2;
2863b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2873b9f94e1Sbellard             if (!p1 || p2 > p1)
2883b9f94e1Sbellard                 p1 = p2;
2893b9f94e1Sbellard         }
2903b9f94e1Sbellard #endif
29183f64091Sbellard         if (p1)
29283f64091Sbellard             p1++;
29383f64091Sbellard         else
29483f64091Sbellard             p1 = base_path;
29583f64091Sbellard         if (p1 > p)
29683f64091Sbellard             p = p1;
29783f64091Sbellard         len = p - base_path;
29883f64091Sbellard         if (len > dest_size - 1)
29983f64091Sbellard             len = dest_size - 1;
30083f64091Sbellard         memcpy(dest, base_path, len);
30183f64091Sbellard         dest[len] = '\0';
30283f64091Sbellard         pstrcat(dest, dest_size, filename);
30383f64091Sbellard     }
30483f64091Sbellard }
30583f64091Sbellard 
306dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
307dc5a1371SPaolo Bonzini {
308dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
309dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
310dc5a1371SPaolo Bonzini     } else {
311dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
312dc5a1371SPaolo Bonzini     }
313dc5a1371SPaolo Bonzini }
314dc5a1371SPaolo Bonzini 
3155efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
316ea2384d3Sbellard {
3178c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
3188c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
319f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
320f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
321f9f05dc5SKevin Wolf 
322f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
323f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
324f8c35c1dSStefan Hajnoczi          */
325f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
32683f64091Sbellard             /* add AIO emulation layer */
327f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
328f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
32983f64091Sbellard         }
330f9f05dc5SKevin Wolf     }
331b2e12bc6SChristoph Hellwig 
3328a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
333ea2384d3Sbellard }
334b338082bSbellard 
3357f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
336fc01f7e7Sbellard {
3377f06d47eSMarkus Armbruster     BlockDriverState *bs = bdrv_new();
338e4e9986bSMarkus Armbruster 
339e4e9986bSMarkus Armbruster     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
340e4e9986bSMarkus Armbruster     return bs;
341e4e9986bSMarkus Armbruster }
342e4e9986bSMarkus Armbruster 
343e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
344e4e9986bSMarkus Armbruster {
345e4e9986bSMarkus Armbruster     BlockDriverState *bs;
346e4e9986bSMarkus Armbruster     int i;
347e4e9986bSMarkus Armbruster 
3485839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
349e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
350fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
351fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
352fbe40ff7SFam Zheng     }
35328a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
354d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
355d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
356cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
357cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3589fcb0251SFam Zheng     bs->refcnt = 1;
359dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
360d7d512f6SPaolo Bonzini 
361b338082bSbellard     return bs;
362b338082bSbellard }
363b338082bSbellard 
364d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
365d7d512f6SPaolo Bonzini {
366d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
367d7d512f6SPaolo Bonzini }
368d7d512f6SPaolo Bonzini 
369ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
370ea2384d3Sbellard {
371ea2384d3Sbellard     BlockDriver *drv1;
3728a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3738a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
374ea2384d3Sbellard             return drv1;
375ea2384d3Sbellard         }
3768a22f02aSStefan Hajnoczi     }
377ea2384d3Sbellard     return NULL;
378ea2384d3Sbellard }
379ea2384d3Sbellard 
380b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
381eb852011SMarkus Armbruster {
382b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
383b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
384b64ec4e4SFam Zheng     };
385b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
386b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
387eb852011SMarkus Armbruster     };
388eb852011SMarkus Armbruster     const char **p;
389eb852011SMarkus Armbruster 
390b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
391eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
392b64ec4e4SFam Zheng     }
393eb852011SMarkus Armbruster 
394b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
395eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
396eb852011SMarkus Armbruster             return 1;
397eb852011SMarkus Armbruster         }
398eb852011SMarkus Armbruster     }
399b64ec4e4SFam Zheng     if (read_only) {
400b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
401b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
402b64ec4e4SFam Zheng                 return 1;
403b64ec4e4SFam Zheng             }
404b64ec4e4SFam Zheng         }
405b64ec4e4SFam Zheng     }
406eb852011SMarkus Armbruster     return 0;
407eb852011SMarkus Armbruster }
408eb852011SMarkus Armbruster 
409b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
410b64ec4e4SFam Zheng                                           bool read_only)
411eb852011SMarkus Armbruster {
412eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
413b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
414eb852011SMarkus Armbruster }
415eb852011SMarkus Armbruster 
4165b7e1542SZhi Yong Wu typedef struct CreateCo {
4175b7e1542SZhi Yong Wu     BlockDriver *drv;
4185b7e1542SZhi Yong Wu     char *filename;
41983d0521aSChunyan Liu     QemuOpts *opts;
4205b7e1542SZhi Yong Wu     int ret;
421cc84d90fSMax Reitz     Error *err;
4225b7e1542SZhi Yong Wu } CreateCo;
4235b7e1542SZhi Yong Wu 
4245b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4255b7e1542SZhi Yong Wu {
426cc84d90fSMax Reitz     Error *local_err = NULL;
427cc84d90fSMax Reitz     int ret;
428cc84d90fSMax Reitz 
4295b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4305b7e1542SZhi Yong Wu     assert(cco->drv);
4315b7e1542SZhi Yong Wu 
432c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
43384d18f06SMarkus Armbruster     if (local_err) {
434cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
435cc84d90fSMax Reitz     }
436cc84d90fSMax Reitz     cco->ret = ret;
4375b7e1542SZhi Yong Wu }
4385b7e1542SZhi Yong Wu 
4390e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
44083d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
441ea2384d3Sbellard {
4425b7e1542SZhi Yong Wu     int ret;
4430e7e1989SKevin Wolf 
4445b7e1542SZhi Yong Wu     Coroutine *co;
4455b7e1542SZhi Yong Wu     CreateCo cco = {
4465b7e1542SZhi Yong Wu         .drv = drv,
4475b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
44883d0521aSChunyan Liu         .opts = opts,
4495b7e1542SZhi Yong Wu         .ret = NOT_DONE,
450cc84d90fSMax Reitz         .err = NULL,
4515b7e1542SZhi Yong Wu     };
4525b7e1542SZhi Yong Wu 
453c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
454cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
45580168bffSLuiz Capitulino         ret = -ENOTSUP;
45680168bffSLuiz Capitulino         goto out;
4575b7e1542SZhi Yong Wu     }
4585b7e1542SZhi Yong Wu 
4595b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4605b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4615b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4625b7e1542SZhi Yong Wu     } else {
4635b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4645b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4655b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
466b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
4675b7e1542SZhi Yong Wu         }
4685b7e1542SZhi Yong Wu     }
4695b7e1542SZhi Yong Wu 
4705b7e1542SZhi Yong Wu     ret = cco.ret;
471cc84d90fSMax Reitz     if (ret < 0) {
47284d18f06SMarkus Armbruster         if (cco.err) {
473cc84d90fSMax Reitz             error_propagate(errp, cco.err);
474cc84d90fSMax Reitz         } else {
475cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
476cc84d90fSMax Reitz         }
477cc84d90fSMax Reitz     }
4785b7e1542SZhi Yong Wu 
47980168bffSLuiz Capitulino out:
48080168bffSLuiz Capitulino     g_free(cco.filename);
4815b7e1542SZhi Yong Wu     return ret;
482ea2384d3Sbellard }
483ea2384d3Sbellard 
484c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
48584a12e66SChristoph Hellwig {
48684a12e66SChristoph Hellwig     BlockDriver *drv;
487cc84d90fSMax Reitz     Error *local_err = NULL;
488cc84d90fSMax Reitz     int ret;
48984a12e66SChristoph Hellwig 
49098289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
49184a12e66SChristoph Hellwig     if (drv == NULL) {
492cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
49316905d71SStefan Hajnoczi         return -ENOENT;
49484a12e66SChristoph Hellwig     }
49584a12e66SChristoph Hellwig 
496c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
49784d18f06SMarkus Armbruster     if (local_err) {
498cc84d90fSMax Reitz         error_propagate(errp, local_err);
499cc84d90fSMax Reitz     }
500cc84d90fSMax Reitz     return ret;
50184a12e66SChristoph Hellwig }
50284a12e66SChristoph Hellwig 
5033baca891SKevin Wolf void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
504d34682cdSKevin Wolf {
505d34682cdSKevin Wolf     BlockDriver *drv = bs->drv;
5063baca891SKevin Wolf     Error *local_err = NULL;
507d34682cdSKevin Wolf 
508d34682cdSKevin Wolf     memset(&bs->bl, 0, sizeof(bs->bl));
509d34682cdSKevin Wolf 
510466ad822SKevin Wolf     if (!drv) {
5113baca891SKevin Wolf         return;
512466ad822SKevin Wolf     }
513466ad822SKevin Wolf 
514466ad822SKevin Wolf     /* Take some limits from the children as a default */
515466ad822SKevin Wolf     if (bs->file) {
5163baca891SKevin Wolf         bdrv_refresh_limits(bs->file, &local_err);
5173baca891SKevin Wolf         if (local_err) {
5183baca891SKevin Wolf             error_propagate(errp, local_err);
5193baca891SKevin Wolf             return;
5203baca891SKevin Wolf         }
521466ad822SKevin Wolf         bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
5222647fab5SPeter Lieven         bs->bl.max_transfer_length = bs->file->bl.max_transfer_length;
523339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
524339064d5SKevin Wolf     } else {
525339064d5SKevin Wolf         bs->bl.opt_mem_alignment = 512;
526466ad822SKevin Wolf     }
527466ad822SKevin Wolf 
528466ad822SKevin Wolf     if (bs->backing_hd) {
5293baca891SKevin Wolf         bdrv_refresh_limits(bs->backing_hd, &local_err);
5303baca891SKevin Wolf         if (local_err) {
5313baca891SKevin Wolf             error_propagate(errp, local_err);
5323baca891SKevin Wolf             return;
5333baca891SKevin Wolf         }
534466ad822SKevin Wolf         bs->bl.opt_transfer_length =
535466ad822SKevin Wolf             MAX(bs->bl.opt_transfer_length,
536466ad822SKevin Wolf                 bs->backing_hd->bl.opt_transfer_length);
5372647fab5SPeter Lieven         bs->bl.max_transfer_length =
5382647fab5SPeter Lieven             MIN_NON_ZERO(bs->bl.max_transfer_length,
5392647fab5SPeter Lieven                          bs->backing_hd->bl.max_transfer_length);
540339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
541339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
542339064d5SKevin Wolf                 bs->backing_hd->bl.opt_mem_alignment);
543466ad822SKevin Wolf     }
544466ad822SKevin Wolf 
545466ad822SKevin Wolf     /* Then let the driver override it */
546466ad822SKevin Wolf     if (drv->bdrv_refresh_limits) {
5473baca891SKevin Wolf         drv->bdrv_refresh_limits(bs, errp);
548d34682cdSKevin Wolf     }
549d34682cdSKevin Wolf }
550d34682cdSKevin Wolf 
551eba25057SJim Meyering /*
552eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
553eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
554eba25057SJim Meyering  */
555eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
556eba25057SJim Meyering {
557d5249393Sbellard #ifdef _WIN32
5583b9f94e1Sbellard     char temp_dir[MAX_PATH];
559eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
560eba25057SJim Meyering        have length MAX_PATH or greater.  */
561eba25057SJim Meyering     assert(size >= MAX_PATH);
562eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
563eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
564eba25057SJim Meyering             ? 0 : -GetLastError());
565d5249393Sbellard #else
566ea2384d3Sbellard     int fd;
5677ccfb2ebSblueswir1     const char *tmpdir;
5680badc1eeSaurel32     tmpdir = getenv("TMPDIR");
56969bef793SAmit Shah     if (!tmpdir) {
57069bef793SAmit Shah         tmpdir = "/var/tmp";
57169bef793SAmit Shah     }
572eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
573eba25057SJim Meyering         return -EOVERFLOW;
574ea2384d3Sbellard     }
575eba25057SJim Meyering     fd = mkstemp(filename);
576fe235a06SDunrong Huang     if (fd < 0) {
577fe235a06SDunrong Huang         return -errno;
578fe235a06SDunrong Huang     }
579fe235a06SDunrong Huang     if (close(fd) != 0) {
580fe235a06SDunrong Huang         unlink(filename);
581eba25057SJim Meyering         return -errno;
582eba25057SJim Meyering     }
583eba25057SJim Meyering     return 0;
584d5249393Sbellard #endif
585eba25057SJim Meyering }
586ea2384d3Sbellard 
587f3a5d3f8SChristoph Hellwig /*
588f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
589f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
590f3a5d3f8SChristoph Hellwig  */
591f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
592f3a5d3f8SChristoph Hellwig {
593508c7cb3SChristoph Hellwig     int score_max = 0, score;
594508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
595f3a5d3f8SChristoph Hellwig 
5968a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
597508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
598508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
599508c7cb3SChristoph Hellwig             if (score > score_max) {
600508c7cb3SChristoph Hellwig                 score_max = score;
601508c7cb3SChristoph Hellwig                 drv = d;
602f3a5d3f8SChristoph Hellwig             }
603508c7cb3SChristoph Hellwig         }
604f3a5d3f8SChristoph Hellwig     }
605f3a5d3f8SChristoph Hellwig 
606508c7cb3SChristoph Hellwig     return drv;
607f3a5d3f8SChristoph Hellwig }
608f3a5d3f8SChristoph Hellwig 
60998289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
61098289620SKevin Wolf                                 bool allow_protocol_prefix)
61184a12e66SChristoph Hellwig {
61284a12e66SChristoph Hellwig     BlockDriver *drv1;
61384a12e66SChristoph Hellwig     char protocol[128];
61484a12e66SChristoph Hellwig     int len;
61584a12e66SChristoph Hellwig     const char *p;
61684a12e66SChristoph Hellwig 
61766f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
61866f82ceeSKevin Wolf 
61939508e7aSChristoph Hellwig     /*
62039508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
62139508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
62239508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
62339508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
62439508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
62539508e7aSChristoph Hellwig      */
62684a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
62739508e7aSChristoph Hellwig     if (drv1) {
62884a12e66SChristoph Hellwig         return drv1;
62984a12e66SChristoph Hellwig     }
63039508e7aSChristoph Hellwig 
63198289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
63239508e7aSChristoph Hellwig         return bdrv_find_format("file");
63339508e7aSChristoph Hellwig     }
63498289620SKevin Wolf 
6359e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
6369e0b22f4SStefan Hajnoczi     assert(p != NULL);
63784a12e66SChristoph Hellwig     len = p - filename;
63884a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
63984a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
64084a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
64184a12e66SChristoph Hellwig     protocol[len] = '\0';
64284a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
64384a12e66SChristoph Hellwig         if (drv1->protocol_name &&
64484a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
64584a12e66SChristoph Hellwig             return drv1;
64684a12e66SChristoph Hellwig         }
64784a12e66SChristoph Hellwig     }
64884a12e66SChristoph Hellwig     return NULL;
64984a12e66SChristoph Hellwig }
65084a12e66SChristoph Hellwig 
651f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
65234b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
653ea2384d3Sbellard {
654f500a6d3SKevin Wolf     int score, score_max;
655ea2384d3Sbellard     BlockDriver *drv1, *drv;
65683f64091Sbellard     uint8_t buf[2048];
657f500a6d3SKevin Wolf     int ret = 0;
658f8ea0b00SNicholas Bellinger 
65908a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
6608e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
661c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
662c98ac35dSStefan Weil         if (!drv) {
66334b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
664c98ac35dSStefan Weil             ret = -ENOENT;
665c98ac35dSStefan Weil         }
666c98ac35dSStefan Weil         *pdrv = drv;
667c98ac35dSStefan Weil         return ret;
6681a396859SNicholas A. Bellinger     }
669f8ea0b00SNicholas Bellinger 
67083f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
671ea2384d3Sbellard     if (ret < 0) {
67234b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
67334b5d2c6SMax Reitz                          "format");
674c98ac35dSStefan Weil         *pdrv = NULL;
675c98ac35dSStefan Weil         return ret;
676ea2384d3Sbellard     }
677ea2384d3Sbellard 
678ea2384d3Sbellard     score_max = 0;
67984a12e66SChristoph Hellwig     drv = NULL;
6808a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
68183f64091Sbellard         if (drv1->bdrv_probe) {
682ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
683ea2384d3Sbellard             if (score > score_max) {
684ea2384d3Sbellard                 score_max = score;
685ea2384d3Sbellard                 drv = drv1;
686ea2384d3Sbellard             }
687ea2384d3Sbellard         }
68883f64091Sbellard     }
689c98ac35dSStefan Weil     if (!drv) {
69034b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
69134b5d2c6SMax Reitz                    "driver found");
692c98ac35dSStefan Weil         ret = -ENOENT;
693c98ac35dSStefan Weil     }
694c98ac35dSStefan Weil     *pdrv = drv;
695c98ac35dSStefan Weil     return ret;
696ea2384d3Sbellard }
697ea2384d3Sbellard 
69851762288SStefan Hajnoczi /**
69951762288SStefan Hajnoczi  * Set the current 'total_sectors' value
70065a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
70151762288SStefan Hajnoczi  */
70251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
70351762288SStefan Hajnoczi {
70451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
70551762288SStefan Hajnoczi 
706396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
707396759adSNicholas Bellinger     if (bs->sg)
708396759adSNicholas Bellinger         return 0;
709396759adSNicholas Bellinger 
71051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
71151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
71251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
71351762288SStefan Hajnoczi         if (length < 0) {
71451762288SStefan Hajnoczi             return length;
71551762288SStefan Hajnoczi         }
7167e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
71751762288SStefan Hajnoczi     }
71851762288SStefan Hajnoczi 
71951762288SStefan Hajnoczi     bs->total_sectors = hint;
72051762288SStefan Hajnoczi     return 0;
72151762288SStefan Hajnoczi }
72251762288SStefan Hajnoczi 
723c3993cdcSStefan Hajnoczi /**
7249e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
7259e8f1835SPaolo Bonzini  *
7269e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
7279e8f1835SPaolo Bonzini  */
7289e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
7299e8f1835SPaolo Bonzini {
7309e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
7319e8f1835SPaolo Bonzini 
7329e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
7339e8f1835SPaolo Bonzini         /* do nothing */
7349e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
7359e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
7369e8f1835SPaolo Bonzini     } else {
7379e8f1835SPaolo Bonzini         return -1;
7389e8f1835SPaolo Bonzini     }
7399e8f1835SPaolo Bonzini 
7409e8f1835SPaolo Bonzini     return 0;
7419e8f1835SPaolo Bonzini }
7429e8f1835SPaolo Bonzini 
7439e8f1835SPaolo Bonzini /**
744c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
745c3993cdcSStefan Hajnoczi  *
746c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
747c3993cdcSStefan Hajnoczi  */
748c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
749c3993cdcSStefan Hajnoczi {
750c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
751c3993cdcSStefan Hajnoczi 
752c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
753c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
75492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
75592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
756c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
757c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
758c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
759c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
760c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
761c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
762c3993cdcSStefan Hajnoczi         /* this is the default */
763c3993cdcSStefan Hajnoczi     } else {
764c3993cdcSStefan Hajnoczi         return -1;
765c3993cdcSStefan Hajnoczi     }
766c3993cdcSStefan Hajnoczi 
767c3993cdcSStefan Hajnoczi     return 0;
768c3993cdcSStefan Hajnoczi }
769c3993cdcSStefan Hajnoczi 
77053fec9d3SStefan Hajnoczi /**
77153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
77253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
77353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
77453fec9d3SStefan Hajnoczi  */
77553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
77653fec9d3SStefan Hajnoczi {
77753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
77853fec9d3SStefan Hajnoczi }
77953fec9d3SStefan Hajnoczi 
78053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
78153fec9d3SStefan Hajnoczi {
78253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
78353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
78453fec9d3SStefan Hajnoczi }
78553fec9d3SStefan Hajnoczi 
7860b50cc88SKevin Wolf /*
787b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
788b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
789b1e6fc08SKevin Wolf  * like a backing file)
790b1e6fc08SKevin Wolf  */
791b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
792b1e6fc08SKevin Wolf {
793b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
794b1e6fc08SKevin Wolf }
795b1e6fc08SKevin Wolf 
796b1e6fc08SKevin Wolf /*
7970b50cc88SKevin Wolf  * Returns the flags that bs->file should get, based on the given flags for
7980b50cc88SKevin Wolf  * the parent BDS
7990b50cc88SKevin Wolf  */
8000b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags)
8010b50cc88SKevin Wolf {
8020b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
8030b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
8040b50cc88SKevin Wolf 
8050b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
8060b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
8070b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
8080b50cc88SKevin Wolf 
8090b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
8105669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
8110b50cc88SKevin Wolf 
8120b50cc88SKevin Wolf     return flags;
8130b50cc88SKevin Wolf }
8140b50cc88SKevin Wolf 
815317fc44eSKevin Wolf /*
816317fc44eSKevin Wolf  * Returns the flags that bs->backing_hd should get, based on the given flags
817317fc44eSKevin Wolf  * for the parent BDS
818317fc44eSKevin Wolf  */
819317fc44eSKevin Wolf static int bdrv_backing_flags(int flags)
820317fc44eSKevin Wolf {
821317fc44eSKevin Wolf     /* backing files always opened read-only */
822317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
823317fc44eSKevin Wolf 
824317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
8258bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
826317fc44eSKevin Wolf 
827317fc44eSKevin Wolf     return flags;
828317fc44eSKevin Wolf }
829317fc44eSKevin Wolf 
8307b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
8317b272452SKevin Wolf {
8327b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
8337b272452SKevin Wolf 
8347b272452SKevin Wolf     /*
8357b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
8367b272452SKevin Wolf      * image.
8377b272452SKevin Wolf      */
83820cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
8397b272452SKevin Wolf 
8407b272452SKevin Wolf     /*
8417b272452SKevin Wolf      * Snapshots should be writable.
8427b272452SKevin Wolf      */
8438bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
8447b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
8457b272452SKevin Wolf     }
8467b272452SKevin Wolf 
8477b272452SKevin Wolf     return open_flags;
8487b272452SKevin Wolf }
8497b272452SKevin Wolf 
850636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8516913c0c2SBenoît Canet                                   const char *node_name,
8526913c0c2SBenoît Canet                                   Error **errp)
8536913c0c2SBenoît Canet {
8546913c0c2SBenoît Canet     if (!node_name) {
855636ea370SKevin Wolf         return;
8566913c0c2SBenoît Canet     }
8576913c0c2SBenoît Canet 
8589aebf3b8SKevin Wolf     /* Check for empty string or invalid characters */
859f5bebbbbSMarkus Armbruster     if (!id_wellformed(node_name)) {
8609aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
861636ea370SKevin Wolf         return;
8626913c0c2SBenoît Canet     }
8636913c0c2SBenoît Canet 
8640c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8657f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8660c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8670c5e94eeSBenoît Canet                    node_name);
868636ea370SKevin Wolf         return;
8690c5e94eeSBenoît Canet     }
8700c5e94eeSBenoît Canet 
8716913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8726913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8736913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
874636ea370SKevin Wolf         return;
8756913c0c2SBenoît Canet     }
8766913c0c2SBenoît Canet 
8776913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8786913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8796913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
8806913c0c2SBenoît Canet }
8816913c0c2SBenoît Canet 
882b6ce07aaSKevin Wolf /*
88357915332SKevin Wolf  * Common part for opening disk images and files
884b6ad491aSKevin Wolf  *
885b6ad491aSKevin Wolf  * Removes all processed options from *options.
88657915332SKevin Wolf  */
887f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
88834b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
88957915332SKevin Wolf {
89057915332SKevin Wolf     int ret, open_flags;
891035fccdfSKevin Wolf     const char *filename;
8926913c0c2SBenoît Canet     const char *node_name = NULL;
89334b5d2c6SMax Reitz     Error *local_err = NULL;
89457915332SKevin Wolf 
89557915332SKevin Wolf     assert(drv != NULL);
8966405875cSPaolo Bonzini     assert(bs->file == NULL);
897707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
89857915332SKevin Wolf 
89945673671SKevin Wolf     if (file != NULL) {
90045673671SKevin Wolf         filename = file->filename;
90145673671SKevin Wolf     } else {
90245673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
90345673671SKevin Wolf     }
90445673671SKevin Wolf 
905765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
906765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
907765003dbSKevin Wolf                    drv->format_name);
908765003dbSKevin Wolf         return -EINVAL;
909765003dbSKevin Wolf     }
910765003dbSKevin Wolf 
91145673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
91228dcee10SStefan Hajnoczi 
9136913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
914636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9150fb6395cSMarkus Armbruster     if (local_err) {
916636ea370SKevin Wolf         error_propagate(errp, local_err);
917636ea370SKevin Wolf         return -EINVAL;
9186913c0c2SBenoît Canet     }
9196913c0c2SBenoît Canet     qdict_del(options, "node-name");
9206913c0c2SBenoît Canet 
9215d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
9225d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
9235d186eb0SKevin Wolf      * and return immediately. */
9245d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
9255d186eb0SKevin Wolf         bdrv_swap(file, bs);
9265d186eb0SKevin Wolf         return 0;
9275d186eb0SKevin Wolf     }
9285d186eb0SKevin Wolf 
92957915332SKevin Wolf     bs->open_flags = flags;
9301b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
931c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9320d51b4deSAsias He     bs->zero_beyond_eof = true;
933b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
934b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
93520cca275SKevin Wolf     bs->growable = !!(flags & BDRV_O_PROTOCOL);
936b64ec4e4SFam Zheng 
937b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9388f94a6e4SKevin Wolf         error_setg(errp,
9398f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9408f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9418f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9428f94a6e4SKevin Wolf                    drv->format_name);
943b64ec4e4SFam Zheng         return -ENOTSUP;
944b64ec4e4SFam Zheng     }
94557915332SKevin Wolf 
94653fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
9470ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
9480ebd24e0SKevin Wolf         if (!bs->read_only) {
94953fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9500ebd24e0SKevin Wolf         } else {
9510ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
9520ebd24e0SKevin Wolf             return -EINVAL;
9530ebd24e0SKevin Wolf         }
95453fec9d3SStefan Hajnoczi     }
95553fec9d3SStefan Hajnoczi 
956c2ad1b0cSKevin Wolf     if (filename != NULL) {
95757915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
958c2ad1b0cSKevin Wolf     } else {
959c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
960c2ad1b0cSKevin Wolf     }
96191af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
96257915332SKevin Wolf 
96357915332SKevin Wolf     bs->drv = drv;
9647267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
96557915332SKevin Wolf 
96603f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
967e7c63796SStefan Hajnoczi 
96866f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
96966f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9705d186eb0SKevin Wolf         assert(file == NULL);
971030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
97234b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
973f500a6d3SKevin Wolf     } else {
9742af5ef70SKevin Wolf         if (file == NULL) {
97534b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
97634b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9772af5ef70SKevin Wolf             ret = -EINVAL;
9782af5ef70SKevin Wolf             goto free_and_fail;
9792af5ef70SKevin Wolf         }
980f500a6d3SKevin Wolf         bs->file = file;
98134b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
98266f82ceeSKevin Wolf     }
98366f82ceeSKevin Wolf 
98457915332SKevin Wolf     if (ret < 0) {
98584d18f06SMarkus Armbruster         if (local_err) {
98634b5d2c6SMax Reitz             error_propagate(errp, local_err);
9872fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9882fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
98934b5d2c6SMax Reitz         } else {
99034b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
99134b5d2c6SMax Reitz         }
99257915332SKevin Wolf         goto free_and_fail;
99357915332SKevin Wolf     }
99457915332SKevin Wolf 
99551762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
99651762288SStefan Hajnoczi     if (ret < 0) {
99734b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
99851762288SStefan Hajnoczi         goto free_and_fail;
99957915332SKevin Wolf     }
100051762288SStefan Hajnoczi 
10013baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10023baca891SKevin Wolf     if (local_err) {
10033baca891SKevin Wolf         error_propagate(errp, local_err);
10043baca891SKevin Wolf         ret = -EINVAL;
10053baca891SKevin Wolf         goto free_and_fail;
10063baca891SKevin Wolf     }
10073baca891SKevin Wolf 
1008c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
100947ea2de2SKevin Wolf     assert((bs->request_alignment != 0) || bs->sg);
101057915332SKevin Wolf     return 0;
101157915332SKevin Wolf 
101257915332SKevin Wolf free_and_fail:
101366f82ceeSKevin Wolf     bs->file = NULL;
10147267c094SAnthony Liguori     g_free(bs->opaque);
101557915332SKevin Wolf     bs->opaque = NULL;
101657915332SKevin Wolf     bs->drv = NULL;
101757915332SKevin Wolf     return ret;
101857915332SKevin Wolf }
101957915332SKevin Wolf 
10205e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10215e5c4f63SKevin Wolf {
10225e5c4f63SKevin Wolf     QObject *options_obj;
10235e5c4f63SKevin Wolf     QDict *options;
10245e5c4f63SKevin Wolf     int ret;
10255e5c4f63SKevin Wolf 
10265e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10275e5c4f63SKevin Wolf     assert(ret);
10285e5c4f63SKevin Wolf 
10295e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10305e5c4f63SKevin Wolf     if (!options_obj) {
10315e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10325e5c4f63SKevin Wolf         return NULL;
10335e5c4f63SKevin Wolf     }
10345e5c4f63SKevin Wolf 
10355e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10365e5c4f63SKevin Wolf         qobject_decref(options_obj);
10375e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10385e5c4f63SKevin Wolf         return NULL;
10395e5c4f63SKevin Wolf     }
10405e5c4f63SKevin Wolf 
10415e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10425e5c4f63SKevin Wolf     qdict_flatten(options);
10435e5c4f63SKevin Wolf 
10445e5c4f63SKevin Wolf     return options;
10455e5c4f63SKevin Wolf }
10465e5c4f63SKevin Wolf 
104757915332SKevin Wolf /*
1048f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1049f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
1050f54120ffSKevin Wolf  */
10515e5c4f63SKevin Wolf static int bdrv_fill_options(QDict **options, const char **pfilename, int flags,
105217b005f1SKevin Wolf                              BlockDriver *drv, Error **errp)
1053f54120ffSKevin Wolf {
10545e5c4f63SKevin Wolf     const char *filename = *pfilename;
1055f54120ffSKevin Wolf     const char *drvname;
1056462f5bcfSKevin Wolf     bool protocol = flags & BDRV_O_PROTOCOL;
1057f54120ffSKevin Wolf     bool parse_filename = false;
1058f54120ffSKevin Wolf     Error *local_err = NULL;
1059f54120ffSKevin Wolf 
10605e5c4f63SKevin Wolf     /* Parse json: pseudo-protocol */
10615e5c4f63SKevin Wolf     if (filename && g_str_has_prefix(filename, "json:")) {
10625e5c4f63SKevin Wolf         QDict *json_options = parse_json_filename(filename, &local_err);
10635e5c4f63SKevin Wolf         if (local_err) {
10645e5c4f63SKevin Wolf             error_propagate(errp, local_err);
10655e5c4f63SKevin Wolf             return -EINVAL;
10665e5c4f63SKevin Wolf         }
10675e5c4f63SKevin Wolf 
10685e5c4f63SKevin Wolf         /* Options given in the filename have lower priority than options
10695e5c4f63SKevin Wolf          * specified directly */
10705e5c4f63SKevin Wolf         qdict_join(*options, json_options, false);
10715e5c4f63SKevin Wolf         QDECREF(json_options);
10725e5c4f63SKevin Wolf         *pfilename = filename = NULL;
10735e5c4f63SKevin Wolf     }
10745e5c4f63SKevin Wolf 
1075f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
107617b005f1SKevin Wolf     if (protocol && filename) {
1077f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1078f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1079f54120ffSKevin Wolf             parse_filename = true;
1080f54120ffSKevin Wolf         } else {
1081f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1082f54120ffSKevin Wolf                              "the same time");
1083f54120ffSKevin Wolf             return -EINVAL;
1084f54120ffSKevin Wolf         }
1085f54120ffSKevin Wolf     }
1086f54120ffSKevin Wolf 
1087f54120ffSKevin Wolf     /* Find the right block driver */
1088f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1089f54120ffSKevin Wolf     drvname = qdict_get_try_str(*options, "driver");
1090f54120ffSKevin Wolf 
109117b005f1SKevin Wolf     if (drv) {
109217b005f1SKevin Wolf         if (drvname) {
109317b005f1SKevin Wolf             error_setg(errp, "Driver specified twice");
109417b005f1SKevin Wolf             return -EINVAL;
109517b005f1SKevin Wolf         }
109617b005f1SKevin Wolf         drvname = drv->format_name;
109717b005f1SKevin Wolf         qdict_put(*options, "driver", qstring_from_str(drvname));
109817b005f1SKevin Wolf     } else {
109917b005f1SKevin Wolf         if (!drvname && protocol) {
1100f54120ffSKevin Wolf             if (filename) {
1101f54120ffSKevin Wolf                 drv = bdrv_find_protocol(filename, parse_filename);
1102f54120ffSKevin Wolf                 if (!drv) {
1103f54120ffSKevin Wolf                     error_setg(errp, "Unknown protocol");
1104f54120ffSKevin Wolf                     return -EINVAL;
1105f54120ffSKevin Wolf                 }
1106f54120ffSKevin Wolf 
1107f54120ffSKevin Wolf                 drvname = drv->format_name;
1108f54120ffSKevin Wolf                 qdict_put(*options, "driver", qstring_from_str(drvname));
1109f54120ffSKevin Wolf             } else {
1110f54120ffSKevin Wolf                 error_setg(errp, "Must specify either driver or file");
1111f54120ffSKevin Wolf                 return -EINVAL;
1112f54120ffSKevin Wolf             }
111317b005f1SKevin Wolf         } else if (drvname) {
1114f54120ffSKevin Wolf             drv = bdrv_find_format(drvname);
1115f54120ffSKevin Wolf             if (!drv) {
1116f54120ffSKevin Wolf                 error_setg(errp, "Unknown driver '%s'", drvname);
1117f54120ffSKevin Wolf                 return -ENOENT;
1118f54120ffSKevin Wolf             }
111917b005f1SKevin Wolf         }
112017b005f1SKevin Wolf     }
112117b005f1SKevin Wolf 
112217b005f1SKevin Wolf     assert(drv || !protocol);
1123f54120ffSKevin Wolf 
1124f54120ffSKevin Wolf     /* Driver-specific filename parsing */
112517b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1126f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1127f54120ffSKevin Wolf         if (local_err) {
1128f54120ffSKevin Wolf             error_propagate(errp, local_err);
1129f54120ffSKevin Wolf             return -EINVAL;
1130f54120ffSKevin Wolf         }
1131f54120ffSKevin Wolf 
1132f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1133f54120ffSKevin Wolf             qdict_del(*options, "filename");
1134f54120ffSKevin Wolf         }
1135f54120ffSKevin Wolf     }
1136f54120ffSKevin Wolf 
1137f54120ffSKevin Wolf     return 0;
1138f54120ffSKevin Wolf }
1139f54120ffSKevin Wolf 
11408d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
11418d24cce1SFam Zheng {
11428d24cce1SFam Zheng 
1143826b6ca0SFam Zheng     if (bs->backing_hd) {
1144826b6ca0SFam Zheng         assert(bs->backing_blocker);
1145826b6ca0SFam Zheng         bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker);
1146826b6ca0SFam Zheng     } else if (backing_hd) {
1147826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
1148826b6ca0SFam Zheng                    "device is used as backing hd of '%s'",
1149bfb197e0SMarkus Armbruster                    bdrv_get_device_name(bs));
1150826b6ca0SFam Zheng     }
1151826b6ca0SFam Zheng 
11528d24cce1SFam Zheng     bs->backing_hd = backing_hd;
11538d24cce1SFam Zheng     if (!backing_hd) {
1154826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1155826b6ca0SFam Zheng         bs->backing_blocker = NULL;
11568d24cce1SFam Zheng         goto out;
11578d24cce1SFam Zheng     }
11588d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
11598d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
11608d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
11618d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1162826b6ca0SFam Zheng 
1163826b6ca0SFam Zheng     bdrv_op_block_all(bs->backing_hd, bs->backing_blocker);
1164826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1165826b6ca0SFam Zheng     bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT,
1166826b6ca0SFam Zheng                     bs->backing_blocker);
11678d24cce1SFam Zheng out:
11683baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
11698d24cce1SFam Zheng }
11708d24cce1SFam Zheng 
117131ca6d07SKevin Wolf /*
117231ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
117331ca6d07SKevin Wolf  *
117431ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
117531ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
117631ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
117731ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
117831ca6d07SKevin Wolf  */
117934b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
11809156df12SPaolo Bonzini {
11811ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1182317fc44eSKevin Wolf     int ret = 0;
11839156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
11848d24cce1SFam Zheng     BlockDriverState *backing_hd;
118534b5d2c6SMax Reitz     Error *local_err = NULL;
11869156df12SPaolo Bonzini 
11879156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
118831ca6d07SKevin Wolf         QDECREF(options);
11891ba4b6a5SBenoît Canet         goto free_exit;
11909156df12SPaolo Bonzini     }
11919156df12SPaolo Bonzini 
119231ca6d07SKevin Wolf     /* NULL means an empty set of options */
119331ca6d07SKevin Wolf     if (options == NULL) {
119431ca6d07SKevin Wolf         options = qdict_new();
119531ca6d07SKevin Wolf     }
119631ca6d07SKevin Wolf 
11979156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
11981cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
11991cb6f506SKevin Wolf         backing_filename[0] = '\0';
12001cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
120131ca6d07SKevin Wolf         QDECREF(options);
12021ba4b6a5SBenoît Canet         goto free_exit;
1203dbecebddSFam Zheng     } else {
12041ba4b6a5SBenoît Canet         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX);
12059156df12SPaolo Bonzini     }
12069156df12SPaolo Bonzini 
12078ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
12088ee79e70SKevin Wolf         ret = -EINVAL;
12098ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
12108ee79e70SKevin Wolf         QDECREF(options);
12118ee79e70SKevin Wolf         goto free_exit;
12128ee79e70SKevin Wolf     }
12138ee79e70SKevin Wolf 
1214e4e9986bSMarkus Armbruster     backing_hd = bdrv_new();
12158d24cce1SFam Zheng 
12169156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
12179156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
12189156df12SPaolo Bonzini     }
12199156df12SPaolo Bonzini 
1220f67503e5SMax Reitz     assert(bs->backing_hd == NULL);
12218d24cce1SFam Zheng     ret = bdrv_open(&backing_hd,
1222ddf5636dSMax Reitz                     *backing_filename ? backing_filename : NULL, NULL, options,
1223317fc44eSKevin Wolf                     bdrv_backing_flags(bs->open_flags), back_drv, &local_err);
12249156df12SPaolo Bonzini     if (ret < 0) {
12258d24cce1SFam Zheng         bdrv_unref(backing_hd);
12268d24cce1SFam Zheng         backing_hd = NULL;
12279156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1228b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1229b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1230b04b6b6eSFam Zheng         error_free(local_err);
12311ba4b6a5SBenoît Canet         goto free_exit;
12329156df12SPaolo Bonzini     }
12338d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
1234d80ac658SPeter Feiner 
12351ba4b6a5SBenoît Canet free_exit:
12361ba4b6a5SBenoît Canet     g_free(backing_filename);
12371ba4b6a5SBenoît Canet     return ret;
12389156df12SPaolo Bonzini }
12399156df12SPaolo Bonzini 
1240b6ce07aaSKevin Wolf /*
1241da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1242da557aacSMax Reitz  * device's options.
1243da557aacSMax Reitz  *
1244da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1245da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1246da557aacSMax Reitz  *
1247da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1248da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1249da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1250da557aacSMax Reitz  * BlockdevRef.
1251da557aacSMax Reitz  *
1252da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1253f67503e5SMax Reitz  *
1254f67503e5SMax Reitz  * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
1255da557aacSMax Reitz  */
1256da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1257da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1258f7d9fd8cSMax Reitz                     bool allow_none, Error **errp)
1259da557aacSMax Reitz {
1260da557aacSMax Reitz     QDict *image_options;
1261da557aacSMax Reitz     int ret;
1262da557aacSMax Reitz     char *bdref_key_dot;
1263da557aacSMax Reitz     const char *reference;
1264da557aacSMax Reitz 
1265f67503e5SMax Reitz     assert(pbs);
1266f67503e5SMax Reitz     assert(*pbs == NULL);
1267f67503e5SMax Reitz 
1268da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1269da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1270da557aacSMax Reitz     g_free(bdref_key_dot);
1271da557aacSMax Reitz 
1272da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1273da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1274da557aacSMax Reitz         if (allow_none) {
1275da557aacSMax Reitz             ret = 0;
1276da557aacSMax Reitz         } else {
1277da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1278da557aacSMax Reitz                        bdref_key);
1279da557aacSMax Reitz             ret = -EINVAL;
1280da557aacSMax Reitz         }
1281b20e61e0SMarkus Armbruster         QDECREF(image_options);
1282da557aacSMax Reitz         goto done;
1283da557aacSMax Reitz     }
1284da557aacSMax Reitz 
1285f7d9fd8cSMax Reitz     ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
1286da557aacSMax Reitz 
1287da557aacSMax Reitz done:
1288da557aacSMax Reitz     qdict_del(options, bdref_key);
1289da557aacSMax Reitz     return ret;
1290da557aacSMax Reitz }
1291da557aacSMax Reitz 
12926b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1293b998875dSKevin Wolf {
1294b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
12951ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1296b998875dSKevin Wolf     int64_t total_size;
1297b998875dSKevin Wolf     BlockDriver *bdrv_qcow2;
129883d0521aSChunyan Liu     QemuOpts *opts = NULL;
1299b998875dSKevin Wolf     QDict *snapshot_options;
1300b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1301b998875dSKevin Wolf     Error *local_err;
1302b998875dSKevin Wolf     int ret;
1303b998875dSKevin Wolf 
1304b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1305b998875dSKevin Wolf        instead of opening 'filename' directly */
1306b998875dSKevin Wolf 
1307b998875dSKevin Wolf     /* Get the required size from the image */
1308f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1309f187743aSKevin Wolf     if (total_size < 0) {
13106b8aeca5SChen Gang         ret = total_size;
1311f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
13121ba4b6a5SBenoît Canet         goto out;
1313f187743aSKevin Wolf     }
1314b998875dSKevin Wolf 
1315b998875dSKevin Wolf     /* Create the temporary image */
13161ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1317b998875dSKevin Wolf     if (ret < 0) {
1318b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
13191ba4b6a5SBenoît Canet         goto out;
1320b998875dSKevin Wolf     }
1321b998875dSKevin Wolf 
1322b998875dSKevin Wolf     bdrv_qcow2 = bdrv_find_format("qcow2");
1323c282e1fdSChunyan Liu     opts = qemu_opts_create(bdrv_qcow2->create_opts, NULL, 0,
1324c282e1fdSChunyan Liu                             &error_abort);
132583d0521aSChunyan Liu     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size);
1326c282e1fdSChunyan Liu     ret = bdrv_create(bdrv_qcow2, tmp_filename, opts, &local_err);
132783d0521aSChunyan Liu     qemu_opts_del(opts);
1328b998875dSKevin Wolf     if (ret < 0) {
1329b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1330b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1331b998875dSKevin Wolf                          error_get_pretty(local_err));
1332b998875dSKevin Wolf         error_free(local_err);
13331ba4b6a5SBenoît Canet         goto out;
1334b998875dSKevin Wolf     }
1335b998875dSKevin Wolf 
1336b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1337b998875dSKevin Wolf     snapshot_options = qdict_new();
1338b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1339b998875dSKevin Wolf               qstring_from_str("file"));
1340b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1341b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1342b998875dSKevin Wolf 
1343e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1344b998875dSKevin Wolf 
1345b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
1346b1e6fc08SKevin Wolf                     flags, bdrv_qcow2, &local_err);
1347b998875dSKevin Wolf     if (ret < 0) {
1348b998875dSKevin Wolf         error_propagate(errp, local_err);
13491ba4b6a5SBenoît Canet         goto out;
1350b998875dSKevin Wolf     }
1351b998875dSKevin Wolf 
1352b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
13531ba4b6a5SBenoît Canet 
13541ba4b6a5SBenoît Canet out:
13551ba4b6a5SBenoît Canet     g_free(tmp_filename);
13566b8aeca5SChen Gang     return ret;
1357b998875dSKevin Wolf }
1358b998875dSKevin Wolf 
1359da557aacSMax Reitz /*
1360b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1361de9c0cecSKevin Wolf  *
1362de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1363de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1364de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1365de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1366f67503e5SMax Reitz  *
1367f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1368f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1369ddf5636dSMax Reitz  *
1370ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1371ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1372ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1373b6ce07aaSKevin Wolf  */
1374ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename,
1375ddf5636dSMax Reitz               const char *reference, QDict *options, int flags,
1376ddf5636dSMax Reitz               BlockDriver *drv, Error **errp)
1377ea2384d3Sbellard {
1378b6ce07aaSKevin Wolf     int ret;
1379f67503e5SMax Reitz     BlockDriverState *file = NULL, *bs;
138074fe54f2SKevin Wolf     const char *drvname;
138134b5d2c6SMax Reitz     Error *local_err = NULL;
1382b1e6fc08SKevin Wolf     int snapshot_flags = 0;
138333e3963eSbellard 
1384f67503e5SMax Reitz     assert(pbs);
1385f67503e5SMax Reitz 
1386ddf5636dSMax Reitz     if (reference) {
1387ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1388ddf5636dSMax Reitz         QDECREF(options);
1389ddf5636dSMax Reitz 
1390ddf5636dSMax Reitz         if (*pbs) {
1391ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1392ddf5636dSMax Reitz                        "another block device");
1393ddf5636dSMax Reitz             return -EINVAL;
1394ddf5636dSMax Reitz         }
1395ddf5636dSMax Reitz 
1396ddf5636dSMax Reitz         if (filename || options_non_empty) {
1397ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1398ddf5636dSMax Reitz                        "additional options or a new filename");
1399ddf5636dSMax Reitz             return -EINVAL;
1400ddf5636dSMax Reitz         }
1401ddf5636dSMax Reitz 
1402ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1403ddf5636dSMax Reitz         if (!bs) {
1404ddf5636dSMax Reitz             return -ENODEV;
1405ddf5636dSMax Reitz         }
1406ddf5636dSMax Reitz         bdrv_ref(bs);
1407ddf5636dSMax Reitz         *pbs = bs;
1408ddf5636dSMax Reitz         return 0;
1409ddf5636dSMax Reitz     }
1410ddf5636dSMax Reitz 
1411f67503e5SMax Reitz     if (*pbs) {
1412f67503e5SMax Reitz         bs = *pbs;
1413f67503e5SMax Reitz     } else {
1414e4e9986bSMarkus Armbruster         bs = bdrv_new();
1415f67503e5SMax Reitz     }
1416f67503e5SMax Reitz 
1417de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1418de9c0cecSKevin Wolf     if (options == NULL) {
1419de9c0cecSKevin Wolf         options = qdict_new();
1420de9c0cecSKevin Wolf     }
1421de9c0cecSKevin Wolf 
142217b005f1SKevin Wolf     ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err);
1423462f5bcfSKevin Wolf     if (local_err) {
1424462f5bcfSKevin Wolf         goto fail;
1425462f5bcfSKevin Wolf     }
1426462f5bcfSKevin Wolf 
142776c591b0SKevin Wolf     /* Find the right image format driver */
142876c591b0SKevin Wolf     drv = NULL;
142976c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
143076c591b0SKevin Wolf     if (drvname) {
143176c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
143276c591b0SKevin Wolf         qdict_del(options, "driver");
143376c591b0SKevin Wolf         if (!drv) {
143476c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
143576c591b0SKevin Wolf             ret = -EINVAL;
143676c591b0SKevin Wolf             goto fail;
143776c591b0SKevin Wolf         }
143876c591b0SKevin Wolf     }
143976c591b0SKevin Wolf 
144076c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
144176c591b0SKevin Wolf     if (drv && !drv->bdrv_file_open) {
144276c591b0SKevin Wolf         /* If the user explicitly wants a format driver here, we'll need to add
144376c591b0SKevin Wolf          * another layer for the protocol in bs->file */
144476c591b0SKevin Wolf         flags &= ~BDRV_O_PROTOCOL;
144576c591b0SKevin Wolf     }
144676c591b0SKevin Wolf 
1447de9c0cecSKevin Wolf     bs->options = options;
1448b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1449de9c0cecSKevin Wolf 
1450f500a6d3SKevin Wolf     /* Open image file without format layer */
1451f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1452be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1453be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1454be028adcSJeff Cody         }
1455b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1456b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
1457b1e6fc08SKevin Wolf             flags = bdrv_backing_flags(flags);
1458b1e6fc08SKevin Wolf         }
1459be028adcSJeff Cody 
1460f67503e5SMax Reitz         assert(file == NULL);
1461054963f8SMax Reitz         ret = bdrv_open_image(&file, filename, options, "file",
14620b50cc88SKevin Wolf                               bdrv_inherited_flags(flags),
14630b50cc88SKevin Wolf                               true, &local_err);
1464f500a6d3SKevin Wolf         if (ret < 0) {
14658bfea15dSKevin Wolf             goto fail;
1466f500a6d3SKevin Wolf         }
1467f4788adcSKevin Wolf     }
1468f500a6d3SKevin Wolf 
146976c591b0SKevin Wolf     /* Image format probing */
147076c591b0SKevin Wolf     if (!drv && file) {
147134b5d2c6SMax Reitz         ret = find_image_format(file, filename, &drv, &local_err);
147217b005f1SKevin Wolf         if (ret < 0) {
147317b005f1SKevin Wolf             goto fail;
147417b005f1SKevin Wolf         }
147576c591b0SKevin Wolf     } else if (!drv) {
14762a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
14772a05cbe4SMax Reitz         ret = -EINVAL;
14788bfea15dSKevin Wolf         goto fail;
14792a05cbe4SMax Reitz     }
1480f500a6d3SKevin Wolf 
1481b6ce07aaSKevin Wolf     /* Open the image */
148234b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1483b6ce07aaSKevin Wolf     if (ret < 0) {
14848bfea15dSKevin Wolf         goto fail;
14856987307cSChristoph Hellwig     }
14866987307cSChristoph Hellwig 
14872a05cbe4SMax Reitz     if (file && (bs->file != file)) {
14884f6fd349SFam Zheng         bdrv_unref(file);
1489f500a6d3SKevin Wolf         file = NULL;
1490f500a6d3SKevin Wolf     }
1491f500a6d3SKevin Wolf 
1492b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
14939156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
149431ca6d07SKevin Wolf         QDict *backing_options;
149531ca6d07SKevin Wolf 
14965726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
149734b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1498b6ce07aaSKevin Wolf         if (ret < 0) {
1499b6ad491aSKevin Wolf             goto close_and_fail;
1500b6ce07aaSKevin Wolf         }
1501b6ce07aaSKevin Wolf     }
1502b6ce07aaSKevin Wolf 
150391af7014SMax Reitz     bdrv_refresh_filename(bs);
150491af7014SMax Reitz 
1505b998875dSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1506b998875dSKevin Wolf      * temporary snapshot afterwards. */
1507b1e6fc08SKevin Wolf     if (snapshot_flags) {
15086b8aeca5SChen Gang         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1509b998875dSKevin Wolf         if (local_err) {
1510b998875dSKevin Wolf             goto close_and_fail;
1511b998875dSKevin Wolf         }
1512b998875dSKevin Wolf     }
1513b998875dSKevin Wolf 
1514b6ad491aSKevin Wolf     /* Check if any unknown options were used */
15155acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1516b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
15175acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
15185acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
15195acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
15205acd9d81SMax Reitz         } else {
152134b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
15225acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1523bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
15245acd9d81SMax Reitz         }
1525b6ad491aSKevin Wolf 
1526b6ad491aSKevin Wolf         ret = -EINVAL;
1527b6ad491aSKevin Wolf         goto close_and_fail;
1528b6ad491aSKevin Wolf     }
1529b6ad491aSKevin Wolf 
1530b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1531a7f53e26SMarkus Armbruster         if (bs->blk) {
1532a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1533a7f53e26SMarkus Armbruster         }
1534c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1535c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1536c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1537c3adb58fSMarkus Armbruster         error_setg(errp,
1538c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1539c3adb58fSMarkus Armbruster         ret = -EBUSY;
1540c3adb58fSMarkus Armbruster         goto close_and_fail;
1541b6ce07aaSKevin Wolf     }
1542b6ce07aaSKevin Wolf 
1543c3adb58fSMarkus Armbruster     QDECREF(options);
1544f67503e5SMax Reitz     *pbs = bs;
1545b6ce07aaSKevin Wolf     return 0;
1546b6ce07aaSKevin Wolf 
15478bfea15dSKevin Wolf fail:
1548f500a6d3SKevin Wolf     if (file != NULL) {
15494f6fd349SFam Zheng         bdrv_unref(file);
1550f500a6d3SKevin Wolf     }
1551de9c0cecSKevin Wolf     QDECREF(bs->options);
1552b6ad491aSKevin Wolf     QDECREF(options);
1553de9c0cecSKevin Wolf     bs->options = NULL;
1554f67503e5SMax Reitz     if (!*pbs) {
1555f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1556f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1557f67503e5SMax Reitz            since it has not really been opened yet. */
1558f67503e5SMax Reitz         bdrv_unref(bs);
1559f67503e5SMax Reitz     }
156084d18f06SMarkus Armbruster     if (local_err) {
156134b5d2c6SMax Reitz         error_propagate(errp, local_err);
156234b5d2c6SMax Reitz     }
1563b6ad491aSKevin Wolf     return ret;
1564de9c0cecSKevin Wolf 
1565b6ad491aSKevin Wolf close_and_fail:
1566f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1567f67503e5SMax Reitz     if (*pbs) {
1568b6ad491aSKevin Wolf         bdrv_close(bs);
1569f67503e5SMax Reitz     } else {
1570f67503e5SMax Reitz         bdrv_unref(bs);
1571f67503e5SMax Reitz     }
1572b6ad491aSKevin Wolf     QDECREF(options);
157384d18f06SMarkus Armbruster     if (local_err) {
157434b5d2c6SMax Reitz         error_propagate(errp, local_err);
157534b5d2c6SMax Reitz     }
1576b6ce07aaSKevin Wolf     return ret;
1577b6ce07aaSKevin Wolf }
1578b6ce07aaSKevin Wolf 
1579e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1580e971aa12SJeff Cody      bool prepared;
1581e971aa12SJeff Cody      BDRVReopenState state;
1582e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1583e971aa12SJeff Cody } BlockReopenQueueEntry;
1584e971aa12SJeff Cody 
1585e971aa12SJeff Cody /*
1586e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1587e971aa12SJeff Cody  * reopen of multiple devices.
1588e971aa12SJeff Cody  *
1589e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1590e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1591e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1592e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1593e971aa12SJeff Cody  * atomic 'set'.
1594e971aa12SJeff Cody  *
1595e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1596e971aa12SJeff Cody  *
1597e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1598e971aa12SJeff Cody  *
1599e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1600e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1601e971aa12SJeff Cody  *
1602e971aa12SJeff Cody  */
1603e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1604e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1605e971aa12SJeff Cody {
1606e971aa12SJeff Cody     assert(bs != NULL);
1607e971aa12SJeff Cody 
1608e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1609e971aa12SJeff Cody     if (bs_queue == NULL) {
1610e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1611e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1612e971aa12SJeff Cody     }
1613e971aa12SJeff Cody 
1614f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1615f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1616f1f25a2eSKevin Wolf 
1617e971aa12SJeff Cody     if (bs->file) {
1618f1f25a2eSKevin Wolf         bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags));
1619e971aa12SJeff Cody     }
1620e971aa12SJeff Cody 
1621e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1622e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1623e971aa12SJeff Cody 
1624e971aa12SJeff Cody     bs_entry->state.bs = bs;
1625e971aa12SJeff Cody     bs_entry->state.flags = flags;
1626e971aa12SJeff Cody 
1627e971aa12SJeff Cody     return bs_queue;
1628e971aa12SJeff Cody }
1629e971aa12SJeff Cody 
1630e971aa12SJeff Cody /*
1631e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1632e971aa12SJeff Cody  *
1633e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1634e971aa12SJeff Cody  * via bdrv_reopen_queue().
1635e971aa12SJeff Cody  *
1636e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1637e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1638e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1639e971aa12SJeff Cody  * data cleaned up.
1640e971aa12SJeff Cody  *
1641e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1642e971aa12SJeff Cody  * to all devices.
1643e971aa12SJeff Cody  *
1644e971aa12SJeff Cody  */
1645e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1646e971aa12SJeff Cody {
1647e971aa12SJeff Cody     int ret = -1;
1648e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1649e971aa12SJeff Cody     Error *local_err = NULL;
1650e971aa12SJeff Cody 
1651e971aa12SJeff Cody     assert(bs_queue != NULL);
1652e971aa12SJeff Cody 
1653e971aa12SJeff Cody     bdrv_drain_all();
1654e971aa12SJeff Cody 
1655e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1656e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1657e971aa12SJeff Cody             error_propagate(errp, local_err);
1658e971aa12SJeff Cody             goto cleanup;
1659e971aa12SJeff Cody         }
1660e971aa12SJeff Cody         bs_entry->prepared = true;
1661e971aa12SJeff Cody     }
1662e971aa12SJeff Cody 
1663e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1664e971aa12SJeff Cody      * changes
1665e971aa12SJeff Cody      */
1666e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1667e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1668e971aa12SJeff Cody     }
1669e971aa12SJeff Cody 
1670e971aa12SJeff Cody     ret = 0;
1671e971aa12SJeff Cody 
1672e971aa12SJeff Cody cleanup:
1673e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1674e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1675e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1676e971aa12SJeff Cody         }
1677e971aa12SJeff Cody         g_free(bs_entry);
1678e971aa12SJeff Cody     }
1679e971aa12SJeff Cody     g_free(bs_queue);
1680e971aa12SJeff Cody     return ret;
1681e971aa12SJeff Cody }
1682e971aa12SJeff Cody 
1683e971aa12SJeff Cody 
1684e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1685e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1686e971aa12SJeff Cody {
1687e971aa12SJeff Cody     int ret = -1;
1688e971aa12SJeff Cody     Error *local_err = NULL;
1689e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1690e971aa12SJeff Cody 
1691e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1692e971aa12SJeff Cody     if (local_err != NULL) {
1693e971aa12SJeff Cody         error_propagate(errp, local_err);
1694e971aa12SJeff Cody     }
1695e971aa12SJeff Cody     return ret;
1696e971aa12SJeff Cody }
1697e971aa12SJeff Cody 
1698e971aa12SJeff Cody 
1699e971aa12SJeff Cody /*
1700e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1701e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1702e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1703e971aa12SJeff Cody  *
1704e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1705e971aa12SJeff Cody  * flags are the new open flags
1706e971aa12SJeff Cody  * queue is the reopen queue
1707e971aa12SJeff Cody  *
1708e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1709e971aa12SJeff Cody  * as well.
1710e971aa12SJeff Cody  *
1711e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1712e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1713e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1714e971aa12SJeff Cody  *
1715e971aa12SJeff Cody  */
1716e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1717e971aa12SJeff Cody                         Error **errp)
1718e971aa12SJeff Cody {
1719e971aa12SJeff Cody     int ret = -1;
1720e971aa12SJeff Cody     Error *local_err = NULL;
1721e971aa12SJeff Cody     BlockDriver *drv;
1722e971aa12SJeff Cody 
1723e971aa12SJeff Cody     assert(reopen_state != NULL);
1724e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1725e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1726e971aa12SJeff Cody 
1727e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1728e971aa12SJeff Cody      * to r/w */
1729e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1730e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1731e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1732bfb197e0SMarkus Armbruster                   bdrv_get_device_name(reopen_state->bs));
1733e971aa12SJeff Cody         goto error;
1734e971aa12SJeff Cody     }
1735e971aa12SJeff Cody 
1736e971aa12SJeff Cody 
1737e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1738e971aa12SJeff Cody     if (ret) {
1739e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1740e971aa12SJeff Cody                   strerror(-ret));
1741e971aa12SJeff Cody         goto error;
1742e971aa12SJeff Cody     }
1743e971aa12SJeff Cody 
1744e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1745e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1746e971aa12SJeff Cody         if (ret) {
1747e971aa12SJeff Cody             if (local_err != NULL) {
1748e971aa12SJeff Cody                 error_propagate(errp, local_err);
1749e971aa12SJeff Cody             } else {
1750d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1751e971aa12SJeff Cody                            reopen_state->bs->filename);
1752e971aa12SJeff Cody             }
1753e971aa12SJeff Cody             goto error;
1754e971aa12SJeff Cody         }
1755e971aa12SJeff Cody     } else {
1756e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1757e971aa12SJeff Cody          * handler for each supported drv. */
1758e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1759bfb197e0SMarkus Armbruster                   drv->format_name, bdrv_get_device_name(reopen_state->bs),
1760e971aa12SJeff Cody                  "reopening of file");
1761e971aa12SJeff Cody         ret = -1;
1762e971aa12SJeff Cody         goto error;
1763e971aa12SJeff Cody     }
1764e971aa12SJeff Cody 
1765e971aa12SJeff Cody     ret = 0;
1766e971aa12SJeff Cody 
1767e971aa12SJeff Cody error:
1768e971aa12SJeff Cody     return ret;
1769e971aa12SJeff Cody }
1770e971aa12SJeff Cody 
1771e971aa12SJeff Cody /*
1772e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1773e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1774e971aa12SJeff Cody  * the active BlockDriverState contents.
1775e971aa12SJeff Cody  */
1776e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1777e971aa12SJeff Cody {
1778e971aa12SJeff Cody     BlockDriver *drv;
1779e971aa12SJeff Cody 
1780e971aa12SJeff Cody     assert(reopen_state != NULL);
1781e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1782e971aa12SJeff Cody     assert(drv != NULL);
1783e971aa12SJeff Cody 
1784e971aa12SJeff Cody     /* If there are any driver level actions to take */
1785e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1786e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1787e971aa12SJeff Cody     }
1788e971aa12SJeff Cody 
1789e971aa12SJeff Cody     /* set BDS specific flags now */
1790e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1791e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1792e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1793e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1794355ef4acSKevin Wolf 
17953baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
1796e971aa12SJeff Cody }
1797e971aa12SJeff Cody 
1798e971aa12SJeff Cody /*
1799e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1800e971aa12SJeff Cody  * reopen_state
1801e971aa12SJeff Cody  */
1802e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1803e971aa12SJeff Cody {
1804e971aa12SJeff Cody     BlockDriver *drv;
1805e971aa12SJeff Cody 
1806e971aa12SJeff Cody     assert(reopen_state != NULL);
1807e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1808e971aa12SJeff Cody     assert(drv != NULL);
1809e971aa12SJeff Cody 
1810e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1811e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1812e971aa12SJeff Cody     }
1813e971aa12SJeff Cody }
1814e971aa12SJeff Cody 
1815e971aa12SJeff Cody 
1816fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1817fc01f7e7Sbellard {
181833384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
181933384421SMax Reitz 
18203e914655SPaolo Bonzini     if (bs->job) {
18213e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
18223e914655SPaolo Bonzini     }
182358fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
182458fda173SStefan Hajnoczi     bdrv_flush(bs);
182558fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1826d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
18277094f12fSKevin Wolf 
18283cbc002cSPaolo Bonzini     if (bs->drv) {
1829557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1830826b6ca0SFam Zheng             BlockDriverState *backing_hd = bs->backing_hd;
1831826b6ca0SFam Zheng             bdrv_set_backing_hd(bs, NULL);
1832826b6ca0SFam Zheng             bdrv_unref(backing_hd);
1833557df6acSStefan Hajnoczi         }
1834ea2384d3Sbellard         bs->drv->bdrv_close(bs);
18357267c094SAnthony Liguori         g_free(bs->opaque);
1836ea2384d3Sbellard         bs->opaque = NULL;
1837ea2384d3Sbellard         bs->drv = NULL;
183853fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1839a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1840a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
18416405875cSPaolo Bonzini         bs->total_sectors = 0;
18426405875cSPaolo Bonzini         bs->encrypted = 0;
18436405875cSPaolo Bonzini         bs->valid_key = 0;
18446405875cSPaolo Bonzini         bs->sg = 0;
18456405875cSPaolo Bonzini         bs->growable = 0;
18460d51b4deSAsias He         bs->zero_beyond_eof = false;
1847de9c0cecSKevin Wolf         QDECREF(bs->options);
1848de9c0cecSKevin Wolf         bs->options = NULL;
184991af7014SMax Reitz         QDECREF(bs->full_open_options);
185091af7014SMax Reitz         bs->full_open_options = NULL;
1851b338082bSbellard 
185266f82ceeSKevin Wolf         if (bs->file != NULL) {
18534f6fd349SFam Zheng             bdrv_unref(bs->file);
18540ac9377dSPaolo Bonzini             bs->file = NULL;
185566f82ceeSKevin Wolf         }
18569ca11154SPavel Hrdina     }
185766f82ceeSKevin Wolf 
1858a7f53e26SMarkus Armbruster     if (bs->blk) {
1859a7f53e26SMarkus Armbruster         blk_dev_change_media_cb(bs->blk, false);
1860a7f53e26SMarkus Armbruster     }
186198f90dbaSZhi Yong Wu 
186298f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
186398f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
186498f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
186598f90dbaSZhi Yong Wu     }
186633384421SMax Reitz 
186733384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
186833384421SMax Reitz         g_free(ban);
186933384421SMax Reitz     }
187033384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
1871b338082bSbellard }
1872b338082bSbellard 
18732bc93fedSMORITA Kazutaka void bdrv_close_all(void)
18742bc93fedSMORITA Kazutaka {
18752bc93fedSMORITA Kazutaka     BlockDriverState *bs;
18762bc93fedSMORITA Kazutaka 
1877dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
1878ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
1879ed78cda3SStefan Hajnoczi 
1880ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
18812bc93fedSMORITA Kazutaka         bdrv_close(bs);
1882ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
18832bc93fedSMORITA Kazutaka     }
18842bc93fedSMORITA Kazutaka }
18852bc93fedSMORITA Kazutaka 
188688266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
188788266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
188888266f5aSStefan Hajnoczi {
188988266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
189088266f5aSStefan Hajnoczi         return true;
189188266f5aSStefan Hajnoczi     }
1892cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1893cc0681c4SBenoît Canet         return true;
1894cc0681c4SBenoît Canet     }
1895cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
189688266f5aSStefan Hajnoczi         return true;
189788266f5aSStefan Hajnoczi     }
189888266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
189988266f5aSStefan Hajnoczi         return true;
190088266f5aSStefan Hajnoczi     }
190188266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
190288266f5aSStefan Hajnoczi         return true;
190388266f5aSStefan Hajnoczi     }
190488266f5aSStefan Hajnoczi     return false;
190588266f5aSStefan Hajnoczi }
190688266f5aSStefan Hajnoczi 
1907922453bcSStefan Hajnoczi /*
1908922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1909922453bcSStefan Hajnoczi  *
1910922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1911922453bcSStefan Hajnoczi  * after calling this function.
19124c355d53SZhi Yong Wu  *
19134c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
19144c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
19154c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
19164c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
19174c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1918922453bcSStefan Hajnoczi  */
1919922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1920922453bcSStefan Hajnoczi {
192188266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
192288266f5aSStefan Hajnoczi     bool busy = true;
1923922453bcSStefan Hajnoczi     BlockDriverState *bs;
1924922453bcSStefan Hajnoczi 
192588266f5aSStefan Hajnoczi     while (busy) {
19269b536adcSStefan Hajnoczi         busy = false;
1927922453bcSStefan Hajnoczi 
19289b536adcSStefan Hajnoczi         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
19299b536adcSStefan Hajnoczi             AioContext *aio_context = bdrv_get_aio_context(bs);
19309b536adcSStefan Hajnoczi             bool bs_busy;
19319b536adcSStefan Hajnoczi 
19329b536adcSStefan Hajnoczi             aio_context_acquire(aio_context);
1933448ad91dSMing Lei             bdrv_flush_io_queue(bs);
19349b536adcSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
19359b536adcSStefan Hajnoczi             bs_busy = bdrv_requests_pending(bs);
19369b536adcSStefan Hajnoczi             bs_busy |= aio_poll(aio_context, bs_busy);
19379b536adcSStefan Hajnoczi             aio_context_release(aio_context);
19389b536adcSStefan Hajnoczi 
19399b536adcSStefan Hajnoczi             busy |= bs_busy;
19409b536adcSStefan Hajnoczi         }
1941922453bcSStefan Hajnoczi     }
1942922453bcSStefan Hajnoczi }
1943922453bcSStefan Hajnoczi 
1944dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1945dc364f4cSBenoît Canet  * graph_bdrv_state list.
1946d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1947d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1948d22b2f41SRyan Harper {
1949bfb197e0SMarkus Armbruster     /*
1950bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
1951bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
1952bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
1953bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
1954bfb197e0SMarkus Armbruster      * resetting it to null on remove.
1955bfb197e0SMarkus Armbruster      */
1956bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
1957dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1958bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
1959d22b2f41SRyan Harper     }
1960dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1961dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1962dc364f4cSBenoît Canet     }
1963dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1964d22b2f41SRyan Harper }
1965d22b2f41SRyan Harper 
1966e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1967e023b2e2SPaolo Bonzini {
1968e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1969e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1970e023b2e2SPaolo Bonzini     }
1971e023b2e2SPaolo Bonzini }
1972e023b2e2SPaolo Bonzini 
19734ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
19744ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
19754ddc07caSPaolo Bonzini {
19764ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
19774ddc07caSPaolo Bonzini 
19784ddc07caSPaolo Bonzini     /* dev info */
19791b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
19804ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
19814ddc07caSPaolo Bonzini 
19824ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
19834ddc07caSPaolo Bonzini 
1984cc0681c4SBenoît Canet     /* i/o throttled req */
1985cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1986cc0681c4SBenoît Canet            &bs_src->throttle_state,
1987cc0681c4SBenoît Canet            sizeof(ThrottleState));
1988cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1989cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
19904ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
19914ddc07caSPaolo Bonzini 
19924ddc07caSPaolo Bonzini     /* r/w error */
19934ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
19944ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
19954ddc07caSPaolo Bonzini 
19964ddc07caSPaolo Bonzini     /* i/o status */
19974ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
19984ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
19994ddc07caSPaolo Bonzini 
20004ddc07caSPaolo Bonzini     /* dirty bitmap */
2001e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
20024ddc07caSPaolo Bonzini 
20039fcb0251SFam Zheng     /* reference count */
20049fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
20059fcb0251SFam Zheng 
20064ddc07caSPaolo Bonzini     /* job */
20074ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
20084ddc07caSPaolo Bonzini 
20094ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
2010dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
20117e7d56d9SMarkus Armbruster     bs_dest->blk = bs_src->blk;
20127e7d56d9SMarkus Armbruster 
2013fbe40ff7SFam Zheng     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
2014fbe40ff7SFam Zheng            sizeof(bs_dest->op_blockers));
20154ddc07caSPaolo Bonzini }
20164ddc07caSPaolo Bonzini 
20174ddc07caSPaolo Bonzini /*
20184ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
20194ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
20204ddc07caSPaolo Bonzini  * actually attached to a device.
20214ddc07caSPaolo Bonzini  *
20224ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
20234ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
20244ddc07caSPaolo Bonzini  *
2025bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
20264ddc07caSPaolo Bonzini  *
20274ddc07caSPaolo Bonzini  * This function does not create any image files.
20284ddc07caSPaolo Bonzini  */
20294ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
20304ddc07caSPaolo Bonzini {
20314ddc07caSPaolo Bonzini     BlockDriverState tmp;
20324ddc07caSPaolo Bonzini 
203390ce8a06SBenoît Canet     /* The code needs to swap the node_name but simply swapping node_list won't
203490ce8a06SBenoît Canet      * work so first remove the nodes from the graph list, do the swap then
203590ce8a06SBenoît Canet      * insert them back if needed.
203690ce8a06SBenoît Canet      */
203790ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
203890ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
203990ce8a06SBenoît Canet     }
204090ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
204190ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
204290ce8a06SBenoît Canet     }
204390ce8a06SBenoît Canet 
2044bfb197e0SMarkus Armbruster     /* bs_new must be unattached and shouldn't have anything fancy enabled */
20457e7d56d9SMarkus Armbruster     assert(!bs_new->blk);
2046e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
20474ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20484ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2049cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
20504ddc07caSPaolo Bonzini 
20514ddc07caSPaolo Bonzini     tmp = *bs_new;
20524ddc07caSPaolo Bonzini     *bs_new = *bs_old;
20534ddc07caSPaolo Bonzini     *bs_old = tmp;
20544ddc07caSPaolo Bonzini 
20554ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
20564ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
20574ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
20584ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
20594ddc07caSPaolo Bonzini 
2060bfb197e0SMarkus Armbruster     /* bs_new must remain unattached */
20617e7d56d9SMarkus Armbruster     assert(!bs_new->blk);
20624ddc07caSPaolo Bonzini 
20634ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
20644ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20654ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2066cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
20674ddc07caSPaolo Bonzini 
206890ce8a06SBenoît Canet     /* insert the nodes back into the graph node list if needed */
206990ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
207090ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
207190ce8a06SBenoît Canet     }
207290ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
207390ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
207490ce8a06SBenoît Canet     }
207590ce8a06SBenoît Canet 
20764ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
20774ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
20784ddc07caSPaolo Bonzini }
20794ddc07caSPaolo Bonzini 
20808802d1fdSJeff Cody /*
20818802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
20828802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
20838802d1fdSJeff Cody  *
20848802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
20858802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
20868802d1fdSJeff Cody  *
2087bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2088f6801b83SJeff Cody  *
20898802d1fdSJeff Cody  * This function does not create any image files.
20908802d1fdSJeff Cody  */
20918802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
20928802d1fdSJeff Cody {
20934ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
20948802d1fdSJeff Cody 
20958802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
20968802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
20978d24cce1SFam Zheng     bdrv_set_backing_hd(bs_top, bs_new);
20988802d1fdSJeff Cody }
20998802d1fdSJeff Cody 
21004f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2101b338082bSbellard {
21023e914655SPaolo Bonzini     assert(!bs->job);
21033718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
21044f6fd349SFam Zheng     assert(!bs->refcnt);
2105e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
210618846deeSMarkus Armbruster 
2107e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2108e1b5c52eSStefan Hajnoczi 
21091b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2110d22b2f41SRyan Harper     bdrv_make_anon(bs);
211134c6f050Saurel32 
21127267c094SAnthony Liguori     g_free(bs);
2113fc01f7e7Sbellard }
2114fc01f7e7Sbellard 
2115e97fc193Saliguori /*
2116e97fc193Saliguori  * Run consistency checks on an image
2117e97fc193Saliguori  *
2118e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2119a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2120e076f338SKevin Wolf  * check are stored in res.
2121e97fc193Saliguori  */
21224534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2123e97fc193Saliguori {
2124908bcd54SMax Reitz     if (bs->drv == NULL) {
2125908bcd54SMax Reitz         return -ENOMEDIUM;
2126908bcd54SMax Reitz     }
2127e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2128e97fc193Saliguori         return -ENOTSUP;
2129e97fc193Saliguori     }
2130e97fc193Saliguori 
2131e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
21324534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2133e97fc193Saliguori }
2134e97fc193Saliguori 
21358a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
21368a426614SKevin Wolf 
213733e3963eSbellard /* commit COW file into the raw image */
213833e3963eSbellard int bdrv_commit(BlockDriverState *bs)
213933e3963eSbellard {
214019cb3738Sbellard     BlockDriver *drv = bs->drv;
214172706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
21428a426614SKevin Wolf     int n, ro, open_flags;
21430bce597dSJeff Cody     int ret = 0;
214472706ea4SJeff Cody     uint8_t *buf = NULL;
2145c2cba3d9SJim Meyering     char filename[PATH_MAX];
214633e3963eSbellard 
214719cb3738Sbellard     if (!drv)
214819cb3738Sbellard         return -ENOMEDIUM;
214933e3963eSbellard 
21504dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
21514dca4b63SNaphtali Sprei         return -ENOTSUP;
21524dca4b63SNaphtali Sprei     }
21534dca4b63SNaphtali Sprei 
21543718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) ||
21553718d8abSFam Zheng         bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) {
21562d3735d3SStefan Hajnoczi         return -EBUSY;
21572d3735d3SStefan Hajnoczi     }
21582d3735d3SStefan Hajnoczi 
21594dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2160c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2161c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
21624dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
21634dca4b63SNaphtali Sprei 
21644dca4b63SNaphtali Sprei     if (ro) {
21650bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
21660bce597dSJeff Cody             return -EACCES;
21674dca4b63SNaphtali Sprei         }
2168ea2384d3Sbellard     }
2169ea2384d3Sbellard 
217072706ea4SJeff Cody     length = bdrv_getlength(bs);
217172706ea4SJeff Cody     if (length < 0) {
217272706ea4SJeff Cody         ret = length;
217372706ea4SJeff Cody         goto ro_cleanup;
217472706ea4SJeff Cody     }
217572706ea4SJeff Cody 
217672706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
217772706ea4SJeff Cody     if (backing_length < 0) {
217872706ea4SJeff Cody         ret = backing_length;
217972706ea4SJeff Cody         goto ro_cleanup;
218072706ea4SJeff Cody     }
218172706ea4SJeff Cody 
218272706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
218372706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
218472706ea4SJeff Cody      * we must return an error */
218572706ea4SJeff Cody     if (length > backing_length) {
218672706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
218772706ea4SJeff Cody         if (ret < 0) {
218872706ea4SJeff Cody             goto ro_cleanup;
218972706ea4SJeff Cody         }
219072706ea4SJeff Cody     }
219172706ea4SJeff Cody 
219272706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2193857d4f46SKevin Wolf 
2194857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2195857d4f46SKevin Wolf      * bs->backing_hd as well, so no need to compare the alignment manually. */
2196857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2197857d4f46SKevin Wolf     if (buf == NULL) {
2198857d4f46SKevin Wolf         ret = -ENOMEM;
2199857d4f46SKevin Wolf         goto ro_cleanup;
2200857d4f46SKevin Wolf     }
22018a426614SKevin Wolf 
22028a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2203d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2204d663640cSPaolo Bonzini         if (ret < 0) {
2205d663640cSPaolo Bonzini             goto ro_cleanup;
2206d663640cSPaolo Bonzini         }
2207d663640cSPaolo Bonzini         if (ret) {
2208dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2209dabfa6ccSKevin Wolf             if (ret < 0) {
22104dca4b63SNaphtali Sprei                 goto ro_cleanup;
221133e3963eSbellard             }
221233e3963eSbellard 
2213dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2214dabfa6ccSKevin Wolf             if (ret < 0) {
22154dca4b63SNaphtali Sprei                 goto ro_cleanup;
221633e3963eSbellard             }
221733e3963eSbellard         }
221833e3963eSbellard     }
221995389c86Sbellard 
22201d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
22211d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2222dabfa6ccSKevin Wolf         if (ret < 0) {
2223dabfa6ccSKevin Wolf             goto ro_cleanup;
2224dabfa6ccSKevin Wolf         }
22251d44952fSChristoph Hellwig         bdrv_flush(bs);
22261d44952fSChristoph Hellwig     }
222795389c86Sbellard 
22283f5075aeSChristoph Hellwig     /*
22293f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
22303f5075aeSChristoph Hellwig      * stable on disk.
22313f5075aeSChristoph Hellwig      */
2232dabfa6ccSKevin Wolf     if (bs->backing_hd) {
22333f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2234dabfa6ccSKevin Wolf     }
22354dca4b63SNaphtali Sprei 
2236dabfa6ccSKevin Wolf     ret = 0;
22374dca4b63SNaphtali Sprei ro_cleanup:
2238857d4f46SKevin Wolf     qemu_vfree(buf);
22394dca4b63SNaphtali Sprei 
22404dca4b63SNaphtali Sprei     if (ro) {
22410bce597dSJeff Cody         /* ignoring error return here */
22420bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
22434dca4b63SNaphtali Sprei     }
22444dca4b63SNaphtali Sprei 
22451d44952fSChristoph Hellwig     return ret;
224633e3963eSbellard }
224733e3963eSbellard 
2248e8877497SStefan Hajnoczi int bdrv_commit_all(void)
22496ab4b5abSMarkus Armbruster {
22506ab4b5abSMarkus Armbruster     BlockDriverState *bs;
22516ab4b5abSMarkus Armbruster 
2252dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2253ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2254ed78cda3SStefan Hajnoczi 
2255ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2256272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2257e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2258e8877497SStefan Hajnoczi             if (ret < 0) {
2259ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2260e8877497SStefan Hajnoczi                 return ret;
22616ab4b5abSMarkus Armbruster             }
22626ab4b5abSMarkus Armbruster         }
2263ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2264272d2d8eSJeff Cody     }
2265e8877497SStefan Hajnoczi     return 0;
2266e8877497SStefan Hajnoczi }
22676ab4b5abSMarkus Armbruster 
2268dbffbdcfSStefan Hajnoczi /**
2269dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2270dbffbdcfSStefan Hajnoczi  *
2271dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2272dbffbdcfSStefan Hajnoczi  */
2273dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2274dbffbdcfSStefan Hajnoczi {
22752dbafdc0SKevin Wolf     if (req->serialising) {
22762dbafdc0SKevin Wolf         req->bs->serialising_in_flight--;
22772dbafdc0SKevin Wolf     }
22782dbafdc0SKevin Wolf 
2279dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2280f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2281dbffbdcfSStefan Hajnoczi }
2282dbffbdcfSStefan Hajnoczi 
2283dbffbdcfSStefan Hajnoczi /**
2284dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2285dbffbdcfSStefan Hajnoczi  */
2286dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2287dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2288793ed47aSKevin Wolf                                   int64_t offset,
2289793ed47aSKevin Wolf                                   unsigned int bytes, bool is_write)
2290dbffbdcfSStefan Hajnoczi {
2291dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2292dbffbdcfSStefan Hajnoczi         .bs = bs,
2293793ed47aSKevin Wolf         .offset         = offset,
2294793ed47aSKevin Wolf         .bytes          = bytes,
2295dbffbdcfSStefan Hajnoczi         .is_write       = is_write,
22965f8b6491SStefan Hajnoczi         .co             = qemu_coroutine_self(),
22972dbafdc0SKevin Wolf         .serialising    = false,
22987327145fSKevin Wolf         .overlap_offset = offset,
22997327145fSKevin Wolf         .overlap_bytes  = bytes,
2300dbffbdcfSStefan Hajnoczi     };
2301dbffbdcfSStefan Hajnoczi 
2302f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2303f4658285SStefan Hajnoczi 
2304dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2305dbffbdcfSStefan Hajnoczi }
2306dbffbdcfSStefan Hajnoczi 
2307e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
23082dbafdc0SKevin Wolf {
23097327145fSKevin Wolf     int64_t overlap_offset = req->offset & ~(align - 1);
2310e96126ffSKevin Wolf     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
23117327145fSKevin Wolf                                - overlap_offset;
23127327145fSKevin Wolf 
23132dbafdc0SKevin Wolf     if (!req->serialising) {
23142dbafdc0SKevin Wolf         req->bs->serialising_in_flight++;
23152dbafdc0SKevin Wolf         req->serialising = true;
23162dbafdc0SKevin Wolf     }
23177327145fSKevin Wolf 
23187327145fSKevin Wolf     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
23197327145fSKevin Wolf     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
23202dbafdc0SKevin Wolf }
23212dbafdc0SKevin Wolf 
2322d83947acSStefan Hajnoczi /**
2323d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2324d83947acSStefan Hajnoczi  */
2325343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2326d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2327d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2328d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2329d83947acSStefan Hajnoczi {
2330d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2331d83947acSStefan Hajnoczi 
2332d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2333d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2334d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2335d83947acSStefan Hajnoczi     } else {
2336d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2337d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2338d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2339d83947acSStefan Hajnoczi                                             nb_sectors, c);
2340d83947acSStefan Hajnoczi     }
2341d83947acSStefan Hajnoczi }
2342d83947acSStefan Hajnoczi 
23437327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs)
2344793ed47aSKevin Wolf {
2345793ed47aSKevin Wolf     BlockDriverInfo bdi;
23467327145fSKevin Wolf     int ret;
2347793ed47aSKevin Wolf 
23487327145fSKevin Wolf     ret = bdrv_get_info(bs, &bdi);
23497327145fSKevin Wolf     if (ret < 0 || bdi.cluster_size == 0) {
23507327145fSKevin Wolf         return bs->request_alignment;
2351793ed47aSKevin Wolf     } else {
23527327145fSKevin Wolf         return bdi.cluster_size;
2353793ed47aSKevin Wolf     }
2354793ed47aSKevin Wolf }
2355793ed47aSKevin Wolf 
2356f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2357793ed47aSKevin Wolf                                      int64_t offset, unsigned int bytes)
2358793ed47aSKevin Wolf {
2359d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
23607327145fSKevin Wolf     if (offset >= req->overlap_offset + req->overlap_bytes) {
2361d83947acSStefan Hajnoczi         return false;
2362d83947acSStefan Hajnoczi     }
2363d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
23647327145fSKevin Wolf     if (req->overlap_offset >= offset + bytes) {
2365d83947acSStefan Hajnoczi         return false;
2366d83947acSStefan Hajnoczi     }
2367d83947acSStefan Hajnoczi     return true;
2368f4658285SStefan Hajnoczi }
2369f4658285SStefan Hajnoczi 
237028de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
2371f4658285SStefan Hajnoczi {
23722dbafdc0SKevin Wolf     BlockDriverState *bs = self->bs;
2373f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2374f4658285SStefan Hajnoczi     bool retry;
237528de2dcdSKevin Wolf     bool waited = false;
2376f4658285SStefan Hajnoczi 
23772dbafdc0SKevin Wolf     if (!bs->serialising_in_flight) {
237828de2dcdSKevin Wolf         return false;
23792dbafdc0SKevin Wolf     }
23802dbafdc0SKevin Wolf 
2381f4658285SStefan Hajnoczi     do {
2382f4658285SStefan Hajnoczi         retry = false;
2383f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
23842dbafdc0SKevin Wolf             if (req == self || (!req->serialising && !self->serialising)) {
238565afd211SKevin Wolf                 continue;
238665afd211SKevin Wolf             }
23877327145fSKevin Wolf             if (tracked_request_overlaps(req, self->overlap_offset,
23887327145fSKevin Wolf                                          self->overlap_bytes))
23897327145fSKevin Wolf             {
23905f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
23915f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
23925f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
23935f8b6491SStefan Hajnoczi                  */
23945f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
23955f8b6491SStefan Hajnoczi 
23966460440fSKevin Wolf                 /* If the request is already (indirectly) waiting for us, or
23976460440fSKevin Wolf                  * will wait for us as soon as it wakes up, then just go on
23986460440fSKevin Wolf                  * (instead of producing a deadlock in the former case). */
23996460440fSKevin Wolf                 if (!req->waiting_for) {
24006460440fSKevin Wolf                     self->waiting_for = req;
2401f4658285SStefan Hajnoczi                     qemu_co_queue_wait(&req->wait_queue);
24026460440fSKevin Wolf                     self->waiting_for = NULL;
2403f4658285SStefan Hajnoczi                     retry = true;
240428de2dcdSKevin Wolf                     waited = true;
2405f4658285SStefan Hajnoczi                     break;
2406f4658285SStefan Hajnoczi                 }
2407f4658285SStefan Hajnoczi             }
24086460440fSKevin Wolf         }
2409f4658285SStefan Hajnoczi     } while (retry);
241028de2dcdSKevin Wolf 
241128de2dcdSKevin Wolf     return waited;
2412f4658285SStefan Hajnoczi }
2413f4658285SStefan Hajnoczi 
2414756e6736SKevin Wolf /*
2415756e6736SKevin Wolf  * Return values:
2416756e6736SKevin Wolf  * 0        - success
2417756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2418756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2419756e6736SKevin Wolf  *            image file header
2420756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2421756e6736SKevin Wolf  */
2422756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2423756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2424756e6736SKevin Wolf {
2425756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2426469ef350SPaolo Bonzini     int ret;
2427756e6736SKevin Wolf 
24285f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
24295f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
24305f377794SPaolo Bonzini         return -EINVAL;
24315f377794SPaolo Bonzini     }
24325f377794SPaolo Bonzini 
2433756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2434469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2435756e6736SKevin Wolf     } else {
2436469ef350SPaolo Bonzini         ret = -ENOTSUP;
2437756e6736SKevin Wolf     }
2438469ef350SPaolo Bonzini 
2439469ef350SPaolo Bonzini     if (ret == 0) {
2440469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2441469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2442469ef350SPaolo Bonzini     }
2443469ef350SPaolo Bonzini     return ret;
2444756e6736SKevin Wolf }
2445756e6736SKevin Wolf 
24466ebdcee2SJeff Cody /*
24476ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
24486ebdcee2SJeff Cody  *
24496ebdcee2SJeff Cody  * active is the current topmost image.
24506ebdcee2SJeff Cody  *
24516ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
24526ebdcee2SJeff Cody  * or if active == bs.
24534caf0fcdSJeff Cody  *
24544caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
24556ebdcee2SJeff Cody  */
24566ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
24576ebdcee2SJeff Cody                                     BlockDriverState *bs)
24586ebdcee2SJeff Cody {
24594caf0fcdSJeff Cody     while (active && bs != active->backing_hd) {
24604caf0fcdSJeff Cody         active = active->backing_hd;
24616ebdcee2SJeff Cody     }
24626ebdcee2SJeff Cody 
24634caf0fcdSJeff Cody     return active;
24646ebdcee2SJeff Cody }
24656ebdcee2SJeff Cody 
24664caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
24674caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
24684caf0fcdSJeff Cody {
24694caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
24706ebdcee2SJeff Cody }
24716ebdcee2SJeff Cody 
24726ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
24736ebdcee2SJeff Cody     BlockDriverState *bs;
24746ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
24756ebdcee2SJeff Cody } BlkIntermediateStates;
24766ebdcee2SJeff Cody 
24776ebdcee2SJeff Cody 
24786ebdcee2SJeff Cody /*
24796ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
24806ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
24816ebdcee2SJeff Cody  *
24826ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
24836ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
24846ebdcee2SJeff Cody  *
24856ebdcee2SJeff Cody  * E.g., this will convert the following chain:
24866ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
24876ebdcee2SJeff Cody  *
24886ebdcee2SJeff Cody  * to
24896ebdcee2SJeff Cody  *
24906ebdcee2SJeff Cody  * bottom <- base <- active
24916ebdcee2SJeff Cody  *
24926ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
24936ebdcee2SJeff Cody  *
24946ebdcee2SJeff Cody  * base <- intermediate <- top <- active
24956ebdcee2SJeff Cody  *
24966ebdcee2SJeff Cody  * to
24976ebdcee2SJeff Cody  *
24986ebdcee2SJeff Cody  * base <- active
24996ebdcee2SJeff Cody  *
250054e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
250154e26900SJeff Cody  * overlay image metadata.
250254e26900SJeff Cody  *
25036ebdcee2SJeff Cody  * Error conditions:
25046ebdcee2SJeff Cody  *  if active == top, that is considered an error
25056ebdcee2SJeff Cody  *
25066ebdcee2SJeff Cody  */
25076ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
250854e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
25096ebdcee2SJeff Cody {
25106ebdcee2SJeff Cody     BlockDriverState *intermediate;
25116ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
25126ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
25136ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
25146ebdcee2SJeff Cody     int ret = -EIO;
25156ebdcee2SJeff Cody 
25166ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
25176ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
25186ebdcee2SJeff Cody 
25196ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
25206ebdcee2SJeff Cody         goto exit;
25216ebdcee2SJeff Cody     }
25226ebdcee2SJeff Cody 
25236ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
25246ebdcee2SJeff Cody 
25256ebdcee2SJeff Cody     if (new_top_bs == NULL) {
25266ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
25276ebdcee2SJeff Cody         goto exit;
25286ebdcee2SJeff Cody     }
25296ebdcee2SJeff Cody 
25306ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
25316ebdcee2SJeff Cody      * to do, no intermediate images */
25326ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
25336ebdcee2SJeff Cody         ret = 0;
25346ebdcee2SJeff Cody         goto exit;
25356ebdcee2SJeff Cody     }
25366ebdcee2SJeff Cody 
25376ebdcee2SJeff Cody     intermediate = top;
25386ebdcee2SJeff Cody 
25396ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
25406ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
25416ebdcee2SJeff Cody      */
25426ebdcee2SJeff Cody     while (intermediate) {
25435839e53bSMarkus Armbruster         intermediate_state = g_new0(BlkIntermediateStates, 1);
25446ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
25456ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
25466ebdcee2SJeff Cody 
25476ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
25486ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
25496ebdcee2SJeff Cody             break;
25506ebdcee2SJeff Cody         }
25516ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
25526ebdcee2SJeff Cody     }
25536ebdcee2SJeff Cody     if (base_bs == NULL) {
25546ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
25556ebdcee2SJeff Cody          * unravel everything, and exit with error */
25566ebdcee2SJeff Cody         goto exit;
25576ebdcee2SJeff Cody     }
25586ebdcee2SJeff Cody 
25596ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
256054e26900SJeff Cody     backing_file_str = backing_file_str ? backing_file_str : base_bs->filename;
256154e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
25626ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
25636ebdcee2SJeff Cody     if (ret) {
25646ebdcee2SJeff Cody         goto exit;
25656ebdcee2SJeff Cody     }
2566920beae1SFam Zheng     bdrv_set_backing_hd(new_top_bs, base_bs);
25676ebdcee2SJeff Cody 
25686ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25696ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
2570920beae1SFam Zheng         bdrv_set_backing_hd(intermediate_state->bs, NULL);
25714f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
25726ebdcee2SJeff Cody     }
25736ebdcee2SJeff Cody     ret = 0;
25746ebdcee2SJeff Cody 
25756ebdcee2SJeff Cody exit:
25766ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25776ebdcee2SJeff Cody         g_free(intermediate_state);
25786ebdcee2SJeff Cody     }
25796ebdcee2SJeff Cody     return ret;
25806ebdcee2SJeff Cody }
25816ebdcee2SJeff Cody 
25826ebdcee2SJeff Cody 
258371d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
258471d0770cSaliguori                                    size_t size)
258571d0770cSaliguori {
258671d0770cSaliguori     int64_t len;
258771d0770cSaliguori 
25881dd3a447SKevin Wolf     if (size > INT_MAX) {
25891dd3a447SKevin Wolf         return -EIO;
25901dd3a447SKevin Wolf     }
25911dd3a447SKevin Wolf 
259271d0770cSaliguori     if (!bdrv_is_inserted(bs))
259371d0770cSaliguori         return -ENOMEDIUM;
259471d0770cSaliguori 
259571d0770cSaliguori     if (bs->growable)
259671d0770cSaliguori         return 0;
259771d0770cSaliguori 
259871d0770cSaliguori     len = bdrv_getlength(bs);
259971d0770cSaliguori 
2600fbb7b4e0SKevin Wolf     if (offset < 0)
2601fbb7b4e0SKevin Wolf         return -EIO;
2602fbb7b4e0SKevin Wolf 
2603fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
260471d0770cSaliguori         return -EIO;
260571d0770cSaliguori 
260671d0770cSaliguori     return 0;
260771d0770cSaliguori }
260871d0770cSaliguori 
260971d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
261071d0770cSaliguori                               int nb_sectors)
261171d0770cSaliguori {
261254db38a4SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
26138f4754edSKevin Wolf         return -EIO;
26148f4754edSKevin Wolf     }
26158f4754edSKevin Wolf 
2616eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2617eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
261871d0770cSaliguori }
261971d0770cSaliguori 
26201c9805a3SStefan Hajnoczi typedef struct RwCo {
26211c9805a3SStefan Hajnoczi     BlockDriverState *bs;
2622775aa8b6SKevin Wolf     int64_t offset;
26231c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
26241c9805a3SStefan Hajnoczi     bool is_write;
26251c9805a3SStefan Hajnoczi     int ret;
26264105eaaaSPeter Lieven     BdrvRequestFlags flags;
26271c9805a3SStefan Hajnoczi } RwCo;
26281c9805a3SStefan Hajnoczi 
26291c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2630fc01f7e7Sbellard {
26311c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2632fc01f7e7Sbellard 
26331c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
2634775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2635775aa8b6SKevin Wolf                                       rwco->qiov->size, rwco->qiov,
26364105eaaaSPeter Lieven                                       rwco->flags);
26371c9805a3SStefan Hajnoczi     } else {
2638775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2639775aa8b6SKevin Wolf                                        rwco->qiov->size, rwco->qiov,
26404105eaaaSPeter Lieven                                        rwco->flags);
26411c9805a3SStefan Hajnoczi     }
26421c9805a3SStefan Hajnoczi }
2643e7a8a783SKevin Wolf 
26441c9805a3SStefan Hajnoczi /*
26458d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
26461c9805a3SStefan Hajnoczi  */
2647775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
26484105eaaaSPeter Lieven                         QEMUIOVector *qiov, bool is_write,
26494105eaaaSPeter Lieven                         BdrvRequestFlags flags)
26501c9805a3SStefan Hajnoczi {
26511c9805a3SStefan Hajnoczi     Coroutine *co;
26521c9805a3SStefan Hajnoczi     RwCo rwco = {
26531c9805a3SStefan Hajnoczi         .bs = bs,
2654775aa8b6SKevin Wolf         .offset = offset,
26558d3b1a2dSKevin Wolf         .qiov = qiov,
26561c9805a3SStefan Hajnoczi         .is_write = is_write,
26571c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
26584105eaaaSPeter Lieven         .flags = flags,
26591c9805a3SStefan Hajnoczi     };
26601c9805a3SStefan Hajnoczi 
2661498e386cSZhi Yong Wu     /**
2662498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2663498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2664498e386cSZhi Yong Wu      * if it has been enabled.
2665498e386cSZhi Yong Wu      */
2666498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2667498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2668498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2669498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2670498e386cSZhi Yong Wu     }
2671498e386cSZhi Yong Wu 
26721c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
26731c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
26741c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
26751c9805a3SStefan Hajnoczi     } else {
26762572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
26772572b37aSStefan Hajnoczi 
26781c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
26791c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
26801c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
26812572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
26821c9805a3SStefan Hajnoczi         }
26831c9805a3SStefan Hajnoczi     }
26841c9805a3SStefan Hajnoczi     return rwco.ret;
2685e7a8a783SKevin Wolf }
2686e7a8a783SKevin Wolf 
26878d3b1a2dSKevin Wolf /*
26888d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
26898d3b1a2dSKevin Wolf  */
26908d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
26914105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
26928d3b1a2dSKevin Wolf {
26938d3b1a2dSKevin Wolf     QEMUIOVector qiov;
26948d3b1a2dSKevin Wolf     struct iovec iov = {
26958d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
26968d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
26978d3b1a2dSKevin Wolf     };
26988d3b1a2dSKevin Wolf 
2699da15ee51SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
2700da15ee51SKevin Wolf         return -EINVAL;
2701da15ee51SKevin Wolf     }
2702da15ee51SKevin Wolf 
27038d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2704775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2705775aa8b6SKevin Wolf                         &qiov, is_write, flags);
27068d3b1a2dSKevin Wolf }
27078d3b1a2dSKevin Wolf 
27081c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
27091c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
27101c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
27111c9805a3SStefan Hajnoczi {
27124105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
271383f64091Sbellard }
2714fc01f7e7Sbellard 
271507d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
271607d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
271707d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
271807d27a44SMarkus Armbruster {
271907d27a44SMarkus Armbruster     bool enabled;
272007d27a44SMarkus Armbruster     int ret;
272107d27a44SMarkus Armbruster 
272207d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
272307d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
27244e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
272507d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
272607d27a44SMarkus Armbruster     return ret;
272707d27a44SMarkus Armbruster }
272807d27a44SMarkus Armbruster 
272919cb3738Sbellard /* Return < 0 if error. Important errors are:
273019cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
273119cb3738Sbellard   -ENOMEDIUM   No media inserted.
273219cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
273319cb3738Sbellard   -EACCES      Trying to write a read-only device
273419cb3738Sbellard */
2735fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2736fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2737fc01f7e7Sbellard {
27384105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
273983f64091Sbellard }
274083f64091Sbellard 
2741aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2742aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
27434105eaaaSPeter Lieven {
27444105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2745aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
27468d3b1a2dSKevin Wolf }
27478d3b1a2dSKevin Wolf 
2748d75cbb5eSPeter Lieven /*
2749d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2750d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2751d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2752d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2753d75cbb5eSPeter Lieven  *
2754d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2755d75cbb5eSPeter Lieven  */
2756d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2757d75cbb5eSPeter Lieven {
2758d32f7c10SMarkus Armbruster     int64_t target_sectors, ret, nb_sectors, sector_num = 0;
2759d75cbb5eSPeter Lieven     int n;
2760d75cbb5eSPeter Lieven 
2761d32f7c10SMarkus Armbruster     target_sectors = bdrv_nb_sectors(bs);
2762d32f7c10SMarkus Armbruster     if (target_sectors < 0) {
2763d32f7c10SMarkus Armbruster         return target_sectors;
27649ce10c0bSKevin Wolf     }
27659ce10c0bSKevin Wolf 
2766d75cbb5eSPeter Lieven     for (;;) {
2767d32f7c10SMarkus Armbruster         nb_sectors = target_sectors - sector_num;
2768d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2769d75cbb5eSPeter Lieven             return 0;
2770d75cbb5eSPeter Lieven         }
2771d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2772d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2773d75cbb5eSPeter Lieven         }
2774d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
27753d94ce60SPeter Lieven         if (ret < 0) {
27763d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
27773d94ce60SPeter Lieven                          sector_num, strerror(-ret));
27783d94ce60SPeter Lieven             return ret;
27793d94ce60SPeter Lieven         }
2780d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2781d75cbb5eSPeter Lieven             sector_num += n;
2782d75cbb5eSPeter Lieven             continue;
2783d75cbb5eSPeter Lieven         }
2784d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2785d75cbb5eSPeter Lieven         if (ret < 0) {
2786d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2787d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2788d75cbb5eSPeter Lieven             return ret;
2789d75cbb5eSPeter Lieven         }
2790d75cbb5eSPeter Lieven         sector_num += n;
2791d75cbb5eSPeter Lieven     }
2792d75cbb5eSPeter Lieven }
2793d75cbb5eSPeter Lieven 
2794a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
279583f64091Sbellard {
2796a3ef6571SKevin Wolf     QEMUIOVector qiov;
2797a3ef6571SKevin Wolf     struct iovec iov = {
2798a3ef6571SKevin Wolf         .iov_base = (void *)buf,
2799a3ef6571SKevin Wolf         .iov_len = bytes,
2800a3ef6571SKevin Wolf     };
28019a8c4cceSKevin Wolf     int ret;
280283f64091Sbellard 
2803a3ef6571SKevin Wolf     if (bytes < 0) {
2804a3ef6571SKevin Wolf         return -EINVAL;
280583f64091Sbellard     }
280683f64091Sbellard 
2807a3ef6571SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2808a3ef6571SKevin Wolf     ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
2809a3ef6571SKevin Wolf     if (ret < 0) {
28109a8c4cceSKevin Wolf         return ret;
281183f64091Sbellard     }
281283f64091Sbellard 
2813a3ef6571SKevin Wolf     return bytes;
281483f64091Sbellard }
281583f64091Sbellard 
28168d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
281783f64091Sbellard {
28189a8c4cceSKevin Wolf     int ret;
281983f64091Sbellard 
28208407d5d7SKevin Wolf     ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
28218d3b1a2dSKevin Wolf     if (ret < 0) {
28229a8c4cceSKevin Wolf         return ret;
28238d3b1a2dSKevin Wolf     }
28248d3b1a2dSKevin Wolf 
28258d3b1a2dSKevin Wolf     return qiov->size;
28268d3b1a2dSKevin Wolf }
28278d3b1a2dSKevin Wolf 
28288d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
28298407d5d7SKevin Wolf                 const void *buf, int bytes)
28308d3b1a2dSKevin Wolf {
28318d3b1a2dSKevin Wolf     QEMUIOVector qiov;
28328d3b1a2dSKevin Wolf     struct iovec iov = {
28338d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
28348407d5d7SKevin Wolf         .iov_len    = bytes,
28358d3b1a2dSKevin Wolf     };
28368d3b1a2dSKevin Wolf 
28378407d5d7SKevin Wolf     if (bytes < 0) {
28388407d5d7SKevin Wolf         return -EINVAL;
28398407d5d7SKevin Wolf     }
28408407d5d7SKevin Wolf 
28418d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
28428d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
284383f64091Sbellard }
284483f64091Sbellard 
2845f08145feSKevin Wolf /*
2846f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2847f08145feSKevin Wolf  * request (acts as a barrier)
2848f08145feSKevin Wolf  *
2849f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2850f08145feSKevin Wolf  */
2851f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2852f08145feSKevin Wolf     const void *buf, int count)
2853f08145feSKevin Wolf {
2854f08145feSKevin Wolf     int ret;
2855f08145feSKevin Wolf 
2856f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2857f08145feSKevin Wolf     if (ret < 0) {
2858f08145feSKevin Wolf         return ret;
2859f08145feSKevin Wolf     }
2860f08145feSKevin Wolf 
2861f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2862f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2863f08145feSKevin Wolf         bdrv_flush(bs);
2864f08145feSKevin Wolf     }
2865f08145feSKevin Wolf 
2866f08145feSKevin Wolf     return 0;
2867f08145feSKevin Wolf }
2868f08145feSKevin Wolf 
2869470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2870ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2871ab185921SStefan Hajnoczi {
2872ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2873ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2874ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2875ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2876ab185921SStefan Hajnoczi      */
2877ab185921SStefan Hajnoczi     void *bounce_buffer;
2878ab185921SStefan Hajnoczi 
287979c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2880ab185921SStefan Hajnoczi     struct iovec iov;
2881ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2882ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2883ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2884ab185921SStefan Hajnoczi     size_t skip_bytes;
2885ab185921SStefan Hajnoczi     int ret;
2886ab185921SStefan Hajnoczi 
2887ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2888ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2889ab185921SStefan Hajnoczi      */
2890343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2891ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2892ab185921SStefan Hajnoczi 
2893470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2894ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2895ab185921SStefan Hajnoczi 
2896ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2897857d4f46SKevin Wolf     iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
2898857d4f46SKevin Wolf     if (bounce_buffer == NULL) {
2899857d4f46SKevin Wolf         ret = -ENOMEM;
2900857d4f46SKevin Wolf         goto err;
2901857d4f46SKevin Wolf     }
2902857d4f46SKevin Wolf 
2903ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2904ab185921SStefan Hajnoczi 
290579c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2906ab185921SStefan Hajnoczi                              &bounce_qiov);
2907ab185921SStefan Hajnoczi     if (ret < 0) {
2908ab185921SStefan Hajnoczi         goto err;
2909ab185921SStefan Hajnoczi     }
2910ab185921SStefan Hajnoczi 
291179c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
291279c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2913621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2914aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
291579c053bdSStefan Hajnoczi     } else {
2916f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2917f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2918f05fa4adSPaolo Bonzini          */
291979c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2920ab185921SStefan Hajnoczi                                   &bounce_qiov);
292179c053bdSStefan Hajnoczi     }
292279c053bdSStefan Hajnoczi 
2923ab185921SStefan Hajnoczi     if (ret < 0) {
2924ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2925ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2926ab185921SStefan Hajnoczi          * Simply report it in all cases.
2927ab185921SStefan Hajnoczi          */
2928ab185921SStefan Hajnoczi         goto err;
2929ab185921SStefan Hajnoczi     }
2930ab185921SStefan Hajnoczi 
2931ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
293203396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2933ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2934ab185921SStefan Hajnoczi 
2935ab185921SStefan Hajnoczi err:
2936ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2937ab185921SStefan Hajnoczi     return ret;
2938ab185921SStefan Hajnoczi }
2939ab185921SStefan Hajnoczi 
2940c5fbe571SStefan Hajnoczi /*
2941d0c7f642SKevin Wolf  * Forwards an already correctly aligned request to the BlockDriver. This
2942d0c7f642SKevin Wolf  * handles copy on read and zeroing after EOF; any other features must be
2943d0c7f642SKevin Wolf  * implemented by the caller.
2944c5fbe571SStefan Hajnoczi  */
2945d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
294665afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
2947ec746e10SKevin Wolf     int64_t align, QEMUIOVector *qiov, int flags)
2948da1fa91dSKevin Wolf {
2949da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2950dbffbdcfSStefan Hajnoczi     int ret;
2951da1fa91dSKevin Wolf 
2952d0c7f642SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
2953d0c7f642SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
2954da1fa91dSKevin Wolf 
2955d0c7f642SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2956d0c7f642SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
29578eb029c2SKevin Wolf     assert(!qiov || bytes == qiov->size);
2958d0c7f642SKevin Wolf 
2959d0c7f642SKevin Wolf     /* Handle Copy on Read and associated serialisation */
2960470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
29617327145fSKevin Wolf         /* If we touch the same cluster it counts as an overlap.  This
29627327145fSKevin Wolf          * guarantees that allocating writes will be serialized and not race
29637327145fSKevin Wolf          * with each other for the same cluster.  For example, in copy-on-read
29647327145fSKevin Wolf          * it ensures that the CoR read and write operations are atomic and
29657327145fSKevin Wolf          * guest writes cannot interleave between them. */
29667327145fSKevin Wolf         mark_request_serialising(req, bdrv_get_cluster_size(bs));
2967470c0504SStefan Hajnoczi     }
2968470c0504SStefan Hajnoczi 
29692dbafdc0SKevin Wolf     wait_serialising_requests(req);
2970f4658285SStefan Hajnoczi 
2971470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2972ab185921SStefan Hajnoczi         int pnum;
2973ab185921SStefan Hajnoczi 
2974bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2975ab185921SStefan Hajnoczi         if (ret < 0) {
2976ab185921SStefan Hajnoczi             goto out;
2977ab185921SStefan Hajnoczi         }
2978ab185921SStefan Hajnoczi 
2979ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2980470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2981ab185921SStefan Hajnoczi             goto out;
2982ab185921SStefan Hajnoczi         }
2983ab185921SStefan Hajnoczi     }
2984ab185921SStefan Hajnoczi 
2985d0c7f642SKevin Wolf     /* Forward the request to the BlockDriver */
2986893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2987dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2988893a8f62SMORITA Kazutaka     } else {
2989893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
29904049082cSMarkus Armbruster         int64_t total_sectors, max_nb_sectors;
2991893a8f62SMORITA Kazutaka 
29924049082cSMarkus Armbruster         total_sectors = bdrv_nb_sectors(bs);
29934049082cSMarkus Armbruster         if (total_sectors < 0) {
29944049082cSMarkus Armbruster             ret = total_sectors;
2995893a8f62SMORITA Kazutaka             goto out;
2996893a8f62SMORITA Kazutaka         }
2997893a8f62SMORITA Kazutaka 
29985f5bcd80SKevin Wolf         max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
29995f5bcd80SKevin Wolf                                   align >> BDRV_SECTOR_BITS);
3000893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
300133f461e0SKevin Wolf             QEMUIOVector local_qiov;
300233f461e0SKevin Wolf             size_t local_sectors;
300333f461e0SKevin Wolf 
300433f461e0SKevin Wolf             max_nb_sectors = MIN(max_nb_sectors, SIZE_MAX / BDRV_SECTOR_BITS);
300533f461e0SKevin Wolf             local_sectors = MIN(max_nb_sectors, nb_sectors);
300633f461e0SKevin Wolf 
300733f461e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov);
300833f461e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0,
300933f461e0SKevin Wolf                               local_sectors * BDRV_SECTOR_SIZE);
301033f461e0SKevin Wolf 
301133f461e0SKevin Wolf             ret = drv->bdrv_co_readv(bs, sector_num, local_sectors,
301233f461e0SKevin Wolf                                      &local_qiov);
301333f461e0SKevin Wolf 
301433f461e0SKevin Wolf             qemu_iovec_destroy(&local_qiov);
3015893a8f62SMORITA Kazutaka         } else {
3016893a8f62SMORITA Kazutaka             ret = 0;
3017893a8f62SMORITA Kazutaka         }
3018893a8f62SMORITA Kazutaka 
3019893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
3020893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
3021893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
3022893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
3023893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
3024893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
3025893a8f62SMORITA Kazutaka         }
3026893a8f62SMORITA Kazutaka     }
3027ab185921SStefan Hajnoczi 
3028ab185921SStefan Hajnoczi out:
3029dbffbdcfSStefan Hajnoczi     return ret;
3030da1fa91dSKevin Wolf }
3031da1fa91dSKevin Wolf 
3032d0c7f642SKevin Wolf /*
3033d0c7f642SKevin Wolf  * Handle a read request in coroutine context
3034d0c7f642SKevin Wolf  */
30351b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
30361b0288aeSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3037d0c7f642SKevin Wolf     BdrvRequestFlags flags)
3038d0c7f642SKevin Wolf {
3039d0c7f642SKevin Wolf     BlockDriver *drv = bs->drv;
304065afd211SKevin Wolf     BdrvTrackedRequest req;
304165afd211SKevin Wolf 
30421b0288aeSKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
30431b0288aeSKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
30441b0288aeSKevin Wolf     uint8_t *head_buf = NULL;
30451b0288aeSKevin Wolf     uint8_t *tail_buf = NULL;
30461b0288aeSKevin Wolf     QEMUIOVector local_qiov;
30471b0288aeSKevin Wolf     bool use_local_qiov = false;
3048d0c7f642SKevin Wolf     int ret;
3049d0c7f642SKevin Wolf 
3050d0c7f642SKevin Wolf     if (!drv) {
3051d0c7f642SKevin Wolf         return -ENOMEDIUM;
3052d0c7f642SKevin Wolf     }
30531b0288aeSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3054d0c7f642SKevin Wolf         return -EIO;
3055d0c7f642SKevin Wolf     }
3056d0c7f642SKevin Wolf 
3057d0c7f642SKevin Wolf     if (bs->copy_on_read) {
3058d0c7f642SKevin Wolf         flags |= BDRV_REQ_COPY_ON_READ;
3059d0c7f642SKevin Wolf     }
3060d0c7f642SKevin Wolf 
3061d0c7f642SKevin Wolf     /* throttling disk I/O */
3062d0c7f642SKevin Wolf     if (bs->io_limits_enabled) {
3063d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, false);
3064d0c7f642SKevin Wolf     }
3065d0c7f642SKevin Wolf 
30661b0288aeSKevin Wolf     /* Align read if necessary by padding qiov */
30671b0288aeSKevin Wolf     if (offset & (align - 1)) {
30681b0288aeSKevin Wolf         head_buf = qemu_blockalign(bs, align);
30691b0288aeSKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
30701b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
30711b0288aeSKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30721b0288aeSKevin Wolf         use_local_qiov = true;
30731b0288aeSKevin Wolf 
30741b0288aeSKevin Wolf         bytes += offset & (align - 1);
30751b0288aeSKevin Wolf         offset = offset & ~(align - 1);
30761b0288aeSKevin Wolf     }
30771b0288aeSKevin Wolf 
30781b0288aeSKevin Wolf     if ((offset + bytes) & (align - 1)) {
30791b0288aeSKevin Wolf         if (!use_local_qiov) {
30801b0288aeSKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
30811b0288aeSKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30821b0288aeSKevin Wolf             use_local_qiov = true;
30831b0288aeSKevin Wolf         }
30841b0288aeSKevin Wolf         tail_buf = qemu_blockalign(bs, align);
30851b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf,
30861b0288aeSKevin Wolf                        align - ((offset + bytes) & (align - 1)));
30871b0288aeSKevin Wolf 
30881b0288aeSKevin Wolf         bytes = ROUND_UP(bytes, align);
30891b0288aeSKevin Wolf     }
30901b0288aeSKevin Wolf 
309165afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, false);
3092ec746e10SKevin Wolf     ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
30931b0288aeSKevin Wolf                               use_local_qiov ? &local_qiov : qiov,
30941b0288aeSKevin Wolf                               flags);
309565afd211SKevin Wolf     tracked_request_end(&req);
30961b0288aeSKevin Wolf 
30971b0288aeSKevin Wolf     if (use_local_qiov) {
30981b0288aeSKevin Wolf         qemu_iovec_destroy(&local_qiov);
30991b0288aeSKevin Wolf         qemu_vfree(head_buf);
31001b0288aeSKevin Wolf         qemu_vfree(tail_buf);
31011b0288aeSKevin Wolf     }
31021b0288aeSKevin Wolf 
3103d0c7f642SKevin Wolf     return ret;
3104d0c7f642SKevin Wolf }
3105d0c7f642SKevin Wolf 
31061b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
31071b0288aeSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
31081b0288aeSKevin Wolf     BdrvRequestFlags flags)
31091b0288aeSKevin Wolf {
31101b0288aeSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
31111b0288aeSKevin Wolf         return -EINVAL;
31121b0288aeSKevin Wolf     }
31131b0288aeSKevin Wolf 
31141b0288aeSKevin Wolf     return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
31151b0288aeSKevin Wolf                              nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
31161b0288aeSKevin Wolf }
31171b0288aeSKevin Wolf 
3118c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
3119da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
3120da1fa91dSKevin Wolf {
3121c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
3122da1fa91dSKevin Wolf 
3123470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3124470c0504SStefan Hajnoczi }
3125470c0504SStefan Hajnoczi 
3126470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3127470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3128470c0504SStefan Hajnoczi {
3129470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3130470c0504SStefan Hajnoczi 
3131470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3132470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
3133c5fbe571SStefan Hajnoczi }
3134c5fbe571SStefan Hajnoczi 
3135c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
3136c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
3137c31cb707SPeter Lieven  */
3138c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
3139c31cb707SPeter Lieven 
3140f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
3141aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
3142f08f2ddaSStefan Hajnoczi {
3143f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3144f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3145c31cb707SPeter Lieven     struct iovec iov = {0};
3146c31cb707SPeter Lieven     int ret = 0;
3147f08f2ddaSStefan Hajnoczi 
3148c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3149c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3150621f0589SKevin Wolf 
3151c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3152c31cb707SPeter Lieven         int num = nb_sectors;
3153c31cb707SPeter Lieven 
3154b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3155b8d71c09SPaolo Bonzini          * to be aligned.
3156b8d71c09SPaolo Bonzini          */
3157b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3158b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3159b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3160b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3161c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3162c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3163b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3164b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3165b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3166b8d71c09SPaolo Bonzini                  */
3167b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3168b8d71c09SPaolo Bonzini             }
3169c31cb707SPeter Lieven         }
3170c31cb707SPeter Lieven 
3171c31cb707SPeter Lieven         /* limit request size */
3172c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3173c31cb707SPeter Lieven             num = max_write_zeroes;
3174c31cb707SPeter Lieven         }
3175c31cb707SPeter Lieven 
3176c31cb707SPeter Lieven         ret = -ENOTSUP;
3177f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3178f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3179c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3180f08f2ddaSStefan Hajnoczi         }
3181f08f2ddaSStefan Hajnoczi 
3182c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3183f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3184c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3185c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3186857d4f46SKevin Wolf                 iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE);
3187857d4f46SKevin Wolf                 if (iov.iov_base == NULL) {
3188857d4f46SKevin Wolf                     ret = -ENOMEM;
3189857d4f46SKevin Wolf                     goto fail;
3190857d4f46SKevin Wolf                 }
3191b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3192c31cb707SPeter Lieven             }
3193f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3194f08f2ddaSStefan Hajnoczi 
3195c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3196b8d71c09SPaolo Bonzini 
3197b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3198b8d71c09SPaolo Bonzini              * all future requests.
3199b8d71c09SPaolo Bonzini              */
3200b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3201b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3202b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3203b8d71c09SPaolo Bonzini             }
3204c31cb707SPeter Lieven         }
3205c31cb707SPeter Lieven 
3206c31cb707SPeter Lieven         sector_num += num;
3207c31cb707SPeter Lieven         nb_sectors -= num;
3208c31cb707SPeter Lieven     }
3209f08f2ddaSStefan Hajnoczi 
3210857d4f46SKevin Wolf fail:
3211f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3212f08f2ddaSStefan Hajnoczi     return ret;
3213f08f2ddaSStefan Hajnoczi }
3214f08f2ddaSStefan Hajnoczi 
3215c5fbe571SStefan Hajnoczi /*
3216b404f720SKevin Wolf  * Forwards an already correctly aligned write request to the BlockDriver.
3217c5fbe571SStefan Hajnoczi  */
3218b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
321965afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
322065afd211SKevin Wolf     QEMUIOVector *qiov, int flags)
3221c5fbe571SStefan Hajnoczi {
3222c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
322328de2dcdSKevin Wolf     bool waited;
32246b7cb247SStefan Hajnoczi     int ret;
3225da1fa91dSKevin Wolf 
3226b404f720SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3227b404f720SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3228da1fa91dSKevin Wolf 
3229b404f720SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3230b404f720SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
32318eb029c2SKevin Wolf     assert(!qiov || bytes == qiov->size);
3232cc0681c4SBenoît Canet 
323328de2dcdSKevin Wolf     waited = wait_serialising_requests(req);
323428de2dcdSKevin Wolf     assert(!waited || !req->serialising);
3235af91f9a7SKevin Wolf     assert(req->overlap_offset <= offset);
3236af91f9a7SKevin Wolf     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
3237244eadefSKevin Wolf 
323865afd211SKevin Wolf     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
3239d616b224SStefan Hajnoczi 
3240465bee1dSPeter Lieven     if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
3241465bee1dSPeter Lieven         !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
3242465bee1dSPeter Lieven         qemu_iovec_is_zero(qiov)) {
3243465bee1dSPeter Lieven         flags |= BDRV_REQ_ZERO_WRITE;
3244465bee1dSPeter Lieven         if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
3245465bee1dSPeter Lieven             flags |= BDRV_REQ_MAY_UNMAP;
3246465bee1dSPeter Lieven         }
3247465bee1dSPeter Lieven     }
3248465bee1dSPeter Lieven 
3249d616b224SStefan Hajnoczi     if (ret < 0) {
3250d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3251d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
32529e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
3253aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3254f08f2ddaSStefan Hajnoczi     } else {
32559e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
32566b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3257f08f2ddaSStefan Hajnoczi     }
32589e1cb96dSKevin Wolf     BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
32596b7cb247SStefan Hajnoczi 
3260f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3261f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3262f05fa4adSPaolo Bonzini     }
3263f05fa4adSPaolo Bonzini 
32641755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3265da1fa91dSKevin Wolf 
32665366d0c8SBenoît Canet     block_acct_highest_sector(&bs->stats, sector_num, nb_sectors);
32675e5a94b6SBenoît Canet 
3268df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3269df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3270df2a6f29SPaolo Bonzini     }
3271da1fa91dSKevin Wolf 
32726b7cb247SStefan Hajnoczi     return ret;
3273da1fa91dSKevin Wolf }
3274da1fa91dSKevin Wolf 
3275b404f720SKevin Wolf /*
3276b404f720SKevin Wolf  * Handle a write request in coroutine context
3277b404f720SKevin Wolf  */
32786601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
32796601553eSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3280b404f720SKevin Wolf     BdrvRequestFlags flags)
3281b404f720SKevin Wolf {
328265afd211SKevin Wolf     BdrvTrackedRequest req;
32833b8242e0SKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
32843b8242e0SKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
32853b8242e0SKevin Wolf     uint8_t *head_buf = NULL;
32863b8242e0SKevin Wolf     uint8_t *tail_buf = NULL;
32873b8242e0SKevin Wolf     QEMUIOVector local_qiov;
32883b8242e0SKevin Wolf     bool use_local_qiov = false;
3289b404f720SKevin Wolf     int ret;
3290b404f720SKevin Wolf 
3291b404f720SKevin Wolf     if (!bs->drv) {
3292b404f720SKevin Wolf         return -ENOMEDIUM;
3293b404f720SKevin Wolf     }
3294b404f720SKevin Wolf     if (bs->read_only) {
3295b404f720SKevin Wolf         return -EACCES;
3296b404f720SKevin Wolf     }
32976601553eSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3298b404f720SKevin Wolf         return -EIO;
3299b404f720SKevin Wolf     }
3300b404f720SKevin Wolf 
3301b404f720SKevin Wolf     /* throttling disk I/O */
3302b404f720SKevin Wolf     if (bs->io_limits_enabled) {
3303d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, true);
3304b404f720SKevin Wolf     }
3305b404f720SKevin Wolf 
33063b8242e0SKevin Wolf     /*
33073b8242e0SKevin Wolf      * Align write if necessary by performing a read-modify-write cycle.
33083b8242e0SKevin Wolf      * Pad qiov with the read parts and be sure to have a tracked request not
33093b8242e0SKevin Wolf      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
33103b8242e0SKevin Wolf      */
331165afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, true);
33123b8242e0SKevin Wolf 
33133b8242e0SKevin Wolf     if (offset & (align - 1)) {
33143b8242e0SKevin Wolf         QEMUIOVector head_qiov;
33153b8242e0SKevin Wolf         struct iovec head_iov;
33163b8242e0SKevin Wolf 
33173b8242e0SKevin Wolf         mark_request_serialising(&req, align);
33183b8242e0SKevin Wolf         wait_serialising_requests(&req);
33193b8242e0SKevin Wolf 
33203b8242e0SKevin Wolf         head_buf = qemu_blockalign(bs, align);
33213b8242e0SKevin Wolf         head_iov = (struct iovec) {
33223b8242e0SKevin Wolf             .iov_base   = head_buf,
33233b8242e0SKevin Wolf             .iov_len    = align,
33243b8242e0SKevin Wolf         };
33253b8242e0SKevin Wolf         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
33263b8242e0SKevin Wolf 
33279e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
33283b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
33293b8242e0SKevin Wolf                                   align, &head_qiov, 0);
33303b8242e0SKevin Wolf         if (ret < 0) {
33313b8242e0SKevin Wolf             goto fail;
33323b8242e0SKevin Wolf         }
33339e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
33343b8242e0SKevin Wolf 
33353b8242e0SKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
33363b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
33373b8242e0SKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
33383b8242e0SKevin Wolf         use_local_qiov = true;
33393b8242e0SKevin Wolf 
33403b8242e0SKevin Wolf         bytes += offset & (align - 1);
33413b8242e0SKevin Wolf         offset = offset & ~(align - 1);
33423b8242e0SKevin Wolf     }
33433b8242e0SKevin Wolf 
33443b8242e0SKevin Wolf     if ((offset + bytes) & (align - 1)) {
33453b8242e0SKevin Wolf         QEMUIOVector tail_qiov;
33463b8242e0SKevin Wolf         struct iovec tail_iov;
33473b8242e0SKevin Wolf         size_t tail_bytes;
334828de2dcdSKevin Wolf         bool waited;
33493b8242e0SKevin Wolf 
33503b8242e0SKevin Wolf         mark_request_serialising(&req, align);
335128de2dcdSKevin Wolf         waited = wait_serialising_requests(&req);
335228de2dcdSKevin Wolf         assert(!waited || !use_local_qiov);
33533b8242e0SKevin Wolf 
33543b8242e0SKevin Wolf         tail_buf = qemu_blockalign(bs, align);
33553b8242e0SKevin Wolf         tail_iov = (struct iovec) {
33563b8242e0SKevin Wolf             .iov_base   = tail_buf,
33573b8242e0SKevin Wolf             .iov_len    = align,
33583b8242e0SKevin Wolf         };
33593b8242e0SKevin Wolf         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
33603b8242e0SKevin Wolf 
33619e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
33623b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
33633b8242e0SKevin Wolf                                   align, &tail_qiov, 0);
33643b8242e0SKevin Wolf         if (ret < 0) {
33653b8242e0SKevin Wolf             goto fail;
33663b8242e0SKevin Wolf         }
33679e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
33683b8242e0SKevin Wolf 
33693b8242e0SKevin Wolf         if (!use_local_qiov) {
33703b8242e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
33713b8242e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
33723b8242e0SKevin Wolf             use_local_qiov = true;
33733b8242e0SKevin Wolf         }
33743b8242e0SKevin Wolf 
33753b8242e0SKevin Wolf         tail_bytes = (offset + bytes) & (align - 1);
33763b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
33773b8242e0SKevin Wolf 
33783b8242e0SKevin Wolf         bytes = ROUND_UP(bytes, align);
33793b8242e0SKevin Wolf     }
33803b8242e0SKevin Wolf 
33813b8242e0SKevin Wolf     ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
33823b8242e0SKevin Wolf                                use_local_qiov ? &local_qiov : qiov,
33833b8242e0SKevin Wolf                                flags);
33843b8242e0SKevin Wolf 
33853b8242e0SKevin Wolf fail:
338665afd211SKevin Wolf     tracked_request_end(&req);
3387b404f720SKevin Wolf 
33883b8242e0SKevin Wolf     if (use_local_qiov) {
33893b8242e0SKevin Wolf         qemu_iovec_destroy(&local_qiov);
339099c4a85cSKevin Wolf     }
33913b8242e0SKevin Wolf     qemu_vfree(head_buf);
33923b8242e0SKevin Wolf     qemu_vfree(tail_buf);
33933b8242e0SKevin Wolf 
3394b404f720SKevin Wolf     return ret;
3395b404f720SKevin Wolf }
3396b404f720SKevin Wolf 
33976601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
33986601553eSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
33996601553eSKevin Wolf     BdrvRequestFlags flags)
34006601553eSKevin Wolf {
34016601553eSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
34026601553eSKevin Wolf         return -EINVAL;
34036601553eSKevin Wolf     }
34046601553eSKevin Wolf 
34056601553eSKevin Wolf     return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
34066601553eSKevin Wolf                               nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
34076601553eSKevin Wolf }
34086601553eSKevin Wolf 
3409c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3410c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3411c5fbe571SStefan Hajnoczi {
3412c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3413c5fbe571SStefan Hajnoczi 
3414f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3415f08f2ddaSStefan Hajnoczi }
3416f08f2ddaSStefan Hajnoczi 
3417f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3418aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3419aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3420f08f2ddaSStefan Hajnoczi {
342194d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3422f08f2ddaSStefan Hajnoczi 
3423d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3424d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3425d32f35cbSPeter Lieven     }
3426d32f35cbSPeter Lieven 
3427f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3428aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3429c5fbe571SStefan Hajnoczi }
3430c5fbe571SStefan Hajnoczi 
343183f64091Sbellard /**
343283f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
343383f64091Sbellard  */
343483f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
343583f64091Sbellard {
343683f64091Sbellard     BlockDriver *drv = bs->drv;
343751762288SStefan Hajnoczi     int ret;
343883f64091Sbellard     if (!drv)
343919cb3738Sbellard         return -ENOMEDIUM;
344083f64091Sbellard     if (!drv->bdrv_truncate)
344183f64091Sbellard         return -ENOTSUP;
344259f2689dSNaphtali Sprei     if (bs->read_only)
344359f2689dSNaphtali Sprei         return -EACCES;
34449c75e168SJeff Cody 
344551762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
344651762288SStefan Hajnoczi     if (ret == 0) {
344751762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3448a7f53e26SMarkus Armbruster         if (bs->blk) {
3449a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
3450a7f53e26SMarkus Armbruster         }
345151762288SStefan Hajnoczi     }
345251762288SStefan Hajnoczi     return ret;
345383f64091Sbellard }
345483f64091Sbellard 
345583f64091Sbellard /**
34564a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
34574a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
34584a1d5e1fSFam Zheng  */
34594a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
34604a1d5e1fSFam Zheng {
34614a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
34624a1d5e1fSFam Zheng     if (!drv) {
34634a1d5e1fSFam Zheng         return -ENOMEDIUM;
34644a1d5e1fSFam Zheng     }
34654a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
34664a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
34674a1d5e1fSFam Zheng     }
34684a1d5e1fSFam Zheng     if (bs->file) {
34694a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
34704a1d5e1fSFam Zheng     }
34714a1d5e1fSFam Zheng     return -ENOTSUP;
34724a1d5e1fSFam Zheng }
34734a1d5e1fSFam Zheng 
34744a1d5e1fSFam Zheng /**
347565a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
347683f64091Sbellard  */
347765a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
347883f64091Sbellard {
347983f64091Sbellard     BlockDriver *drv = bs->drv;
348065a9bb25SMarkus Armbruster 
348183f64091Sbellard     if (!drv)
348219cb3738Sbellard         return -ENOMEDIUM;
348351762288SStefan Hajnoczi 
3484b94a2610SKevin Wolf     if (drv->has_variable_length) {
3485b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3486b94a2610SKevin Wolf         if (ret < 0) {
3487b94a2610SKevin Wolf             return ret;
3488fc01f7e7Sbellard         }
348946a4e4e6SStefan Hajnoczi     }
349065a9bb25SMarkus Armbruster     return bs->total_sectors;
349165a9bb25SMarkus Armbruster }
349265a9bb25SMarkus Armbruster 
349365a9bb25SMarkus Armbruster /**
349465a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
349565a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
349665a9bb25SMarkus Armbruster  */
349765a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
349865a9bb25SMarkus Armbruster {
349965a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
350065a9bb25SMarkus Armbruster 
350165a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
350246a4e4e6SStefan Hajnoczi }
3503fc01f7e7Sbellard 
350419cb3738Sbellard /* return 0 as number of sectors if no device present or error */
350596b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3506fc01f7e7Sbellard {
350765a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
350865a9bb25SMarkus Armbruster 
350965a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
3510fc01f7e7Sbellard }
3511cf98951bSbellard 
3512ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3513ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3514abd7f68dSMarkus Armbruster {
3515abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3516abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3517abd7f68dSMarkus Armbruster }
3518abd7f68dSMarkus Armbruster 
35191ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3520abd7f68dSMarkus Armbruster {
3521abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3522abd7f68dSMarkus Armbruster }
3523abd7f68dSMarkus Armbruster 
35243e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
35253e1caa5fSPaolo Bonzini {
35263e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
35273e1caa5fSPaolo Bonzini 
35283e1caa5fSPaolo Bonzini     switch (on_err) {
35293e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
3530a589569fSWenchao Xia         return (error == ENOSPC) ?
3531a589569fSWenchao Xia                BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
35323e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
3533a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_STOP;
35343e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
3535a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_REPORT;
35363e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
3537a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_IGNORE;
35383e1caa5fSPaolo Bonzini     default:
35393e1caa5fSPaolo Bonzini         abort();
35403e1caa5fSPaolo Bonzini     }
35413e1caa5fSPaolo Bonzini }
35423e1caa5fSPaolo Bonzini 
3543c7c2ff0cSLuiz Capitulino static void send_qmp_error_event(BlockDriverState *bs,
3544c7c2ff0cSLuiz Capitulino                                  BlockErrorAction action,
3545c7c2ff0cSLuiz Capitulino                                  bool is_read, int error)
3546c7c2ff0cSLuiz Capitulino {
3547573742a5SPeter Maydell     IoOperationType optype;
3548c7c2ff0cSLuiz Capitulino 
3549573742a5SPeter Maydell     optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
3550573742a5SPeter Maydell     qapi_event_send_block_io_error(bdrv_get_device_name(bs), optype, action,
3551c7c2ff0cSLuiz Capitulino                                    bdrv_iostatus_is_enabled(bs),
3552624ff573SLuiz Capitulino                                    error == ENOSPC, strerror(error),
3553624ff573SLuiz Capitulino                                    &error_abort);
3554c7c2ff0cSLuiz Capitulino }
3555c7c2ff0cSLuiz Capitulino 
35563e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
35573e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
35583e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
35593e1caa5fSPaolo Bonzini  */
35603e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
35613e1caa5fSPaolo Bonzini                        bool is_read, int error)
35623e1caa5fSPaolo Bonzini {
35633e1caa5fSPaolo Bonzini     assert(error >= 0);
35642bd3bce8SPaolo Bonzini 
3565a589569fSWenchao Xia     if (action == BLOCK_ERROR_ACTION_STOP) {
35662bd3bce8SPaolo Bonzini         /* First set the iostatus, so that "info block" returns an iostatus
35672bd3bce8SPaolo Bonzini          * that matches the events raised so far (an additional error iostatus
35682bd3bce8SPaolo Bonzini          * is fine, but not a lost one).
35692bd3bce8SPaolo Bonzini          */
35703e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
35712bd3bce8SPaolo Bonzini 
35722bd3bce8SPaolo Bonzini         /* Then raise the request to stop the VM and the event.
35732bd3bce8SPaolo Bonzini          * qemu_system_vmstop_request_prepare has two effects.  First,
35742bd3bce8SPaolo Bonzini          * it ensures that the STOP event always comes after the
35752bd3bce8SPaolo Bonzini          * BLOCK_IO_ERROR event.  Second, it ensures that even if management
35762bd3bce8SPaolo Bonzini          * can observe the STOP event and do a "cont" before the STOP
35772bd3bce8SPaolo Bonzini          * event is issued, the VM will not stop.  In this case, vm_start()
35782bd3bce8SPaolo Bonzini          * also ensures that the STOP/RESUME pair of events is emitted.
35792bd3bce8SPaolo Bonzini          */
35802bd3bce8SPaolo Bonzini         qemu_system_vmstop_request_prepare();
3581c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
35822bd3bce8SPaolo Bonzini         qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
35832bd3bce8SPaolo Bonzini     } else {
3584c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
35853e1caa5fSPaolo Bonzini     }
35863e1caa5fSPaolo Bonzini }
35873e1caa5fSPaolo Bonzini 
3588b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3589b338082bSbellard {
3590b338082bSbellard     return bs->read_only;
3591b338082bSbellard }
3592b338082bSbellard 
3593985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3594985a03b0Sths {
3595985a03b0Sths     return bs->sg;
3596985a03b0Sths }
3597985a03b0Sths 
3598e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3599e900a7b7SChristoph Hellwig {
3600e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3601e900a7b7SChristoph Hellwig }
3602e900a7b7SChristoph Hellwig 
3603425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3604425b0148SPaolo Bonzini {
3605425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
360655b110f2SJeff Cody 
360755b110f2SJeff Cody     /* so a reopen() will preserve wce */
360855b110f2SJeff Cody     if (wce) {
360955b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
361055b110f2SJeff Cody     } else {
361155b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
361255b110f2SJeff Cody     }
3613425b0148SPaolo Bonzini }
3614425b0148SPaolo Bonzini 
3615ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3616ea2384d3Sbellard {
3617ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3618ea2384d3Sbellard         return 1;
3619ea2384d3Sbellard     return bs->encrypted;
3620ea2384d3Sbellard }
3621ea2384d3Sbellard 
3622c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3623c0f4ce77Saliguori {
3624c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3625c0f4ce77Saliguori 
3626c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3627c0f4ce77Saliguori         return 1;
3628c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3629c0f4ce77Saliguori }
3630c0f4ce77Saliguori 
3631ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3632ea2384d3Sbellard {
3633ea2384d3Sbellard     int ret;
3634ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3635ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3636ea2384d3Sbellard         if (ret < 0)
3637ea2384d3Sbellard             return ret;
3638ea2384d3Sbellard         if (!bs->encrypted)
3639ea2384d3Sbellard             return 0;
3640ea2384d3Sbellard     }
3641fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3642fd04a2aeSShahar Havivi         return -EINVAL;
3643fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3644fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3645fd04a2aeSShahar Havivi     }
3646c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3647bb5fc20fSaliguori     if (ret < 0) {
3648bb5fc20fSaliguori         bs->valid_key = 0;
3649bb5fc20fSaliguori     } else if (!bs->valid_key) {
3650bb5fc20fSaliguori         bs->valid_key = 1;
3651a7f53e26SMarkus Armbruster         if (bs->blk) {
3652bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
3653a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
3654a7f53e26SMarkus Armbruster         }
3655bb5fc20fSaliguori     }
3656c0f4ce77Saliguori     return ret;
3657ea2384d3Sbellard }
3658ea2384d3Sbellard 
3659f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3660ea2384d3Sbellard {
3661f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3662ea2384d3Sbellard }
3663ea2384d3Sbellard 
3664ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
3665ada42401SStefan Hajnoczi {
3666ada42401SStefan Hajnoczi     return strcmp(a, b);
3667ada42401SStefan Hajnoczi }
3668ada42401SStefan Hajnoczi 
3669ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3670ea2384d3Sbellard                          void *opaque)
3671ea2384d3Sbellard {
3672ea2384d3Sbellard     BlockDriver *drv;
3673e855e4fbSJeff Cody     int count = 0;
3674ada42401SStefan Hajnoczi     int i;
3675e855e4fbSJeff Cody     const char **formats = NULL;
3676ea2384d3Sbellard 
36778a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3678e855e4fbSJeff Cody         if (drv->format_name) {
3679e855e4fbSJeff Cody             bool found = false;
3680e855e4fbSJeff Cody             int i = count;
3681e855e4fbSJeff Cody             while (formats && i && !found) {
3682e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
3683e855e4fbSJeff Cody             }
3684e855e4fbSJeff Cody 
3685e855e4fbSJeff Cody             if (!found) {
36865839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
3687e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
3688ea2384d3Sbellard             }
3689ea2384d3Sbellard         }
3690e855e4fbSJeff Cody     }
3691ada42401SStefan Hajnoczi 
3692ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
3693ada42401SStefan Hajnoczi 
3694ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
3695ada42401SStefan Hajnoczi         it(opaque, formats[i]);
3696ada42401SStefan Hajnoczi     }
3697ada42401SStefan Hajnoczi 
3698e855e4fbSJeff Cody     g_free(formats);
3699e855e4fbSJeff Cody }
3700ea2384d3Sbellard 
3701dc364f4cSBenoît Canet /* This function is to find block backend bs */
37027f06d47eSMarkus Armbruster /* TODO convert callers to blk_by_name(), then remove */
3703b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3704b338082bSbellard {
37057f06d47eSMarkus Armbruster     BlockBackend *blk = blk_by_name(name);
3706b338082bSbellard 
37077f06d47eSMarkus Armbruster     return blk ? blk_bs(blk) : NULL;
3708b338082bSbellard }
3709b338082bSbellard 
3710dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3711dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3712dc364f4cSBenoît Canet {
3713dc364f4cSBenoît Canet     BlockDriverState *bs;
3714dc364f4cSBenoît Canet 
3715dc364f4cSBenoît Canet     assert(node_name);
3716dc364f4cSBenoît Canet 
3717dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3718dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3719dc364f4cSBenoît Canet             return bs;
3720dc364f4cSBenoît Canet         }
3721dc364f4cSBenoît Canet     }
3722dc364f4cSBenoît Canet     return NULL;
3723dc364f4cSBenoît Canet }
3724dc364f4cSBenoît Canet 
3725c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3726c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3727c13163fbSBenoît Canet {
3728c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3729c13163fbSBenoît Canet     BlockDriverState *bs;
3730c13163fbSBenoît Canet 
3731c13163fbSBenoît Canet     list = NULL;
3732c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3733c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3734c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3735c13163fbSBenoît Canet         entry->next = list;
3736c13163fbSBenoît Canet         list = entry;
3737c13163fbSBenoît Canet     }
3738c13163fbSBenoît Canet 
3739c13163fbSBenoît Canet     return list;
3740c13163fbSBenoît Canet }
3741c13163fbSBenoît Canet 
374212d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
374312d3ba82SBenoît Canet                                  const char *node_name,
374412d3ba82SBenoît Canet                                  Error **errp)
374512d3ba82SBenoît Canet {
37467f06d47eSMarkus Armbruster     BlockBackend *blk;
37477f06d47eSMarkus Armbruster     BlockDriverState *bs;
374812d3ba82SBenoît Canet 
374912d3ba82SBenoît Canet     if (device) {
37507f06d47eSMarkus Armbruster         blk = blk_by_name(device);
375112d3ba82SBenoît Canet 
37527f06d47eSMarkus Armbruster         if (blk) {
37537f06d47eSMarkus Armbruster             return blk_bs(blk);
375412d3ba82SBenoît Canet         }
3755dd67fa50SBenoît Canet     }
375612d3ba82SBenoît Canet 
3757dd67fa50SBenoît Canet     if (node_name) {
375812d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
375912d3ba82SBenoît Canet 
3760dd67fa50SBenoît Canet         if (bs) {
3761dd67fa50SBenoît Canet             return bs;
3762dd67fa50SBenoît Canet         }
376312d3ba82SBenoît Canet     }
376412d3ba82SBenoît Canet 
3765dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
3766dd67fa50SBenoît Canet                      device ? device : "",
3767dd67fa50SBenoît Canet                      node_name ? node_name : "");
3768dd67fa50SBenoît Canet     return NULL;
376912d3ba82SBenoît Canet }
377012d3ba82SBenoît Canet 
37715a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
37725a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
37735a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
37745a6684d2SJeff Cody {
37755a6684d2SJeff Cody     while (top && top != base) {
37765a6684d2SJeff Cody         top = top->backing_hd;
37775a6684d2SJeff Cody     }
37785a6684d2SJeff Cody 
37795a6684d2SJeff Cody     return top != NULL;
37805a6684d2SJeff Cody }
37815a6684d2SJeff Cody 
37822f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
37832f399b0aSMarkus Armbruster {
37842f399b0aSMarkus Armbruster     if (!bs) {
37852f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
37862f399b0aSMarkus Armbruster     }
3787dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
37882f399b0aSMarkus Armbruster }
37892f399b0aSMarkus Armbruster 
37907f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
3791bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
3792ea2384d3Sbellard {
3793bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
3794ea2384d3Sbellard }
3795ea2384d3Sbellard 
3796c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3797c8433287SMarkus Armbruster {
3798c8433287SMarkus Armbruster     return bs->open_flags;
3799c8433287SMarkus Armbruster }
3800c8433287SMarkus Armbruster 
3801f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3802c6ca28d6Saliguori {
3803c6ca28d6Saliguori     BlockDriverState *bs;
3804f0f0fdfeSKevin Wolf     int result = 0;
3805c6ca28d6Saliguori 
3806dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3807ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3808ed78cda3SStefan Hajnoczi         int ret;
3809ed78cda3SStefan Hajnoczi 
3810ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
3811ed78cda3SStefan Hajnoczi         ret = bdrv_flush(bs);
3812f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3813f0f0fdfeSKevin Wolf             result = ret;
3814c6ca28d6Saliguori         }
3815ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
38161b7bdbc1SStefan Hajnoczi     }
3817c6ca28d6Saliguori 
3818f0f0fdfeSKevin Wolf     return result;
3819f0f0fdfeSKevin Wolf }
3820f0f0fdfeSKevin Wolf 
38213ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
38223ac21627SPeter Lieven {
38233ac21627SPeter Lieven     return 1;
38243ac21627SPeter Lieven }
38253ac21627SPeter Lieven 
3826f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3827f2feebbdSKevin Wolf {
3828f2feebbdSKevin Wolf     assert(bs->drv);
3829f2feebbdSKevin Wolf 
383011212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
383111212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
383211212d8fSPaolo Bonzini     if (bs->backing_hd) {
383311212d8fSPaolo Bonzini         return 0;
383411212d8fSPaolo Bonzini     }
3835336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3836336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3837f2feebbdSKevin Wolf     }
3838f2feebbdSKevin Wolf 
38393ac21627SPeter Lieven     /* safe default */
38403ac21627SPeter Lieven     return 0;
3841f2feebbdSKevin Wolf }
3842f2feebbdSKevin Wolf 
38434ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
38444ce78691SPeter Lieven {
38454ce78691SPeter Lieven     BlockDriverInfo bdi;
38464ce78691SPeter Lieven 
38474ce78691SPeter Lieven     if (bs->backing_hd) {
38484ce78691SPeter Lieven         return false;
38494ce78691SPeter Lieven     }
38504ce78691SPeter Lieven 
38514ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
38524ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
38534ce78691SPeter Lieven     }
38544ce78691SPeter Lieven 
38554ce78691SPeter Lieven     return false;
38564ce78691SPeter Lieven }
38574ce78691SPeter Lieven 
38584ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
38594ce78691SPeter Lieven {
38604ce78691SPeter Lieven     BlockDriverInfo bdi;
38614ce78691SPeter Lieven 
38624ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
38634ce78691SPeter Lieven         return false;
38644ce78691SPeter Lieven     }
38654ce78691SPeter Lieven 
38664ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
38674ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
38684ce78691SPeter Lieven     }
38694ce78691SPeter Lieven 
38704ce78691SPeter Lieven     return false;
38714ce78691SPeter Lieven }
38724ce78691SPeter Lieven 
3873b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3874376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3875b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3876376ae3f1SStefan Hajnoczi     int64_t sector_num;
3877376ae3f1SStefan Hajnoczi     int nb_sectors;
3878376ae3f1SStefan Hajnoczi     int *pnum;
3879b6b8a333SPaolo Bonzini     int64_t ret;
3880376ae3f1SStefan Hajnoczi     bool done;
3881b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3882376ae3f1SStefan Hajnoczi 
3883f58c7b35Sths /*
3884f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3885f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3886f58c7b35Sths  * hence all their sectors are reported as allocated.
3887f58c7b35Sths  *
3888bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3889bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3890bd9533e3SStefan Hajnoczi  *
3891f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3892f58c7b35Sths  * the specified sector) that are known to be in the same
3893f58c7b35Sths  * allocated/unallocated state.
3894f58c7b35Sths  *
3895bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3896bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3897f58c7b35Sths  */
3898b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3899bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3900060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3901f58c7b35Sths {
390230a7f2fcSMarkus Armbruster     int64_t total_sectors;
3903f58c7b35Sths     int64_t n;
39045daa74a6SPaolo Bonzini     int64_t ret, ret2;
3905bd9533e3SStefan Hajnoczi 
390630a7f2fcSMarkus Armbruster     total_sectors = bdrv_nb_sectors(bs);
390730a7f2fcSMarkus Armbruster     if (total_sectors < 0) {
390830a7f2fcSMarkus Armbruster         return total_sectors;
3909617ccb46SPaolo Bonzini     }
3910617ccb46SPaolo Bonzini 
391130a7f2fcSMarkus Armbruster     if (sector_num >= total_sectors) {
39126aebab14SStefan Hajnoczi         *pnum = 0;
39136aebab14SStefan Hajnoczi         return 0;
39146aebab14SStefan Hajnoczi     }
3915bd9533e3SStefan Hajnoczi 
391630a7f2fcSMarkus Armbruster     n = total_sectors - sector_num;
3917bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3918bd9533e3SStefan Hajnoczi         nb_sectors = n;
3919bd9533e3SStefan Hajnoczi     }
3920bd9533e3SStefan Hajnoczi 
3921b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3922bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3923e88ae226SKevin Wolf         ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
3924918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3925918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3926918e92d7SPaolo Bonzini         }
3927918e92d7SPaolo Bonzini         return ret;
39286aebab14SStefan Hajnoczi     }
39296aebab14SStefan Hajnoczi 
3930415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3931415b5b01SPaolo Bonzini     if (ret < 0) {
39323e0a233dSPeter Lieven         *pnum = 0;
3933415b5b01SPaolo Bonzini         return ret;
3934415b5b01SPaolo Bonzini     }
3935415b5b01SPaolo Bonzini 
393692bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
393792bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
393892bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
393992bc50a5SPeter Lieven                                      *pnum, pnum);
394092bc50a5SPeter Lieven     }
394192bc50a5SPeter Lieven 
3942e88ae226SKevin Wolf     if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
3943e88ae226SKevin Wolf         ret |= BDRV_BLOCK_ALLOCATED;
3944e88ae226SKevin Wolf     }
3945e88ae226SKevin Wolf 
3946c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3947c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
3948415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
39491f9db224SPeter Lieven         } else if (bs->backing_hd) {
3950f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
395130a7f2fcSMarkus Armbruster             int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
395230a7f2fcSMarkus Armbruster             if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
3953f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3954f0ad5712SPaolo Bonzini             }
3955f0ad5712SPaolo Bonzini         }
3956415b5b01SPaolo Bonzini     }
39575daa74a6SPaolo Bonzini 
39585daa74a6SPaolo Bonzini     if (bs->file &&
39595daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
39605daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
396159c9a95fSMax Reitz         int file_pnum;
396259c9a95fSMax Reitz 
39635daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
396459c9a95fSMax Reitz                                         *pnum, &file_pnum);
39655daa74a6SPaolo Bonzini         if (ret2 >= 0) {
39665daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
39675daa74a6SPaolo Bonzini              * is useful but not necessary.
39685daa74a6SPaolo Bonzini              */
396959c9a95fSMax Reitz             if (!file_pnum) {
397059c9a95fSMax Reitz                 /* !file_pnum indicates an offset at or beyond the EOF; it is
397159c9a95fSMax Reitz                  * perfectly valid for the format block driver to point to such
397259c9a95fSMax Reitz                  * offsets, so catch it and mark everything as zero */
397359c9a95fSMax Reitz                 ret |= BDRV_BLOCK_ZERO;
397459c9a95fSMax Reitz             } else {
397559c9a95fSMax Reitz                 /* Limit request to the range reported by the protocol driver */
397659c9a95fSMax Reitz                 *pnum = file_pnum;
39775daa74a6SPaolo Bonzini                 ret |= (ret2 & BDRV_BLOCK_ZERO);
39785daa74a6SPaolo Bonzini             }
39795daa74a6SPaolo Bonzini         }
398059c9a95fSMax Reitz     }
39815daa74a6SPaolo Bonzini 
3982415b5b01SPaolo Bonzini     return ret;
3983060f51c9SStefan Hajnoczi }
3984060f51c9SStefan Hajnoczi 
3985b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3986b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3987060f51c9SStefan Hajnoczi {
3988b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3989060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3990060f51c9SStefan Hajnoczi 
3991b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3992060f51c9SStefan Hajnoczi                                          data->pnum);
3993060f51c9SStefan Hajnoczi     data->done = true;
3994060f51c9SStefan Hajnoczi }
3995060f51c9SStefan Hajnoczi 
3996060f51c9SStefan Hajnoczi /*
3997b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3998060f51c9SStefan Hajnoczi  *
3999b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
4000060f51c9SStefan Hajnoczi  */
4001b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
4002b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
4003060f51c9SStefan Hajnoczi {
4004376ae3f1SStefan Hajnoczi     Coroutine *co;
4005b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
4006376ae3f1SStefan Hajnoczi         .bs = bs,
4007376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
4008376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
4009376ae3f1SStefan Hajnoczi         .pnum = pnum,
4010376ae3f1SStefan Hajnoczi         .done = false,
4011376ae3f1SStefan Hajnoczi     };
4012376ae3f1SStefan Hajnoczi 
4013bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
4014bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
4015b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
4016bdad13b9SPaolo Bonzini     } else {
40172572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
40182572b37aSStefan Hajnoczi 
4019b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
4020376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
4021376ae3f1SStefan Hajnoczi         while (!data.done) {
40222572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
4023376ae3f1SStefan Hajnoczi         }
4024bdad13b9SPaolo Bonzini     }
4025376ae3f1SStefan Hajnoczi     return data.ret;
4026376ae3f1SStefan Hajnoczi }
4027f58c7b35Sths 
4028b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
4029b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
4030b6b8a333SPaolo Bonzini {
40314333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
40324333bb71SPaolo Bonzini     if (ret < 0) {
40334333bb71SPaolo Bonzini         return ret;
40344333bb71SPaolo Bonzini     }
403501fb2705SKevin Wolf     return !!(ret & BDRV_BLOCK_ALLOCATED);
4036b6b8a333SPaolo Bonzini }
4037b6b8a333SPaolo Bonzini 
4038188a7bbfSPaolo Bonzini /*
4039188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
4040188a7bbfSPaolo Bonzini  *
4041188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
4042188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
4043188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
4044188a7bbfSPaolo Bonzini  *
4045188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
4046188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
4047188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
4048188a7bbfSPaolo Bonzini  *
4049188a7bbfSPaolo Bonzini  */
40504f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
4051188a7bbfSPaolo Bonzini                             BlockDriverState *base,
4052188a7bbfSPaolo Bonzini                             int64_t sector_num,
4053188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
4054188a7bbfSPaolo Bonzini {
4055188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
4056188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
4057188a7bbfSPaolo Bonzini 
4058188a7bbfSPaolo Bonzini     intermediate = top;
4059188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
4060188a7bbfSPaolo Bonzini         int pnum_inter;
4061bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
4062188a7bbfSPaolo Bonzini                                 &pnum_inter);
4063188a7bbfSPaolo Bonzini         if (ret < 0) {
4064188a7bbfSPaolo Bonzini             return ret;
4065188a7bbfSPaolo Bonzini         } else if (ret) {
4066188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
4067188a7bbfSPaolo Bonzini             return 1;
4068188a7bbfSPaolo Bonzini         }
4069188a7bbfSPaolo Bonzini 
4070188a7bbfSPaolo Bonzini         /*
4071188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
4072188a7bbfSPaolo Bonzini          * might have
4073188a7bbfSPaolo Bonzini          *
4074188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
4075188a7bbfSPaolo Bonzini          */
407663ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
407763ba17d3SVishvananda Ishaya             (intermediate == top ||
407863ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
4079188a7bbfSPaolo Bonzini             n = pnum_inter;
4080188a7bbfSPaolo Bonzini         }
4081188a7bbfSPaolo Bonzini 
4082188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
4083188a7bbfSPaolo Bonzini     }
4084188a7bbfSPaolo Bonzini 
4085188a7bbfSPaolo Bonzini     *pnum = n;
4086188a7bbfSPaolo Bonzini     return 0;
4087188a7bbfSPaolo Bonzini }
4088188a7bbfSPaolo Bonzini 
4089045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
4090045df330Saliguori {
4091045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
4092045df330Saliguori         return bs->backing_file;
4093045df330Saliguori     else if (bs->encrypted)
4094045df330Saliguori         return bs->filename;
4095045df330Saliguori     else
4096045df330Saliguori         return NULL;
4097045df330Saliguori }
4098045df330Saliguori 
409983f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
410083f64091Sbellard                                char *filename, int filename_size)
410183f64091Sbellard {
410283f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
410383f64091Sbellard }
410483f64091Sbellard 
4105faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
4106faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
4107faea38e7Sbellard {
4108faea38e7Sbellard     BlockDriver *drv = bs->drv;
4109faea38e7Sbellard     if (!drv)
411019cb3738Sbellard         return -ENOMEDIUM;
4111faea38e7Sbellard     if (!drv->bdrv_write_compressed)
4112faea38e7Sbellard         return -ENOTSUP;
4113fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
4114fbb7b4e0SKevin Wolf         return -EIO;
41157cd1e32aSlirans@il.ibm.com 
4116e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
41177cd1e32aSlirans@il.ibm.com 
4118faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
4119faea38e7Sbellard }
4120faea38e7Sbellard 
4121faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4122faea38e7Sbellard {
4123faea38e7Sbellard     BlockDriver *drv = bs->drv;
4124faea38e7Sbellard     if (!drv)
412519cb3738Sbellard         return -ENOMEDIUM;
4126faea38e7Sbellard     if (!drv->bdrv_get_info)
4127faea38e7Sbellard         return -ENOTSUP;
4128faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
4129faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
4130faea38e7Sbellard }
4131faea38e7Sbellard 
4132eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
4133eae041feSMax Reitz {
4134eae041feSMax Reitz     BlockDriver *drv = bs->drv;
4135eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
4136eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
4137eae041feSMax Reitz     }
4138eae041feSMax Reitz     return NULL;
4139eae041feSMax Reitz }
4140eae041feSMax Reitz 
414145566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
414245566e9cSChristoph Hellwig                       int64_t pos, int size)
4143178e08a5Saliguori {
4144cf8074b3SKevin Wolf     QEMUIOVector qiov;
4145cf8074b3SKevin Wolf     struct iovec iov = {
4146cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
4147cf8074b3SKevin Wolf         .iov_len    = size,
4148cf8074b3SKevin Wolf     };
4149cf8074b3SKevin Wolf 
4150cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
4151cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
4152cf8074b3SKevin Wolf }
4153cf8074b3SKevin Wolf 
4154cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
4155cf8074b3SKevin Wolf {
4156178e08a5Saliguori     BlockDriver *drv = bs->drv;
4157cf8074b3SKevin Wolf 
4158cf8074b3SKevin Wolf     if (!drv) {
4159178e08a5Saliguori         return -ENOMEDIUM;
4160cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
4161cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
4162cf8074b3SKevin Wolf     } else if (bs->file) {
4163cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
4164cf8074b3SKevin Wolf     }
4165cf8074b3SKevin Wolf 
41667cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4167178e08a5Saliguori }
4168178e08a5Saliguori 
416945566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
417045566e9cSChristoph Hellwig                       int64_t pos, int size)
4171178e08a5Saliguori {
4172178e08a5Saliguori     BlockDriver *drv = bs->drv;
4173178e08a5Saliguori     if (!drv)
4174178e08a5Saliguori         return -ENOMEDIUM;
41757cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
417645566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
41777cdb1f6dSMORITA Kazutaka     if (bs->file)
41787cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
41797cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4180178e08a5Saliguori }
4181178e08a5Saliguori 
41828b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
41838b9b0cc2SKevin Wolf {
4184bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
41858b9b0cc2SKevin Wolf         return;
41868b9b0cc2SKevin Wolf     }
41878b9b0cc2SKevin Wolf 
4188bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
418941c695c7SKevin Wolf }
41908b9b0cc2SKevin Wolf 
419141c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
419241c695c7SKevin Wolf                           const char *tag)
419341c695c7SKevin Wolf {
419441c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
419541c695c7SKevin Wolf         bs = bs->file;
419641c695c7SKevin Wolf     }
419741c695c7SKevin Wolf 
419841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
419941c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
420041c695c7SKevin Wolf     }
420141c695c7SKevin Wolf 
420241c695c7SKevin Wolf     return -ENOTSUP;
420341c695c7SKevin Wolf }
420441c695c7SKevin Wolf 
42054cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
42064cc70e93SFam Zheng {
42074cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
42084cc70e93SFam Zheng         bs = bs->file;
42094cc70e93SFam Zheng     }
42104cc70e93SFam Zheng 
42114cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
42124cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
42134cc70e93SFam Zheng     }
42144cc70e93SFam Zheng 
42154cc70e93SFam Zheng     return -ENOTSUP;
42164cc70e93SFam Zheng }
42174cc70e93SFam Zheng 
421841c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
421941c695c7SKevin Wolf {
4220938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
422141c695c7SKevin Wolf         bs = bs->file;
422241c695c7SKevin Wolf     }
422341c695c7SKevin Wolf 
422441c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
422541c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
422641c695c7SKevin Wolf     }
422741c695c7SKevin Wolf 
422841c695c7SKevin Wolf     return -ENOTSUP;
422941c695c7SKevin Wolf }
423041c695c7SKevin Wolf 
423141c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
423241c695c7SKevin Wolf {
423341c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
423441c695c7SKevin Wolf         bs = bs->file;
423541c695c7SKevin Wolf     }
423641c695c7SKevin Wolf 
423741c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
423841c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
423941c695c7SKevin Wolf     }
424041c695c7SKevin Wolf 
424141c695c7SKevin Wolf     return false;
42428b9b0cc2SKevin Wolf }
42438b9b0cc2SKevin Wolf 
4244199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
4245199630b6SBlue Swirl {
4246199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4247199630b6SBlue Swirl }
4248199630b6SBlue Swirl 
4249b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
4250b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
4251b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
4252b1b1d783SJeff Cody  * the CWD rather than the chain. */
4253e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4254e8a6bb9cSMarcelo Tosatti         const char *backing_file)
4255e8a6bb9cSMarcelo Tosatti {
4256b1b1d783SJeff Cody     char *filename_full = NULL;
4257b1b1d783SJeff Cody     char *backing_file_full = NULL;
4258b1b1d783SJeff Cody     char *filename_tmp = NULL;
4259b1b1d783SJeff Cody     int is_protocol = 0;
4260b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
4261b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
4262b1b1d783SJeff Cody 
4263b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
4264e8a6bb9cSMarcelo Tosatti         return NULL;
4265e8a6bb9cSMarcelo Tosatti     }
4266e8a6bb9cSMarcelo Tosatti 
4267b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
4268b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
4269b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
4270b1b1d783SJeff Cody 
4271b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
4272b1b1d783SJeff Cody 
4273b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4274b1b1d783SJeff Cody 
4275b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
4276b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
4277b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4278b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4279b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4280b1b1d783SJeff Cody                 break;
4281b1b1d783SJeff Cody             }
4282e8a6bb9cSMarcelo Tosatti         } else {
4283b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
4284b1b1d783SJeff Cody              * image's filename path */
4285b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4286b1b1d783SJeff Cody                          backing_file);
4287b1b1d783SJeff Cody 
4288b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
4289b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
4290b1b1d783SJeff Cody                 continue;
4291b1b1d783SJeff Cody             }
4292b1b1d783SJeff Cody 
4293b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
4294b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
4295b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4296b1b1d783SJeff Cody                          curr_bs->backing_file);
4297b1b1d783SJeff Cody 
4298b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
4299b1b1d783SJeff Cody                 continue;
4300b1b1d783SJeff Cody             }
4301b1b1d783SJeff Cody 
4302b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
4303b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4304b1b1d783SJeff Cody                 break;
4305b1b1d783SJeff Cody             }
4306e8a6bb9cSMarcelo Tosatti         }
4307e8a6bb9cSMarcelo Tosatti     }
4308e8a6bb9cSMarcelo Tosatti 
4309b1b1d783SJeff Cody     g_free(filename_full);
4310b1b1d783SJeff Cody     g_free(backing_file_full);
4311b1b1d783SJeff Cody     g_free(filename_tmp);
4312b1b1d783SJeff Cody     return retval;
4313e8a6bb9cSMarcelo Tosatti }
4314e8a6bb9cSMarcelo Tosatti 
4315f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
4316f198fd1cSBenoît Canet {
4317f198fd1cSBenoît Canet     if (!bs->drv) {
4318f198fd1cSBenoît Canet         return 0;
4319f198fd1cSBenoît Canet     }
4320f198fd1cSBenoît Canet 
4321f198fd1cSBenoît Canet     if (!bs->backing_hd) {
4322f198fd1cSBenoît Canet         return 0;
4323f198fd1cSBenoît Canet     }
4324f198fd1cSBenoît Canet 
4325f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4326f198fd1cSBenoît Canet }
4327f198fd1cSBenoît Canet 
4328ea2384d3Sbellard /**************************************************************/
432983f64091Sbellard /* async I/Os */
4330ea2384d3Sbellard 
43317c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
4332f141eafeSaliguori                            QEMUIOVector *qiov, int nb_sectors,
4333097310b5SMarkus Armbruster                            BlockCompletionFunc *cb, void *opaque)
4334ea2384d3Sbellard {
4335bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4336bbf0a440SStefan Hajnoczi 
4337d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
43388c5873d6SStefan Hajnoczi                                  cb, opaque, false);
433983f64091Sbellard }
434083f64091Sbellard 
43417c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4342f141eafeSaliguori                             QEMUIOVector *qiov, int nb_sectors,
4343097310b5SMarkus Armbruster                             BlockCompletionFunc *cb, void *opaque)
43447674e7bfSbellard {
4345bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4346bbf0a440SStefan Hajnoczi 
4347d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
43488c5873d6SStefan Hajnoczi                                  cb, opaque, true);
434983f64091Sbellard }
435083f64091Sbellard 
43517c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4352d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4353097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque)
4354d5ef94d4SPaolo Bonzini {
4355d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4356d5ef94d4SPaolo Bonzini 
4357d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4358d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4359d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4360d5ef94d4SPaolo Bonzini }
4361d5ef94d4SPaolo Bonzini 
436240b4f539SKevin Wolf 
436340b4f539SKevin Wolf typedef struct MultiwriteCB {
436440b4f539SKevin Wolf     int error;
436540b4f539SKevin Wolf     int num_requests;
436640b4f539SKevin Wolf     int num_callbacks;
436740b4f539SKevin Wolf     struct {
4368097310b5SMarkus Armbruster         BlockCompletionFunc *cb;
436940b4f539SKevin Wolf         void *opaque;
437040b4f539SKevin Wolf         QEMUIOVector *free_qiov;
437140b4f539SKevin Wolf     } callbacks[];
437240b4f539SKevin Wolf } MultiwriteCB;
437340b4f539SKevin Wolf 
437440b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
437540b4f539SKevin Wolf {
437640b4f539SKevin Wolf     int i;
437740b4f539SKevin Wolf 
437840b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
437940b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
43801e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
43811e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
43821e1ea48dSStefan Hajnoczi         }
43837267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
438440b4f539SKevin Wolf     }
438540b4f539SKevin Wolf }
438640b4f539SKevin Wolf 
438740b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
438840b4f539SKevin Wolf {
438940b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
439040b4f539SKevin Wolf 
43916d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
43926d519a5fSStefan Hajnoczi 
4393cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
439440b4f539SKevin Wolf         mcb->error = ret;
439540b4f539SKevin Wolf     }
439640b4f539SKevin Wolf 
439740b4f539SKevin Wolf     mcb->num_requests--;
439840b4f539SKevin Wolf     if (mcb->num_requests == 0) {
439940b4f539SKevin Wolf         multiwrite_user_cb(mcb);
44007267c094SAnthony Liguori         g_free(mcb);
440140b4f539SKevin Wolf     }
440240b4f539SKevin Wolf }
440340b4f539SKevin Wolf 
440440b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
440540b4f539SKevin Wolf {
440677be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
440777be4366SChristoph Hellwig 
440877be4366SChristoph Hellwig     /*
440977be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
441077be4366SChristoph Hellwig      * here as that could overflow the return value.
441177be4366SChristoph Hellwig      */
441277be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
441377be4366SChristoph Hellwig         return 1;
441477be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
441577be4366SChristoph Hellwig         return -1;
441677be4366SChristoph Hellwig     } else {
441777be4366SChristoph Hellwig         return 0;
441877be4366SChristoph Hellwig     }
441940b4f539SKevin Wolf }
442040b4f539SKevin Wolf 
442140b4f539SKevin Wolf /*
442240b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
442340b4f539SKevin Wolf  * requests that remain after merging.
442440b4f539SKevin Wolf  */
442540b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
442640b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
442740b4f539SKevin Wolf {
442840b4f539SKevin Wolf     int i, outidx;
442940b4f539SKevin Wolf 
443040b4f539SKevin Wolf     // Sort requests by start sector
443140b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
443240b4f539SKevin Wolf 
443340b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
443440b4f539SKevin Wolf     // filling up gaps with zero sectors.
443540b4f539SKevin Wolf     outidx = 0;
443640b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
443740b4f539SKevin Wolf         int merge = 0;
443840b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
443940b4f539SKevin Wolf 
4440b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
444140b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
444240b4f539SKevin Wolf             merge = 1;
444340b4f539SKevin Wolf         }
444440b4f539SKevin Wolf 
4445e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4446e2a305fbSChristoph Hellwig             merge = 0;
4447e2a305fbSChristoph Hellwig         }
4448e2a305fbSChristoph Hellwig 
44496c5a42acSPeter Lieven         if (bs->bl.max_transfer_length && reqs[outidx].nb_sectors +
44506c5a42acSPeter Lieven             reqs[i].nb_sectors > bs->bl.max_transfer_length) {
44516c5a42acSPeter Lieven             merge = 0;
44526c5a42acSPeter Lieven         }
44536c5a42acSPeter Lieven 
445440b4f539SKevin Wolf         if (merge) {
445540b4f539SKevin Wolf             size_t size;
44567267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
445740b4f539SKevin Wolf             qemu_iovec_init(qiov,
445840b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
445940b4f539SKevin Wolf 
446040b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
446140b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
446240b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
44631b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
446440b4f539SKevin Wolf 
4465b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4466b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
446740b4f539SKevin Wolf 
446840b4f539SKevin Wolf             // Add the second request
44691b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
447040b4f539SKevin Wolf 
4471391827ebSStefan Hajnoczi             // Add tail of first request, if necessary
4472391827ebSStefan Hajnoczi             if (qiov->size < reqs[outidx].qiov->size) {
4473391827ebSStefan Hajnoczi                 qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size,
4474391827ebSStefan Hajnoczi                                   reqs[outidx].qiov->size - qiov->size);
4475391827ebSStefan Hajnoczi             }
4476391827ebSStefan Hajnoczi 
4477cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
447840b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
447940b4f539SKevin Wolf 
448040b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
448140b4f539SKevin Wolf         } else {
448240b4f539SKevin Wolf             outidx++;
448340b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
448440b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
448540b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
448640b4f539SKevin Wolf         }
448740b4f539SKevin Wolf     }
448840b4f539SKevin Wolf 
448940b4f539SKevin Wolf     return outidx + 1;
449040b4f539SKevin Wolf }
449140b4f539SKevin Wolf 
449240b4f539SKevin Wolf /*
449340b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
449440b4f539SKevin Wolf  *
449540b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
449640b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
449740b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
449840b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
449940b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
450040b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
450140b4f539SKevin Wolf  *
450240b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
450340b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
450440b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
450540b4f539SKevin Wolf  */
450640b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
450740b4f539SKevin Wolf {
450840b4f539SKevin Wolf     MultiwriteCB *mcb;
450940b4f539SKevin Wolf     int i;
451040b4f539SKevin Wolf 
4511301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4512301db7c2SRyan Harper     if (bs->drv == NULL) {
4513301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4514301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4515301db7c2SRyan Harper         }
4516301db7c2SRyan Harper         return -1;
4517301db7c2SRyan Harper     }
4518301db7c2SRyan Harper 
451940b4f539SKevin Wolf     if (num_reqs == 0) {
452040b4f539SKevin Wolf         return 0;
452140b4f539SKevin Wolf     }
452240b4f539SKevin Wolf 
452340b4f539SKevin Wolf     // Create MultiwriteCB structure
45247267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
452540b4f539SKevin Wolf     mcb->num_requests = 0;
452640b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
452740b4f539SKevin Wolf 
452840b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
452940b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
453040b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
453140b4f539SKevin Wolf     }
453240b4f539SKevin Wolf 
453340b4f539SKevin Wolf     // Check for mergable requests
453440b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
453540b4f539SKevin Wolf 
45366d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
45376d519a5fSStefan Hajnoczi 
4538df9309fbSPaolo Bonzini     /* Run the aio requests. */
4539df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
454040b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4541d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4542d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4543d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4544d20d9b7cSPaolo Bonzini                               true);
454540b4f539SKevin Wolf     }
454640b4f539SKevin Wolf 
454740b4f539SKevin Wolf     return 0;
454840b4f539SKevin Wolf }
454940b4f539SKevin Wolf 
45507c84b1b8SMarkus Armbruster void bdrv_aio_cancel(BlockAIOCB *acb)
455183f64091Sbellard {
455202c50efeSFam Zheng     qemu_aio_ref(acb);
455302c50efeSFam Zheng     bdrv_aio_cancel_async(acb);
455402c50efeSFam Zheng     while (acb->refcnt > 1) {
455502c50efeSFam Zheng         if (acb->aiocb_info->get_aio_context) {
455602c50efeSFam Zheng             aio_poll(acb->aiocb_info->get_aio_context(acb), true);
455702c50efeSFam Zheng         } else if (acb->bs) {
455802c50efeSFam Zheng             aio_poll(bdrv_get_aio_context(acb->bs), true);
455902c50efeSFam Zheng         } else {
456002c50efeSFam Zheng             abort();
456102c50efeSFam Zheng         }
456202c50efeSFam Zheng     }
45638007429aSFam Zheng     qemu_aio_unref(acb);
456402c50efeSFam Zheng }
456502c50efeSFam Zheng 
456602c50efeSFam Zheng /* Async version of aio cancel. The caller is not blocked if the acb implements
456702c50efeSFam Zheng  * cancel_async, otherwise we do nothing and let the request normally complete.
456802c50efeSFam Zheng  * In either case the completion callback must be called. */
45697c84b1b8SMarkus Armbruster void bdrv_aio_cancel_async(BlockAIOCB *acb)
457002c50efeSFam Zheng {
457102c50efeSFam Zheng     if (acb->aiocb_info->cancel_async) {
457202c50efeSFam Zheng         acb->aiocb_info->cancel_async(acb);
457302c50efeSFam Zheng     }
457483f64091Sbellard }
457583f64091Sbellard 
457683f64091Sbellard /**************************************************************/
457783f64091Sbellard /* async block device emulation */
457883f64091Sbellard 
45797c84b1b8SMarkus Armbruster typedef struct BlockAIOCBSync {
45807c84b1b8SMarkus Armbruster     BlockAIOCB common;
4581c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4582c16b5a2cSChristoph Hellwig     int ret;
4583c16b5a2cSChristoph Hellwig     /* vector translation state */
4584c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4585c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4586c16b5a2cSChristoph Hellwig     int is_write;
45877c84b1b8SMarkus Armbruster } BlockAIOCBSync;
4588c16b5a2cSChristoph Hellwig 
4589d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
45907c84b1b8SMarkus Armbruster     .aiocb_size         = sizeof(BlockAIOCBSync),
4591c16b5a2cSChristoph Hellwig };
4592c16b5a2cSChristoph Hellwig 
459383f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4594beac80cdSbellard {
45957c84b1b8SMarkus Armbruster     BlockAIOCBSync *acb = opaque;
4596f141eafeSaliguori 
4597857d4f46SKevin Wolf     if (!acb->is_write && acb->ret >= 0) {
459803396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4599857d4f46SKevin Wolf     }
4600ceb42de8Saliguori     qemu_vfree(acb->bounce);
4601ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
46026a7ad299SDor Laor     qemu_bh_delete(acb->bh);
460336afc451SAvi Kivity     acb->bh = NULL;
46048007429aSFam Zheng     qemu_aio_unref(acb);
4605beac80cdSbellard }
4606beac80cdSbellard 
46077c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4608f141eafeSaliguori                                       int64_t sector_num,
4609f141eafeSaliguori                                       QEMUIOVector *qiov,
4610f141eafeSaliguori                                       int nb_sectors,
4611097310b5SMarkus Armbruster                                       BlockCompletionFunc *cb,
4612f141eafeSaliguori                                       void *opaque,
4613f141eafeSaliguori                                       int is_write)
4614f141eafeSaliguori 
4615ea2384d3Sbellard {
46167c84b1b8SMarkus Armbruster     BlockAIOCBSync *acb;
461783f64091Sbellard 
4618d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4619f141eafeSaliguori     acb->is_write = is_write;
4620f141eafeSaliguori     acb->qiov = qiov;
4621857d4f46SKevin Wolf     acb->bounce = qemu_try_blockalign(bs, qiov->size);
46222572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb);
4623f141eafeSaliguori 
4624857d4f46SKevin Wolf     if (acb->bounce == NULL) {
4625857d4f46SKevin Wolf         acb->ret = -ENOMEM;
4626857d4f46SKevin Wolf     } else if (is_write) {
4627d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
46281ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4629f141eafeSaliguori     } else {
46301ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4631f141eafeSaliguori     }
4632f141eafeSaliguori 
4633ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4634f141eafeSaliguori 
4635ce1a14dcSpbrook     return &acb->common;
46367a6cba61Spbrook }
46377a6cba61Spbrook 
46387c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4639f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4640097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque)
464183f64091Sbellard {
4642f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
464383f64091Sbellard }
464483f64091Sbellard 
46457c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4646f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4647097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque)
4648f141eafeSaliguori {
4649f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4650f141eafeSaliguori }
4651f141eafeSaliguori 
465268485420SKevin Wolf 
46537c84b1b8SMarkus Armbruster typedef struct BlockAIOCBCoroutine {
46547c84b1b8SMarkus Armbruster     BlockAIOCB common;
465568485420SKevin Wolf     BlockRequest req;
465668485420SKevin Wolf     bool is_write;
4657d318aea9SKevin Wolf     bool *done;
465868485420SKevin Wolf     QEMUBH* bh;
46597c84b1b8SMarkus Armbruster } BlockAIOCBCoroutine;
466068485420SKevin Wolf 
4661d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
46627c84b1b8SMarkus Armbruster     .aiocb_size         = sizeof(BlockAIOCBCoroutine),
466368485420SKevin Wolf };
466468485420SKevin Wolf 
466535246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
466668485420SKevin Wolf {
46677c84b1b8SMarkus Armbruster     BlockAIOCBCoroutine *acb = opaque;
466868485420SKevin Wolf 
466968485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4670d318aea9SKevin Wolf 
467168485420SKevin Wolf     qemu_bh_delete(acb->bh);
46728007429aSFam Zheng     qemu_aio_unref(acb);
467368485420SKevin Wolf }
467468485420SKevin Wolf 
4675b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4676b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4677b2a61371SStefan Hajnoczi {
46787c84b1b8SMarkus Armbruster     BlockAIOCBCoroutine *acb = opaque;
4679b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4680b2a61371SStefan Hajnoczi 
4681b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4682b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4683d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4684b2a61371SStefan Hajnoczi     } else {
4685b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4686d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4687b2a61371SStefan Hajnoczi     }
4688b2a61371SStefan Hajnoczi 
46892572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
4690b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4691b2a61371SStefan Hajnoczi }
4692b2a61371SStefan Hajnoczi 
46937c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
469468485420SKevin Wolf                                          int64_t sector_num,
469568485420SKevin Wolf                                          QEMUIOVector *qiov,
469668485420SKevin Wolf                                          int nb_sectors,
4697d20d9b7cSPaolo Bonzini                                          BdrvRequestFlags flags,
4698097310b5SMarkus Armbruster                                          BlockCompletionFunc *cb,
469968485420SKevin Wolf                                          void *opaque,
47008c5873d6SStefan Hajnoczi                                          bool is_write)
470168485420SKevin Wolf {
470268485420SKevin Wolf     Coroutine *co;
47037c84b1b8SMarkus Armbruster     BlockAIOCBCoroutine *acb;
470468485420SKevin Wolf 
4705d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
470668485420SKevin Wolf     acb->req.sector = sector_num;
470768485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
470868485420SKevin Wolf     acb->req.qiov = qiov;
4709d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
471068485420SKevin Wolf     acb->is_write = is_write;
471168485420SKevin Wolf 
47128c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
471368485420SKevin Wolf     qemu_coroutine_enter(co, acb);
471468485420SKevin Wolf 
471568485420SKevin Wolf     return &acb->common;
471668485420SKevin Wolf }
471768485420SKevin Wolf 
471807f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4719b2e12bc6SChristoph Hellwig {
47207c84b1b8SMarkus Armbruster     BlockAIOCBCoroutine *acb = opaque;
472107f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4722b2e12bc6SChristoph Hellwig 
472307f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
47242572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
4725b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4726b2e12bc6SChristoph Hellwig }
4727b2e12bc6SChristoph Hellwig 
47287c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4729097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque)
4730016f5cf6SAlexander Graf {
473107f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4732016f5cf6SAlexander Graf 
473307f07615SPaolo Bonzini     Coroutine *co;
47347c84b1b8SMarkus Armbruster     BlockAIOCBCoroutine *acb;
4735016f5cf6SAlexander Graf 
4736d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4737d318aea9SKevin Wolf 
473807f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
473907f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4740016f5cf6SAlexander Graf 
4741016f5cf6SAlexander Graf     return &acb->common;
4742016f5cf6SAlexander Graf }
4743016f5cf6SAlexander Graf 
47444265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
47454265d620SPaolo Bonzini {
47467c84b1b8SMarkus Armbruster     BlockAIOCBCoroutine *acb = opaque;
47474265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
47484265d620SPaolo Bonzini 
47494265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
47502572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
47514265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
47524265d620SPaolo Bonzini }
47534265d620SPaolo Bonzini 
47547c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,
47554265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
4756097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque)
47574265d620SPaolo Bonzini {
47584265d620SPaolo Bonzini     Coroutine *co;
47597c84b1b8SMarkus Armbruster     BlockAIOCBCoroutine *acb;
47604265d620SPaolo Bonzini 
47614265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
47624265d620SPaolo Bonzini 
4763d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
47644265d620SPaolo Bonzini     acb->req.sector = sector_num;
47654265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
47664265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
47674265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
47684265d620SPaolo Bonzini 
47694265d620SPaolo Bonzini     return &acb->common;
47704265d620SPaolo Bonzini }
47714265d620SPaolo Bonzini 
4772ea2384d3Sbellard void bdrv_init(void)
4773ea2384d3Sbellard {
47745efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4775ea2384d3Sbellard }
4776ce1a14dcSpbrook 
4777eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4778eb852011SMarkus Armbruster {
4779eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4780eb852011SMarkus Armbruster     bdrv_init();
4781eb852011SMarkus Armbruster }
4782eb852011SMarkus Armbruster 
4783d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
4784097310b5SMarkus Armbruster                    BlockCompletionFunc *cb, void *opaque)
47856bbff9a0Saliguori {
47867c84b1b8SMarkus Armbruster     BlockAIOCB *acb;
4787ce1a14dcSpbrook 
4788d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4789d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4790ce1a14dcSpbrook     acb->bs = bs;
4791ce1a14dcSpbrook     acb->cb = cb;
4792ce1a14dcSpbrook     acb->opaque = opaque;
4793f197fe2bSFam Zheng     acb->refcnt = 1;
4794ce1a14dcSpbrook     return acb;
4795ce1a14dcSpbrook }
4796ce1a14dcSpbrook 
4797f197fe2bSFam Zheng void qemu_aio_ref(void *p)
4798f197fe2bSFam Zheng {
47997c84b1b8SMarkus Armbruster     BlockAIOCB *acb = p;
4800f197fe2bSFam Zheng     acb->refcnt++;
4801f197fe2bSFam Zheng }
4802f197fe2bSFam Zheng 
48038007429aSFam Zheng void qemu_aio_unref(void *p)
4804ce1a14dcSpbrook {
48057c84b1b8SMarkus Armbruster     BlockAIOCB *acb = p;
4806f197fe2bSFam Zheng     assert(acb->refcnt > 0);
4807f197fe2bSFam Zheng     if (--acb->refcnt == 0) {
4808d7331bedSStefan Hajnoczi         g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4809ce1a14dcSpbrook     }
4810f197fe2bSFam Zheng }
481119cb3738Sbellard 
481219cb3738Sbellard /**************************************************************/
4813f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4814f9f05dc5SKevin Wolf 
4815f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4816f9f05dc5SKevin Wolf     Coroutine *coroutine;
4817f9f05dc5SKevin Wolf     int ret;
4818f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4819f9f05dc5SKevin Wolf 
4820f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4821f9f05dc5SKevin Wolf {
4822f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4823f9f05dc5SKevin Wolf 
4824f9f05dc5SKevin Wolf     co->ret = ret;
4825f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4826f9f05dc5SKevin Wolf }
4827f9f05dc5SKevin Wolf 
4828f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4829f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4830f9f05dc5SKevin Wolf                                       bool is_write)
4831f9f05dc5SKevin Wolf {
4832f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4833f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4834f9f05dc5SKevin Wolf     };
48357c84b1b8SMarkus Armbruster     BlockAIOCB *acb;
4836f9f05dc5SKevin Wolf 
4837f9f05dc5SKevin Wolf     if (is_write) {
4838a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4839f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4840f9f05dc5SKevin Wolf     } else {
4841a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4842f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4843f9f05dc5SKevin Wolf     }
4844f9f05dc5SKevin Wolf 
484559370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4846f9f05dc5SKevin Wolf     if (!acb) {
4847f9f05dc5SKevin Wolf         return -EIO;
4848f9f05dc5SKevin Wolf     }
4849f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4850f9f05dc5SKevin Wolf 
4851f9f05dc5SKevin Wolf     return co.ret;
4852f9f05dc5SKevin Wolf }
4853f9f05dc5SKevin Wolf 
4854f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4855f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4856f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4857f9f05dc5SKevin Wolf {
4858f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4859f9f05dc5SKevin Wolf }
4860f9f05dc5SKevin Wolf 
4861f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4862f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4863f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4864f9f05dc5SKevin Wolf {
4865f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4866f9f05dc5SKevin Wolf }
4867f9f05dc5SKevin Wolf 
486807f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4869e7a8a783SKevin Wolf {
487007f07615SPaolo Bonzini     RwCo *rwco = opaque;
487107f07615SPaolo Bonzini 
487207f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
487307f07615SPaolo Bonzini }
487407f07615SPaolo Bonzini 
487507f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
487607f07615SPaolo Bonzini {
4877eb489bb1SKevin Wolf     int ret;
4878eb489bb1SKevin Wolf 
487929cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
488007f07615SPaolo Bonzini         return 0;
4881eb489bb1SKevin Wolf     }
4882eb489bb1SKevin Wolf 
4883ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4884bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4885eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4886eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4887eb489bb1SKevin Wolf         if (ret < 0) {
4888eb489bb1SKevin Wolf             return ret;
4889eb489bb1SKevin Wolf         }
4890eb489bb1SKevin Wolf     }
4891eb489bb1SKevin Wolf 
4892ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4893ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4894d4c82329SKevin Wolf         goto flush_parent;
4895ca716364SKevin Wolf     }
4896ca716364SKevin Wolf 
4897bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4898eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
489929cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
490007f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
49017c84b1b8SMarkus Armbruster         BlockAIOCB *acb;
4902e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4903e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4904e7a8a783SKevin Wolf         };
4905e7a8a783SKevin Wolf 
490607f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
490707f07615SPaolo Bonzini         if (acb == NULL) {
490829cdb251SPaolo Bonzini             ret = -EIO;
490907f07615SPaolo Bonzini         } else {
4910e7a8a783SKevin Wolf             qemu_coroutine_yield();
491129cdb251SPaolo Bonzini             ret = co.ret;
4912e7a8a783SKevin Wolf         }
491307f07615SPaolo Bonzini     } else {
491407f07615SPaolo Bonzini         /*
491507f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
491607f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
491707f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
491807f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
491907f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
492007f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
492107f07615SPaolo Bonzini          * mode.
492207f07615SPaolo Bonzini          *
492307f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
492407f07615SPaolo Bonzini          */
492529cdb251SPaolo Bonzini         ret = 0;
492607f07615SPaolo Bonzini     }
492729cdb251SPaolo Bonzini     if (ret < 0) {
492829cdb251SPaolo Bonzini         return ret;
492929cdb251SPaolo Bonzini     }
493029cdb251SPaolo Bonzini 
493129cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
493229cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
493329cdb251SPaolo Bonzini      */
4934d4c82329SKevin Wolf flush_parent:
493529cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
493607f07615SPaolo Bonzini }
493707f07615SPaolo Bonzini 
49385a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
49390f15423cSAnthony Liguori {
49405a8a30dbSKevin Wolf     Error *local_err = NULL;
49415a8a30dbSKevin Wolf     int ret;
49425a8a30dbSKevin Wolf 
49433456a8d1SKevin Wolf     if (!bs->drv)  {
49443456a8d1SKevin Wolf         return;
49450f15423cSAnthony Liguori     }
49463456a8d1SKevin Wolf 
49477ea2d269SAlexey Kardashevskiy     if (!(bs->open_flags & BDRV_O_INCOMING)) {
49487ea2d269SAlexey Kardashevskiy         return;
49497ea2d269SAlexey Kardashevskiy     }
49507ea2d269SAlexey Kardashevskiy     bs->open_flags &= ~BDRV_O_INCOMING;
49517ea2d269SAlexey Kardashevskiy 
49523456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
49535a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
49543456a8d1SKevin Wolf     } else if (bs->file) {
49555a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs->file, &local_err);
49565a8a30dbSKevin Wolf     }
49575a8a30dbSKevin Wolf     if (local_err) {
49585a8a30dbSKevin Wolf         error_propagate(errp, local_err);
49595a8a30dbSKevin Wolf         return;
49603456a8d1SKevin Wolf     }
49613456a8d1SKevin Wolf 
49625a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
49635a8a30dbSKevin Wolf     if (ret < 0) {
49645a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
49655a8a30dbSKevin Wolf         return;
49665a8a30dbSKevin Wolf     }
49670f15423cSAnthony Liguori }
49680f15423cSAnthony Liguori 
49695a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
49700f15423cSAnthony Liguori {
49710f15423cSAnthony Liguori     BlockDriverState *bs;
49725a8a30dbSKevin Wolf     Error *local_err = NULL;
49730f15423cSAnthony Liguori 
4974dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
4975ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
4976ed78cda3SStefan Hajnoczi 
4977ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
49785a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
4979ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
49805a8a30dbSKevin Wolf         if (local_err) {
49815a8a30dbSKevin Wolf             error_propagate(errp, local_err);
49825a8a30dbSKevin Wolf             return;
49835a8a30dbSKevin Wolf         }
49840f15423cSAnthony Liguori     }
49850f15423cSAnthony Liguori }
49860f15423cSAnthony Liguori 
498707f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
498807f07615SPaolo Bonzini {
498907f07615SPaolo Bonzini     Coroutine *co;
499007f07615SPaolo Bonzini     RwCo rwco = {
499107f07615SPaolo Bonzini         .bs = bs,
499207f07615SPaolo Bonzini         .ret = NOT_DONE,
499307f07615SPaolo Bonzini     };
499407f07615SPaolo Bonzini 
499507f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
499607f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
499707f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
499807f07615SPaolo Bonzini     } else {
49992572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
50002572b37aSStefan Hajnoczi 
500107f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
500207f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
500307f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
50042572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
500507f07615SPaolo Bonzini         }
500607f07615SPaolo Bonzini     }
500707f07615SPaolo Bonzini 
500807f07615SPaolo Bonzini     return rwco.ret;
500907f07615SPaolo Bonzini }
5010e7a8a783SKevin Wolf 
5011775aa8b6SKevin Wolf typedef struct DiscardCo {
5012775aa8b6SKevin Wolf     BlockDriverState *bs;
5013775aa8b6SKevin Wolf     int64_t sector_num;
5014775aa8b6SKevin Wolf     int nb_sectors;
5015775aa8b6SKevin Wolf     int ret;
5016775aa8b6SKevin Wolf } DiscardCo;
50174265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
50184265d620SPaolo Bonzini {
5019775aa8b6SKevin Wolf     DiscardCo *rwco = opaque;
50204265d620SPaolo Bonzini 
50214265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
50224265d620SPaolo Bonzini }
50234265d620SPaolo Bonzini 
50246f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
50256f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
50266f14da52SPeter Lieven  */
50276f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
50286f14da52SPeter Lieven 
50294265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
50304265d620SPaolo Bonzini                                  int nb_sectors)
50314265d620SPaolo Bonzini {
5032d51e9fe5SPaolo Bonzini     int max_discard;
5033d51e9fe5SPaolo Bonzini 
50344265d620SPaolo Bonzini     if (!bs->drv) {
50354265d620SPaolo Bonzini         return -ENOMEDIUM;
50364265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
50374265d620SPaolo Bonzini         return -EIO;
50384265d620SPaolo Bonzini     } else if (bs->read_only) {
50394265d620SPaolo Bonzini         return -EROFS;
5040df702c9bSPaolo Bonzini     }
5041df702c9bSPaolo Bonzini 
50428f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
5043df702c9bSPaolo Bonzini 
50449e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
50459e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
50469e8f1835SPaolo Bonzini         return 0;
50479e8f1835SPaolo Bonzini     }
50489e8f1835SPaolo Bonzini 
5049d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
5050d51e9fe5SPaolo Bonzini         return 0;
5051d51e9fe5SPaolo Bonzini     }
50526f14da52SPeter Lieven 
5053d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
50546f14da52SPeter Lieven     while (nb_sectors > 0) {
50556f14da52SPeter Lieven         int ret;
50566f14da52SPeter Lieven         int num = nb_sectors;
50576f14da52SPeter Lieven 
50586f14da52SPeter Lieven         /* align request */
50596f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
50606f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
50616f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
50626f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
50636f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
50646f14da52SPeter Lieven             }
50656f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
50666f14da52SPeter Lieven         }
50676f14da52SPeter Lieven 
50686f14da52SPeter Lieven         /* limit request size */
50696f14da52SPeter Lieven         if (num > max_discard) {
50706f14da52SPeter Lieven             num = max_discard;
50716f14da52SPeter Lieven         }
50726f14da52SPeter Lieven 
5073d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
50746f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
5075d51e9fe5SPaolo Bonzini         } else {
50767c84b1b8SMarkus Armbruster             BlockAIOCB *acb;
50774265d620SPaolo Bonzini             CoroutineIOCompletion co = {
50784265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
50794265d620SPaolo Bonzini             };
50804265d620SPaolo Bonzini 
50814265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
50824265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
50834265d620SPaolo Bonzini             if (acb == NULL) {
50844265d620SPaolo Bonzini                 return -EIO;
50854265d620SPaolo Bonzini             } else {
50864265d620SPaolo Bonzini                 qemu_coroutine_yield();
5087d51e9fe5SPaolo Bonzini                 ret = co.ret;
50884265d620SPaolo Bonzini             }
5089d51e9fe5SPaolo Bonzini         }
50907ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
5091d51e9fe5SPaolo Bonzini             return ret;
5092d51e9fe5SPaolo Bonzini         }
5093d51e9fe5SPaolo Bonzini 
5094d51e9fe5SPaolo Bonzini         sector_num += num;
5095d51e9fe5SPaolo Bonzini         nb_sectors -= num;
5096d51e9fe5SPaolo Bonzini     }
50974265d620SPaolo Bonzini     return 0;
50984265d620SPaolo Bonzini }
50994265d620SPaolo Bonzini 
51004265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
51014265d620SPaolo Bonzini {
51024265d620SPaolo Bonzini     Coroutine *co;
5103775aa8b6SKevin Wolf     DiscardCo rwco = {
51044265d620SPaolo Bonzini         .bs = bs,
51054265d620SPaolo Bonzini         .sector_num = sector_num,
51064265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
51074265d620SPaolo Bonzini         .ret = NOT_DONE,
51084265d620SPaolo Bonzini     };
51094265d620SPaolo Bonzini 
51104265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
51114265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
51124265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
51134265d620SPaolo Bonzini     } else {
51142572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
51152572b37aSStefan Hajnoczi 
51164265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
51174265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
51184265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
51192572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
51204265d620SPaolo Bonzini         }
51214265d620SPaolo Bonzini     }
51224265d620SPaolo Bonzini 
51234265d620SPaolo Bonzini     return rwco.ret;
51244265d620SPaolo Bonzini }
51254265d620SPaolo Bonzini 
5126f9f05dc5SKevin Wolf /**************************************************************/
512719cb3738Sbellard /* removable device support */
512819cb3738Sbellard 
512919cb3738Sbellard /**
513019cb3738Sbellard  * Return TRUE if the media is present
513119cb3738Sbellard  */
513219cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
513319cb3738Sbellard {
513419cb3738Sbellard     BlockDriver *drv = bs->drv;
5135a1aff5bfSMarkus Armbruster 
513619cb3738Sbellard     if (!drv)
513719cb3738Sbellard         return 0;
513819cb3738Sbellard     if (!drv->bdrv_is_inserted)
5139a1aff5bfSMarkus Armbruster         return 1;
5140a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
514119cb3738Sbellard }
514219cb3738Sbellard 
514319cb3738Sbellard /**
51448e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
51458e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
514619cb3738Sbellard  */
514719cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
514819cb3738Sbellard {
514919cb3738Sbellard     BlockDriver *drv = bs->drv;
515019cb3738Sbellard 
51518e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
51528e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
51538e49ca46SMarkus Armbruster     }
51548e49ca46SMarkus Armbruster     return -ENOTSUP;
515519cb3738Sbellard }
515619cb3738Sbellard 
515719cb3738Sbellard /**
515819cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
515919cb3738Sbellard  */
5160f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
516119cb3738Sbellard {
516219cb3738Sbellard     BlockDriver *drv = bs->drv;
5163bfb197e0SMarkus Armbruster     const char *device_name;
516419cb3738Sbellard 
5165822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
5166822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
516719cb3738Sbellard     }
51686f382ed2SLuiz Capitulino 
5169bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
5170bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
5171bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
5172a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
51736f382ed2SLuiz Capitulino     }
517419cb3738Sbellard }
517519cb3738Sbellard 
517619cb3738Sbellard /**
517719cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
517819cb3738Sbellard  * to eject it manually).
517919cb3738Sbellard  */
5180025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
518119cb3738Sbellard {
518219cb3738Sbellard     BlockDriver *drv = bs->drv;
518319cb3738Sbellard 
5184025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
5185b8c6d095SStefan Hajnoczi 
5186025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
5187025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
518819cb3738Sbellard     }
518919cb3738Sbellard }
5190985a03b0Sths 
5191985a03b0Sths /* needed for generic scsi interface */
5192985a03b0Sths 
5193985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
5194985a03b0Sths {
5195985a03b0Sths     BlockDriver *drv = bs->drv;
5196985a03b0Sths 
5197985a03b0Sths     if (drv && drv->bdrv_ioctl)
5198985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
5199985a03b0Sths     return -ENOTSUP;
5200985a03b0Sths }
52017d780669Saliguori 
52027c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
5203221f715dSaliguori         unsigned long int req, void *buf,
5204097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque)
52057d780669Saliguori {
5206221f715dSaliguori     BlockDriver *drv = bs->drv;
52077d780669Saliguori 
5208221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
5209221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
5210221f715dSaliguori     return NULL;
52117d780669Saliguori }
5212e268ca52Saliguori 
52131b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
52147b6f9300SMarkus Armbruster {
52151b7fd729SPaolo Bonzini     bs->guest_block_size = align;
52167b6f9300SMarkus Armbruster }
52177cd1e32aSlirans@il.ibm.com 
5218e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
5219e268ca52Saliguori {
5220339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
5221e268ca52Saliguori }
52227cd1e32aSlirans@il.ibm.com 
52239ebd8448SMax Reitz void *qemu_blockalign0(BlockDriverState *bs, size_t size)
52249ebd8448SMax Reitz {
52259ebd8448SMax Reitz     return memset(qemu_blockalign(bs, size), 0, size);
52269ebd8448SMax Reitz }
52279ebd8448SMax Reitz 
52287d2a35ccSKevin Wolf void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
52297d2a35ccSKevin Wolf {
52307d2a35ccSKevin Wolf     size_t align = bdrv_opt_mem_align(bs);
52317d2a35ccSKevin Wolf 
52327d2a35ccSKevin Wolf     /* Ensure that NULL is never returned on success */
52337d2a35ccSKevin Wolf     assert(align > 0);
52347d2a35ccSKevin Wolf     if (size == 0) {
52357d2a35ccSKevin Wolf         size = align;
52367d2a35ccSKevin Wolf     }
52377d2a35ccSKevin Wolf 
52387d2a35ccSKevin Wolf     return qemu_try_memalign(align, size);
52397d2a35ccSKevin Wolf }
52407d2a35ccSKevin Wolf 
52419ebd8448SMax Reitz void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
52429ebd8448SMax Reitz {
52439ebd8448SMax Reitz     void *mem = qemu_try_blockalign(bs, size);
52449ebd8448SMax Reitz 
52459ebd8448SMax Reitz     if (mem) {
52469ebd8448SMax Reitz         memset(mem, 0, size);
52479ebd8448SMax Reitz     }
52489ebd8448SMax Reitz 
52499ebd8448SMax Reitz     return mem;
52509ebd8448SMax Reitz }
52519ebd8448SMax Reitz 
5252c53b1c51SStefan Hajnoczi /*
5253c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
5254c53b1c51SStefan Hajnoczi  */
5255c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5256c53b1c51SStefan Hajnoczi {
5257c53b1c51SStefan Hajnoczi     int i;
5258339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
5259c53b1c51SStefan Hajnoczi 
5260c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
5261339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
5262c53b1c51SStefan Hajnoczi             return false;
5263c53b1c51SStefan Hajnoczi         }
5264339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
52651ff735bdSKevin Wolf             return false;
52661ff735bdSKevin Wolf         }
5267c53b1c51SStefan Hajnoczi     }
5268c53b1c51SStefan Hajnoczi 
5269c53b1c51SStefan Hajnoczi     return true;
5270c53b1c51SStefan Hajnoczi }
5271c53b1c51SStefan Hajnoczi 
5272b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity,
5273b8afb520SFam Zheng                                           Error **errp)
52747cd1e32aSlirans@il.ibm.com {
52757cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
5276e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5277a55eb92cSJan Kiszka 
527850717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
527950717e94SPaolo Bonzini 
528050717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
5281e4654d2dSFam Zheng     assert(granularity);
528257322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
5283b8afb520SFam Zheng     if (bitmap_size < 0) {
5284b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
5285b8afb520SFam Zheng         errno = -bitmap_size;
5286b8afb520SFam Zheng         return NULL;
5287b8afb520SFam Zheng     }
52885839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
5289e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5290e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5291e4654d2dSFam Zheng     return bitmap;
5292e4654d2dSFam Zheng }
5293e4654d2dSFam Zheng 
5294e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5295e4654d2dSFam Zheng {
5296e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
5297e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5298e4654d2dSFam Zheng         if (bm == bitmap) {
5299e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
5300e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
5301e4654d2dSFam Zheng             g_free(bitmap);
5302e4654d2dSFam Zheng             return;
53037cd1e32aSlirans@il.ibm.com         }
53047cd1e32aSlirans@il.ibm.com     }
53057cd1e32aSlirans@il.ibm.com }
53067cd1e32aSlirans@il.ibm.com 
530721b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
530821b56835SFam Zheng {
530921b56835SFam Zheng     BdrvDirtyBitmap *bm;
531021b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
531121b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
531221b56835SFam Zheng 
531321b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
53145839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
53155839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
531621b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
531721b56835SFam Zheng         info->granularity =
531821b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
531921b56835SFam Zheng         entry->value = info;
532021b56835SFam Zheng         *plist = entry;
532121b56835SFam Zheng         plist = &entry->next;
532221b56835SFam Zheng     }
532321b56835SFam Zheng 
532421b56835SFam Zheng     return list;
532521b56835SFam Zheng }
532621b56835SFam Zheng 
5327e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
53287cd1e32aSlirans@il.ibm.com {
5329e4654d2dSFam Zheng     if (bitmap) {
5330e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
53317cd1e32aSlirans@il.ibm.com     } else {
53327cd1e32aSlirans@il.ibm.com         return 0;
53337cd1e32aSlirans@il.ibm.com     }
53347cd1e32aSlirans@il.ibm.com }
53357cd1e32aSlirans@il.ibm.com 
5336e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
5337e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
53381755da16SPaolo Bonzini {
5339e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
53401755da16SPaolo Bonzini }
53411755da16SPaolo Bonzini 
53421755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
53431755da16SPaolo Bonzini                     int nr_sectors)
53441755da16SPaolo Bonzini {
5345e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5346e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5347e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5348e4654d2dSFam Zheng     }
53491755da16SPaolo Bonzini }
53501755da16SPaolo Bonzini 
5351e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
53527cd1e32aSlirans@il.ibm.com {
5353e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5354e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5355e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5356e4654d2dSFam Zheng     }
53577cd1e32aSlirans@il.ibm.com }
5358aaa0eb75SLiran Schour 
5359e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5360aaa0eb75SLiran Schour {
5361e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
5362aaa0eb75SLiran Schour }
5363f88e1a42SJes Sorensen 
53649fcb0251SFam Zheng /* Get a reference to bs */
53659fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
53669fcb0251SFam Zheng {
53679fcb0251SFam Zheng     bs->refcnt++;
53689fcb0251SFam Zheng }
53699fcb0251SFam Zheng 
53709fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
53719fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
53729fcb0251SFam Zheng  * deleted. */
53739fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
53749fcb0251SFam Zheng {
53759a4d5ca6SJeff Cody     if (!bs) {
53769a4d5ca6SJeff Cody         return;
53779a4d5ca6SJeff Cody     }
53789fcb0251SFam Zheng     assert(bs->refcnt > 0);
53799fcb0251SFam Zheng     if (--bs->refcnt == 0) {
53809fcb0251SFam Zheng         bdrv_delete(bs);
53819fcb0251SFam Zheng     }
53829fcb0251SFam Zheng }
53839fcb0251SFam Zheng 
5384fbe40ff7SFam Zheng struct BdrvOpBlocker {
5385fbe40ff7SFam Zheng     Error *reason;
5386fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
5387fbe40ff7SFam Zheng };
5388fbe40ff7SFam Zheng 
5389fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5390fbe40ff7SFam Zheng {
5391fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
5392fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5393fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5394fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
5395fbe40ff7SFam Zheng         if (errp) {
5396fbe40ff7SFam Zheng             error_setg(errp, "Device '%s' is busy: %s",
5397bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs),
5398bfb197e0SMarkus Armbruster                        error_get_pretty(blocker->reason));
5399fbe40ff7SFam Zheng         }
5400fbe40ff7SFam Zheng         return true;
5401fbe40ff7SFam Zheng     }
5402fbe40ff7SFam Zheng     return false;
5403fbe40ff7SFam Zheng }
5404fbe40ff7SFam Zheng 
5405fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5406fbe40ff7SFam Zheng {
5407fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
5408fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5409fbe40ff7SFam Zheng 
54105839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
5411fbe40ff7SFam Zheng     blocker->reason = reason;
5412fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5413fbe40ff7SFam Zheng }
5414fbe40ff7SFam Zheng 
5415fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5416fbe40ff7SFam Zheng {
5417fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
5418fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5419fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5420fbe40ff7SFam Zheng         if (blocker->reason == reason) {
5421fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
5422fbe40ff7SFam Zheng             g_free(blocker);
5423fbe40ff7SFam Zheng         }
5424fbe40ff7SFam Zheng     }
5425fbe40ff7SFam Zheng }
5426fbe40ff7SFam Zheng 
5427fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5428fbe40ff7SFam Zheng {
5429fbe40ff7SFam Zheng     int i;
5430fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5431fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
5432fbe40ff7SFam Zheng     }
5433fbe40ff7SFam Zheng }
5434fbe40ff7SFam Zheng 
5435fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
5436fbe40ff7SFam Zheng {
5437fbe40ff7SFam Zheng     int i;
5438fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5439fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
5440fbe40ff7SFam Zheng     }
5441fbe40ff7SFam Zheng }
5442fbe40ff7SFam Zheng 
5443fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
5444fbe40ff7SFam Zheng {
5445fbe40ff7SFam Zheng     int i;
5446fbe40ff7SFam Zheng 
5447fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5448fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
5449fbe40ff7SFam Zheng             return false;
5450fbe40ff7SFam Zheng         }
5451fbe40ff7SFam Zheng     }
5452fbe40ff7SFam Zheng     return true;
5453fbe40ff7SFam Zheng }
5454fbe40ff7SFam Zheng 
545528a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
545628a7282aSLuiz Capitulino {
5457d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
545858e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
545928a7282aSLuiz Capitulino }
546028a7282aSLuiz Capitulino 
546128a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
546228a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
546328a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
546428a7282aSLuiz Capitulino {
5465d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
546692aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
546792aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
546892aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
546928a7282aSLuiz Capitulino }
547028a7282aSLuiz Capitulino 
547128a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
547228a7282aSLuiz Capitulino {
5473d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
547428a7282aSLuiz Capitulino }
547528a7282aSLuiz Capitulino 
547628a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
547728a7282aSLuiz Capitulino {
547828a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
547958e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
54803bd293c3SPaolo Bonzini         if (bs->job) {
54813bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
54823bd293c3SPaolo Bonzini         }
548328a7282aSLuiz Capitulino     }
548428a7282aSLuiz Capitulino }
548528a7282aSLuiz Capitulino 
548628a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
548728a7282aSLuiz Capitulino {
54883e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
54893e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
549058e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
549158e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
549228a7282aSLuiz Capitulino     }
549328a7282aSLuiz Capitulino }
549428a7282aSLuiz Capitulino 
5495d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5496f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5497f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5498f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5499f88e1a42SJes Sorensen {
550083d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
550183d0521aSChunyan Liu     QemuOpts *opts = NULL;
550283d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
550383d0521aSChunyan Liu     int64_t size;
5504f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
550596df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5506cc84d90fSMax Reitz     Error *local_err = NULL;
5507f88e1a42SJes Sorensen     int ret = 0;
5508f88e1a42SJes Sorensen 
5509f88e1a42SJes Sorensen     /* Find driver and parse its options */
5510f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5511f88e1a42SJes Sorensen     if (!drv) {
551271c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5513d92ada22SLuiz Capitulino         return;
5514f88e1a42SJes Sorensen     }
5515f88e1a42SJes Sorensen 
551698289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5517f88e1a42SJes Sorensen     if (!proto_drv) {
551871c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5519d92ada22SLuiz Capitulino         return;
5520f88e1a42SJes Sorensen     }
5521f88e1a42SJes Sorensen 
5522c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
5523c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5524f88e1a42SJes Sorensen 
5525f88e1a42SJes Sorensen     /* Create parameter list with default values */
552683d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
552783d0521aSChunyan Liu     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size);
5528f88e1a42SJes Sorensen 
5529f88e1a42SJes Sorensen     /* Parse -o options */
5530f88e1a42SJes Sorensen     if (options) {
553183d0521aSChunyan Liu         if (qemu_opts_do_parse(opts, options, NULL) != 0) {
553283d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
5533f88e1a42SJes Sorensen             goto out;
5534f88e1a42SJes Sorensen         }
5535f88e1a42SJes Sorensen     }
5536f88e1a42SJes Sorensen 
5537f88e1a42SJes Sorensen     if (base_filename) {
553883d0521aSChunyan Liu         if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
553971c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
554071c79813SLuiz Capitulino                        fmt);
5541f88e1a42SJes Sorensen             goto out;
5542f88e1a42SJes Sorensen         }
5543f88e1a42SJes Sorensen     }
5544f88e1a42SJes Sorensen 
5545f88e1a42SJes Sorensen     if (base_fmt) {
554683d0521aSChunyan Liu         if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
554771c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
554871c79813SLuiz Capitulino                              "format '%s'", fmt);
5549f88e1a42SJes Sorensen             goto out;
5550f88e1a42SJes Sorensen         }
5551f88e1a42SJes Sorensen     }
5552f88e1a42SJes Sorensen 
555383d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
555483d0521aSChunyan Liu     if (backing_file) {
555583d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
555671c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
555771c79813SLuiz Capitulino                              "same filename as the backing file");
5558792da93aSJes Sorensen             goto out;
5559792da93aSJes Sorensen         }
5560792da93aSJes Sorensen     }
5561792da93aSJes Sorensen 
556283d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
556383d0521aSChunyan Liu     if (backing_fmt) {
556483d0521aSChunyan Liu         backing_drv = bdrv_find_format(backing_fmt);
556596df67d1SStefan Hajnoczi         if (!backing_drv) {
556671c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
556783d0521aSChunyan Liu                        backing_fmt);
5568f88e1a42SJes Sorensen             goto out;
5569f88e1a42SJes Sorensen         }
5570f88e1a42SJes Sorensen     }
5571f88e1a42SJes Sorensen 
5572f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5573f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
557483d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
557583d0521aSChunyan Liu     if (size == -1) {
557683d0521aSChunyan Liu         if (backing_file) {
557766f6b814SMax Reitz             BlockDriverState *bs;
557852bf1e72SMarkus Armbruster             int64_t size;
557963090dacSPaolo Bonzini             int back_flags;
558063090dacSPaolo Bonzini 
558163090dacSPaolo Bonzini             /* backing files always opened read-only */
558263090dacSPaolo Bonzini             back_flags =
558363090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5584f88e1a42SJes Sorensen 
5585f67503e5SMax Reitz             bs = NULL;
558683d0521aSChunyan Liu             ret = bdrv_open(&bs, backing_file, NULL, NULL, back_flags,
5587cc84d90fSMax Reitz                             backing_drv, &local_err);
5588f88e1a42SJes Sorensen             if (ret < 0) {
5589cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
559083d0521aSChunyan Liu                                  backing_file,
5591cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5592cc84d90fSMax Reitz                 error_free(local_err);
5593cc84d90fSMax Reitz                 local_err = NULL;
5594f88e1a42SJes Sorensen                 goto out;
5595f88e1a42SJes Sorensen             }
559652bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
559752bf1e72SMarkus Armbruster             if (size < 0) {
559852bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
559952bf1e72SMarkus Armbruster                                  backing_file);
560052bf1e72SMarkus Armbruster                 bdrv_unref(bs);
560152bf1e72SMarkus Armbruster                 goto out;
560252bf1e72SMarkus Armbruster             }
5603f88e1a42SJes Sorensen 
560483d0521aSChunyan Liu             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size);
560566f6b814SMax Reitz 
560666f6b814SMax Reitz             bdrv_unref(bs);
5607f88e1a42SJes Sorensen         } else {
560871c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5609f88e1a42SJes Sorensen             goto out;
5610f88e1a42SJes Sorensen         }
5611f88e1a42SJes Sorensen     }
5612f88e1a42SJes Sorensen 
5613f382d43aSMiroslav Rezanina     if (!quiet) {
5614f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
561583d0521aSChunyan Liu         qemu_opts_print(opts);
5616f88e1a42SJes Sorensen         puts("");
5617f382d43aSMiroslav Rezanina     }
561883d0521aSChunyan Liu 
5619c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
562083d0521aSChunyan Liu 
5621cc84d90fSMax Reitz     if (ret == -EFBIG) {
5622cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5623cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5624cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5625f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
562683d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
5627f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5628f3f4d2c0SKevin Wolf         }
5629cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5630cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5631cc84d90fSMax Reitz         error_free(local_err);
5632cc84d90fSMax Reitz         local_err = NULL;
5633f88e1a42SJes Sorensen     }
5634f88e1a42SJes Sorensen 
5635f88e1a42SJes Sorensen out:
563683d0521aSChunyan Liu     qemu_opts_del(opts);
563783d0521aSChunyan Liu     qemu_opts_free(create_opts);
563884d18f06SMarkus Armbruster     if (local_err) {
5639cc84d90fSMax Reitz         error_propagate(errp, local_err);
5640cc84d90fSMax Reitz     }
5641f88e1a42SJes Sorensen }
564285d126f3SStefan Hajnoczi 
564385d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
564485d126f3SStefan Hajnoczi {
5645dcd04228SStefan Hajnoczi     return bs->aio_context;
5646dcd04228SStefan Hajnoczi }
5647dcd04228SStefan Hajnoczi 
5648dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
5649dcd04228SStefan Hajnoczi {
565033384421SMax Reitz     BdrvAioNotifier *baf;
565133384421SMax Reitz 
5652dcd04228SStefan Hajnoczi     if (!bs->drv) {
5653dcd04228SStefan Hajnoczi         return;
5654dcd04228SStefan Hajnoczi     }
5655dcd04228SStefan Hajnoczi 
565633384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
565733384421SMax Reitz         baf->detach_aio_context(baf->opaque);
565833384421SMax Reitz     }
565933384421SMax Reitz 
566013af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
566113af91ebSStefan Hajnoczi         throttle_detach_aio_context(&bs->throttle_state);
566213af91ebSStefan Hajnoczi     }
5663dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
5664dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
5665dcd04228SStefan Hajnoczi     }
5666dcd04228SStefan Hajnoczi     if (bs->file) {
5667dcd04228SStefan Hajnoczi         bdrv_detach_aio_context(bs->file);
5668dcd04228SStefan Hajnoczi     }
5669dcd04228SStefan Hajnoczi     if (bs->backing_hd) {
5670dcd04228SStefan Hajnoczi         bdrv_detach_aio_context(bs->backing_hd);
5671dcd04228SStefan Hajnoczi     }
5672dcd04228SStefan Hajnoczi 
5673dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
5674dcd04228SStefan Hajnoczi }
5675dcd04228SStefan Hajnoczi 
5676dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
5677dcd04228SStefan Hajnoczi                              AioContext *new_context)
5678dcd04228SStefan Hajnoczi {
567933384421SMax Reitz     BdrvAioNotifier *ban;
568033384421SMax Reitz 
5681dcd04228SStefan Hajnoczi     if (!bs->drv) {
5682dcd04228SStefan Hajnoczi         return;
5683dcd04228SStefan Hajnoczi     }
5684dcd04228SStefan Hajnoczi 
5685dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
5686dcd04228SStefan Hajnoczi 
5687dcd04228SStefan Hajnoczi     if (bs->backing_hd) {
5688dcd04228SStefan Hajnoczi         bdrv_attach_aio_context(bs->backing_hd, new_context);
5689dcd04228SStefan Hajnoczi     }
5690dcd04228SStefan Hajnoczi     if (bs->file) {
5691dcd04228SStefan Hajnoczi         bdrv_attach_aio_context(bs->file, new_context);
5692dcd04228SStefan Hajnoczi     }
5693dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
5694dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
5695dcd04228SStefan Hajnoczi     }
569613af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
569713af91ebSStefan Hajnoczi         throttle_attach_aio_context(&bs->throttle_state, new_context);
569813af91ebSStefan Hajnoczi     }
569933384421SMax Reitz 
570033384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
570133384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
570233384421SMax Reitz     }
5703dcd04228SStefan Hajnoczi }
5704dcd04228SStefan Hajnoczi 
5705dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
5706dcd04228SStefan Hajnoczi {
5707dcd04228SStefan Hajnoczi     bdrv_drain_all(); /* ensure there are no in-flight requests */
5708dcd04228SStefan Hajnoczi 
5709dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
5710dcd04228SStefan Hajnoczi 
5711dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
5712dcd04228SStefan Hajnoczi      * case it runs in a different thread.
5713dcd04228SStefan Hajnoczi      */
5714dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
5715dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
5716dcd04228SStefan Hajnoczi     aio_context_release(new_context);
571785d126f3SStefan Hajnoczi }
5718d616b224SStefan Hajnoczi 
571933384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
572033384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
572133384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
572233384421SMax Reitz {
572333384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
572433384421SMax Reitz     *ban = (BdrvAioNotifier){
572533384421SMax Reitz         .attached_aio_context = attached_aio_context,
572633384421SMax Reitz         .detach_aio_context   = detach_aio_context,
572733384421SMax Reitz         .opaque               = opaque
572833384421SMax Reitz     };
572933384421SMax Reitz 
573033384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
573133384421SMax Reitz }
573233384421SMax Reitz 
573333384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
573433384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
573533384421SMax Reitz                                                                    void *),
573633384421SMax Reitz                                       void (*detach_aio_context)(void *),
573733384421SMax Reitz                                       void *opaque)
573833384421SMax Reitz {
573933384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
574033384421SMax Reitz 
574133384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
574233384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
574333384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
574433384421SMax Reitz             ban->opaque               == opaque)
574533384421SMax Reitz         {
574633384421SMax Reitz             QLIST_REMOVE(ban, list);
574733384421SMax Reitz             g_free(ban);
574833384421SMax Reitz 
574933384421SMax Reitz             return;
575033384421SMax Reitz         }
575133384421SMax Reitz     }
575233384421SMax Reitz 
575333384421SMax Reitz     abort();
575433384421SMax Reitz }
575533384421SMax Reitz 
5756d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5757d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5758d616b224SStefan Hajnoczi {
5759d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5760d616b224SStefan Hajnoczi }
57616f176b48SMax Reitz 
5762*77485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
5763*77485434SMax Reitz                        BlockDriverAmendStatusCB *status_cb)
57646f176b48SMax Reitz {
5765c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
57666f176b48SMax Reitz         return -ENOTSUP;
57676f176b48SMax Reitz     }
5768*77485434SMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb);
57696f176b48SMax Reitz }
5770f6186f49SBenoît Canet 
5771b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
5772b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
5773b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
5774b5042a36SBenoît Canet  * node graph.
5775212a5a8fSBenoît Canet  */
5776212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5777212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5778f6186f49SBenoît Canet {
5779b5042a36SBenoît Canet     /* return false if basic checks fails */
5780b5042a36SBenoît Canet     if (!bs || !bs->drv) {
5781b5042a36SBenoît Canet         return false;
5782b5042a36SBenoît Canet     }
5783b5042a36SBenoît Canet 
5784b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
5785b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
5786b5042a36SBenoît Canet      */
5787b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
5788b5042a36SBenoît Canet         return bs == candidate;
5789b5042a36SBenoît Canet     }
5790b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
5791b5042a36SBenoît Canet 
5792b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
5793b5042a36SBenoît Canet      * the node graph.
5794b5042a36SBenoît Canet      */
5795b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
5796212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5797212a5a8fSBenoît Canet     }
5798212a5a8fSBenoît Canet 
5799b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
5800b5042a36SBenoît Canet      */
5801b5042a36SBenoît Canet     return false;
5802212a5a8fSBenoît Canet }
5803212a5a8fSBenoît Canet 
5804212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5805212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5806212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5807212a5a8fSBenoît Canet  */
5808212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5809212a5a8fSBenoît Canet {
5810212a5a8fSBenoît Canet     BlockDriverState *bs;
5811212a5a8fSBenoît Canet 
5812212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5813212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5814212a5a8fSBenoît Canet         bool perm;
5815212a5a8fSBenoît Canet 
5816b5042a36SBenoît Canet         /* try to recurse in this top level bs */
5817e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
5818212a5a8fSBenoît Canet 
5819212a5a8fSBenoît Canet         /* candidate is the first non filter */
5820212a5a8fSBenoît Canet         if (perm) {
5821212a5a8fSBenoît Canet             return true;
5822212a5a8fSBenoît Canet         }
5823212a5a8fSBenoît Canet     }
5824212a5a8fSBenoît Canet 
5825212a5a8fSBenoît Canet     return false;
5826f6186f49SBenoît Canet }
582709158f00SBenoît Canet 
582809158f00SBenoît Canet BlockDriverState *check_to_replace_node(const char *node_name, Error **errp)
582909158f00SBenoît Canet {
583009158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
583109158f00SBenoît Canet     if (!to_replace_bs) {
583209158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
583309158f00SBenoît Canet         return NULL;
583409158f00SBenoît Canet     }
583509158f00SBenoît Canet 
583609158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
583709158f00SBenoît Canet         return NULL;
583809158f00SBenoît Canet     }
583909158f00SBenoît Canet 
584009158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
584109158f00SBenoît Canet      * most non filter in order to prevent data corruption.
584209158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
584309158f00SBenoît Canet      * blocked by the backing blockers.
584409158f00SBenoît Canet      */
584509158f00SBenoît Canet     if (!bdrv_is_first_non_filter(to_replace_bs)) {
584609158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
584709158f00SBenoît Canet         return NULL;
584809158f00SBenoît Canet     }
584909158f00SBenoît Canet 
585009158f00SBenoît Canet     return to_replace_bs;
585109158f00SBenoît Canet }
5852448ad91dSMing Lei 
5853448ad91dSMing Lei void bdrv_io_plug(BlockDriverState *bs)
5854448ad91dSMing Lei {
5855448ad91dSMing Lei     BlockDriver *drv = bs->drv;
5856448ad91dSMing Lei     if (drv && drv->bdrv_io_plug) {
5857448ad91dSMing Lei         drv->bdrv_io_plug(bs);
5858448ad91dSMing Lei     } else if (bs->file) {
5859448ad91dSMing Lei         bdrv_io_plug(bs->file);
5860448ad91dSMing Lei     }
5861448ad91dSMing Lei }
5862448ad91dSMing Lei 
5863448ad91dSMing Lei void bdrv_io_unplug(BlockDriverState *bs)
5864448ad91dSMing Lei {
5865448ad91dSMing Lei     BlockDriver *drv = bs->drv;
5866448ad91dSMing Lei     if (drv && drv->bdrv_io_unplug) {
5867448ad91dSMing Lei         drv->bdrv_io_unplug(bs);
5868448ad91dSMing Lei     } else if (bs->file) {
5869448ad91dSMing Lei         bdrv_io_unplug(bs->file);
5870448ad91dSMing Lei     }
5871448ad91dSMing Lei }
5872448ad91dSMing Lei 
5873448ad91dSMing Lei void bdrv_flush_io_queue(BlockDriverState *bs)
5874448ad91dSMing Lei {
5875448ad91dSMing Lei     BlockDriver *drv = bs->drv;
5876448ad91dSMing Lei     if (drv && drv->bdrv_flush_io_queue) {
5877448ad91dSMing Lei         drv->bdrv_flush_io_queue(bs);
5878448ad91dSMing Lei     } else if (bs->file) {
5879448ad91dSMing Lei         bdrv_flush_io_queue(bs->file);
5880448ad91dSMing Lei     }
5881448ad91dSMing Lei }
588291af7014SMax Reitz 
588391af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
588491af7014SMax Reitz {
588591af7014SMax Reitz     const QDictEntry *entry;
588691af7014SMax Reitz     bool found_any = false;
588791af7014SMax Reitz 
588891af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
588991af7014SMax Reitz          entry = qdict_next(bs->options, entry))
589091af7014SMax Reitz     {
589191af7014SMax Reitz         /* Only take options for this level and exclude all non-driver-specific
589291af7014SMax Reitz          * options */
589391af7014SMax Reitz         if (!strchr(qdict_entry_key(entry), '.') &&
589491af7014SMax Reitz             strcmp(qdict_entry_key(entry), "node-name"))
589591af7014SMax Reitz         {
589691af7014SMax Reitz             qobject_incref(qdict_entry_value(entry));
589791af7014SMax Reitz             qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
589891af7014SMax Reitz             found_any = true;
589991af7014SMax Reitz         }
590091af7014SMax Reitz     }
590191af7014SMax Reitz 
590291af7014SMax Reitz     return found_any;
590391af7014SMax Reitz }
590491af7014SMax Reitz 
590591af7014SMax Reitz /* Updates the following BDS fields:
590691af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
590791af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
590891af7014SMax Reitz  *                    other options; so reading and writing must return the same
590991af7014SMax Reitz  *                    results, but caching etc. may be different)
591091af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
591191af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
591291af7014SMax Reitz  *                       equalling the given one
591391af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
591491af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
591591af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
591691af7014SMax Reitz  */
591791af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
591891af7014SMax Reitz {
591991af7014SMax Reitz     BlockDriver *drv = bs->drv;
592091af7014SMax Reitz     QDict *opts;
592191af7014SMax Reitz 
592291af7014SMax Reitz     if (!drv) {
592391af7014SMax Reitz         return;
592491af7014SMax Reitz     }
592591af7014SMax Reitz 
592691af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
592791af7014SMax Reitz      * refresh that first */
592891af7014SMax Reitz     if (bs->file) {
592991af7014SMax Reitz         bdrv_refresh_filename(bs->file);
593091af7014SMax Reitz     }
593191af7014SMax Reitz 
593291af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
593391af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
593491af7014SMax Reitz          * information before refreshing it */
593591af7014SMax Reitz         bs->exact_filename[0] = '\0';
593691af7014SMax Reitz         if (bs->full_open_options) {
593791af7014SMax Reitz             QDECREF(bs->full_open_options);
593891af7014SMax Reitz             bs->full_open_options = NULL;
593991af7014SMax Reitz         }
594091af7014SMax Reitz 
594191af7014SMax Reitz         drv->bdrv_refresh_filename(bs);
594291af7014SMax Reitz     } else if (bs->file) {
594391af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
594491af7014SMax Reitz         bool has_open_options;
594591af7014SMax Reitz 
594691af7014SMax Reitz         bs->exact_filename[0] = '\0';
594791af7014SMax Reitz         if (bs->full_open_options) {
594891af7014SMax Reitz             QDECREF(bs->full_open_options);
594991af7014SMax Reitz             bs->full_open_options = NULL;
595091af7014SMax Reitz         }
595191af7014SMax Reitz 
595291af7014SMax Reitz         opts = qdict_new();
595391af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
595491af7014SMax Reitz 
595591af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
595691af7014SMax Reitz          * the underlying file should suffice for this one as well */
595791af7014SMax Reitz         if (bs->file->exact_filename[0] && !has_open_options) {
595891af7014SMax Reitz             strcpy(bs->exact_filename, bs->file->exact_filename);
595991af7014SMax Reitz         }
596091af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
596191af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
596291af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
596391af7014SMax Reitz          * contain a representation of the filename, therefore the following
596491af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
596591af7014SMax Reitz         if (bs->file->full_open_options) {
596691af7014SMax Reitz             qdict_put_obj(opts, "driver",
596791af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
596891af7014SMax Reitz             QINCREF(bs->file->full_open_options);
596991af7014SMax Reitz             qdict_put_obj(opts, "file", QOBJECT(bs->file->full_open_options));
597091af7014SMax Reitz 
597191af7014SMax Reitz             bs->full_open_options = opts;
597291af7014SMax Reitz         } else {
597391af7014SMax Reitz             QDECREF(opts);
597491af7014SMax Reitz         }
597591af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
597691af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
597791af7014SMax Reitz          * so the full options QDict should be equal to the options given
597891af7014SMax Reitz          * specifically for this block device when it was opened (plus the
597991af7014SMax Reitz          * driver specification).
598091af7014SMax Reitz          * Because those options don't change, there is no need to update
598191af7014SMax Reitz          * full_open_options when it's already set. */
598291af7014SMax Reitz 
598391af7014SMax Reitz         opts = qdict_new();
598491af7014SMax Reitz         append_open_options(opts, bs);
598591af7014SMax Reitz         qdict_put_obj(opts, "driver",
598691af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
598791af7014SMax Reitz 
598891af7014SMax Reitz         if (bs->exact_filename[0]) {
598991af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
599091af7014SMax Reitz              * require this filename to be parsed), but we have to find some
599191af7014SMax Reitz              * default solution here, so just include it. If some block driver
599291af7014SMax Reitz              * does not support pure options without any filename at all or
599391af7014SMax Reitz              * needs some special format of the options QDict, it needs to
599491af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
599591af7014SMax Reitz              */
599691af7014SMax Reitz             qdict_put_obj(opts, "filename",
599791af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
599891af7014SMax Reitz         }
599991af7014SMax Reitz 
600091af7014SMax Reitz         bs->full_open_options = opts;
600191af7014SMax Reitz     }
600291af7014SMax Reitz 
600391af7014SMax Reitz     if (bs->exact_filename[0]) {
600491af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
600591af7014SMax Reitz     } else if (bs->full_open_options) {
600691af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
600791af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
600891af7014SMax Reitz                  qstring_get_str(json));
600991af7014SMax Reitz         QDECREF(json);
601091af7014SMax Reitz     }
601191af7014SMax Reitz }
60125366d0c8SBenoît Canet 
60135366d0c8SBenoît Canet /* This accessor function purpose is to allow the device models to access the
60145366d0c8SBenoît Canet  * BlockAcctStats structure embedded inside a BlockDriverState without being
60155366d0c8SBenoît Canet  * aware of the BlockDriverState structure layout.
60165366d0c8SBenoît Canet  * It will go away when the BlockAcctStats structure will be moved inside
60175366d0c8SBenoît Canet  * the device models.
60185366d0c8SBenoît Canet  */
60195366d0c8SBenoît Canet BlockAcctStats *bdrv_get_stats(BlockDriverState *bs)
60205366d0c8SBenoît Canet {
60215366d0c8SBenoît Canet     return &bs->stats;
60225366d0c8SBenoît Canet }
6023