xref: /openbmc/qemu/block.c (revision f187743acd39747cc8cc32111518142c924963b9)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
2783c9089eSPaolo Bonzini #include "monitor/monitor.h"
28737e150eSPaolo Bonzini #include "block/block_int.h"
29737e150eSPaolo Bonzini #include "block/blockjob.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
317b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
331de7afc9SPaolo Bonzini #include "qemu/notify.h"
34737e150eSPaolo Bonzini #include "block/coroutine.h"
35c13163fbSBenoît Canet #include "block/qapi.h"
36b2023818SLuiz Capitulino #include "qmp-commands.h"
371de7afc9SPaolo Bonzini #include "qemu/timer.h"
38fc01f7e7Sbellard 
3971e72a19SJuan Quintela #ifdef CONFIG_BSD
407674e7bfSbellard #include <sys/types.h>
417674e7bfSbellard #include <sys/stat.h>
427674e7bfSbellard #include <sys/ioctl.h>
4372cf2d4fSBlue Swirl #include <sys/queue.h>
44c5e97233Sblueswir1 #ifndef __DragonFly__
457674e7bfSbellard #include <sys/disk.h>
467674e7bfSbellard #endif
47c5e97233Sblueswir1 #endif
487674e7bfSbellard 
4949dc768dSaliguori #ifdef _WIN32
5049dc768dSaliguori #include <windows.h>
5149dc768dSaliguori #endif
5249dc768dSaliguori 
53e4654d2dSFam Zheng struct BdrvDirtyBitmap {
54e4654d2dSFam Zheng     HBitmap *bitmap;
55e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
56e4654d2dSFam Zheng };
57e4654d2dSFam Zheng 
581c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
591c9805a3SStefan Hajnoczi 
607d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
61f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
62f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
64f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
65f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
67f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
68f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
69f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
70f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
71f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
72f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
73775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
74775aa8b6SKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
75470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
76775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
77775aa8b6SKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
78f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
79b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
80b2a61371SStefan Hajnoczi                                                int64_t sector_num,
81b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
82b2a61371SStefan Hajnoczi                                                int nb_sectors,
83d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
84b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
85b2a61371SStefan Hajnoczi                                                void *opaque,
868c5873d6SStefan Hajnoczi                                                bool is_write);
87b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
88621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
89aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
90ec530c81Sbellard 
911b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
921b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
937ee930d0Sblueswir1 
94dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
95dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
96dc364f4cSBenoît Canet 
978a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
988a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
99ea2384d3Sbellard 
100eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
101eb852011SMarkus Armbruster static int use_bdrv_whitelist;
102eb852011SMarkus Armbruster 
1039e0b22f4SStefan Hajnoczi #ifdef _WIN32
1049e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1059e0b22f4SStefan Hajnoczi {
1069e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1079e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1089e0b22f4SStefan Hajnoczi             filename[1] == ':');
1099e0b22f4SStefan Hajnoczi }
1109e0b22f4SStefan Hajnoczi 
1119e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1129e0b22f4SStefan Hajnoczi {
1139e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1149e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1159e0b22f4SStefan Hajnoczi         return 1;
1169e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1179e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1189e0b22f4SStefan Hajnoczi         return 1;
1199e0b22f4SStefan Hajnoczi     return 0;
1209e0b22f4SStefan Hajnoczi }
1219e0b22f4SStefan Hajnoczi #endif
1229e0b22f4SStefan Hajnoczi 
1230563e191SZhi Yong Wu /* throttling disk I/O limits */
124cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs,
125cc0681c4SBenoît Canet                         ThrottleConfig *cfg)
126cc0681c4SBenoît Canet {
127cc0681c4SBenoît Canet     int i;
128cc0681c4SBenoît Canet 
129cc0681c4SBenoît Canet     throttle_config(&bs->throttle_state, cfg);
130cc0681c4SBenoît Canet 
131cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
132cc0681c4SBenoît Canet         qemu_co_enter_next(&bs->throttled_reqs[i]);
133cc0681c4SBenoît Canet     }
134cc0681c4SBenoît Canet }
135cc0681c4SBenoît Canet 
136cc0681c4SBenoît Canet /* this function drain all the throttled IOs */
137cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
138cc0681c4SBenoît Canet {
139cc0681c4SBenoît Canet     bool drained = false;
140cc0681c4SBenoît Canet     bool enabled = bs->io_limits_enabled;
141cc0681c4SBenoît Canet     int i;
142cc0681c4SBenoît Canet 
143cc0681c4SBenoît Canet     bs->io_limits_enabled = false;
144cc0681c4SBenoît Canet 
145cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
146cc0681c4SBenoît Canet         while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
147cc0681c4SBenoît Canet             drained = true;
148cc0681c4SBenoît Canet         }
149cc0681c4SBenoît Canet     }
150cc0681c4SBenoît Canet 
151cc0681c4SBenoît Canet     bs->io_limits_enabled = enabled;
152cc0681c4SBenoît Canet 
153cc0681c4SBenoît Canet     return drained;
154cc0681c4SBenoît Canet }
155cc0681c4SBenoît Canet 
15698f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
15798f90dbaSZhi Yong Wu {
15898f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
15998f90dbaSZhi Yong Wu 
160cc0681c4SBenoît Canet     bdrv_start_throttled_reqs(bs);
16198f90dbaSZhi Yong Wu 
162cc0681c4SBenoît Canet     throttle_destroy(&bs->throttle_state);
16398f90dbaSZhi Yong Wu }
16498f90dbaSZhi Yong Wu 
165cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque)
1660563e191SZhi Yong Wu {
1670563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
168cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[0]);
1690563e191SZhi Yong Wu }
1700563e191SZhi Yong Wu 
171cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque)
172cc0681c4SBenoît Canet {
173cc0681c4SBenoît Canet     BlockDriverState *bs = opaque;
174cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[1]);
175cc0681c4SBenoît Canet }
176cc0681c4SBenoît Canet 
177cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */
1780563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1790563e191SZhi Yong Wu {
180cc0681c4SBenoît Canet     assert(!bs->io_limits_enabled);
181cc0681c4SBenoît Canet     throttle_init(&bs->throttle_state,
182cc0681c4SBenoît Canet                   QEMU_CLOCK_VIRTUAL,
183cc0681c4SBenoît Canet                   bdrv_throttle_read_timer_cb,
184cc0681c4SBenoît Canet                   bdrv_throttle_write_timer_cb,
185cc0681c4SBenoît Canet                   bs);
1860563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1870563e191SZhi Yong Wu }
1880563e191SZhi Yong Wu 
189cc0681c4SBenoît Canet /* This function makes an IO wait if needed
190cc0681c4SBenoît Canet  *
191cc0681c4SBenoît Canet  * @nb_sectors: the number of sectors of the IO
192cc0681c4SBenoît Canet  * @is_write:   is the IO a write
19398f90dbaSZhi Yong Wu  */
194cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs,
195d5103588SKevin Wolf                                      unsigned int bytes,
196cc0681c4SBenoît Canet                                      bool is_write)
197cc0681c4SBenoît Canet {
198cc0681c4SBenoît Canet     /* does this io must wait */
199cc0681c4SBenoît Canet     bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
20098f90dbaSZhi Yong Wu 
201cc0681c4SBenoît Canet     /* if must wait or any request of this type throttled queue the IO */
202cc0681c4SBenoît Canet     if (must_wait ||
203cc0681c4SBenoît Canet         !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
204cc0681c4SBenoît Canet         qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
20598f90dbaSZhi Yong Wu     }
20698f90dbaSZhi Yong Wu 
207cc0681c4SBenoît Canet     /* the IO will be executed, do the accounting */
208d5103588SKevin Wolf     throttle_account(&bs->throttle_state, is_write, bytes);
209d5103588SKevin Wolf 
210cc0681c4SBenoît Canet 
211cc0681c4SBenoît Canet     /* if the next request must wait -> do nothing */
212cc0681c4SBenoît Canet     if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
213cc0681c4SBenoît Canet         return;
214cc0681c4SBenoît Canet     }
215cc0681c4SBenoît Canet 
216cc0681c4SBenoît Canet     /* else queue next request for execution */
217cc0681c4SBenoît Canet     qemu_co_queue_next(&bs->throttled_reqs[is_write]);
21898f90dbaSZhi Yong Wu }
21998f90dbaSZhi Yong Wu 
220339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
221339064d5SKevin Wolf {
222339064d5SKevin Wolf     if (!bs || !bs->drv) {
223339064d5SKevin Wolf         /* 4k should be on the safe side */
224339064d5SKevin Wolf         return 4096;
225339064d5SKevin Wolf     }
226339064d5SKevin Wolf 
227339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
228339064d5SKevin Wolf }
229339064d5SKevin Wolf 
2309e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
2319e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2329e0b22f4SStefan Hajnoczi {
233947995c0SPaolo Bonzini     const char *p;
234947995c0SPaolo Bonzini 
2359e0b22f4SStefan Hajnoczi #ifdef _WIN32
2369e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2379e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2389e0b22f4SStefan Hajnoczi         return 0;
2399e0b22f4SStefan Hajnoczi     }
240947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
241947995c0SPaolo Bonzini #else
242947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2439e0b22f4SStefan Hajnoczi #endif
2449e0b22f4SStefan Hajnoczi 
245947995c0SPaolo Bonzini     return *p == ':';
2469e0b22f4SStefan Hajnoczi }
2479e0b22f4SStefan Hajnoczi 
24883f64091Sbellard int path_is_absolute(const char *path)
24983f64091Sbellard {
25021664424Sbellard #ifdef _WIN32
25121664424Sbellard     /* specific case for names like: "\\.\d:" */
252f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
25321664424Sbellard         return 1;
254f53f4da9SPaolo Bonzini     }
255f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2563b9f94e1Sbellard #else
257f53f4da9SPaolo Bonzini     return (*path == '/');
2583b9f94e1Sbellard #endif
25983f64091Sbellard }
26083f64091Sbellard 
26183f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
26283f64091Sbellard    path to it by considering it is relative to base_path. URL are
26383f64091Sbellard    supported. */
26483f64091Sbellard void path_combine(char *dest, int dest_size,
26583f64091Sbellard                   const char *base_path,
26683f64091Sbellard                   const char *filename)
26783f64091Sbellard {
26883f64091Sbellard     const char *p, *p1;
26983f64091Sbellard     int len;
27083f64091Sbellard 
27183f64091Sbellard     if (dest_size <= 0)
27283f64091Sbellard         return;
27383f64091Sbellard     if (path_is_absolute(filename)) {
27483f64091Sbellard         pstrcpy(dest, dest_size, filename);
27583f64091Sbellard     } else {
27683f64091Sbellard         p = strchr(base_path, ':');
27783f64091Sbellard         if (p)
27883f64091Sbellard             p++;
27983f64091Sbellard         else
28083f64091Sbellard             p = base_path;
2813b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2823b9f94e1Sbellard #ifdef _WIN32
2833b9f94e1Sbellard         {
2843b9f94e1Sbellard             const char *p2;
2853b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2863b9f94e1Sbellard             if (!p1 || p2 > p1)
2873b9f94e1Sbellard                 p1 = p2;
2883b9f94e1Sbellard         }
2893b9f94e1Sbellard #endif
29083f64091Sbellard         if (p1)
29183f64091Sbellard             p1++;
29283f64091Sbellard         else
29383f64091Sbellard             p1 = base_path;
29483f64091Sbellard         if (p1 > p)
29583f64091Sbellard             p = p1;
29683f64091Sbellard         len = p - base_path;
29783f64091Sbellard         if (len > dest_size - 1)
29883f64091Sbellard             len = dest_size - 1;
29983f64091Sbellard         memcpy(dest, base_path, len);
30083f64091Sbellard         dest[len] = '\0';
30183f64091Sbellard         pstrcat(dest, dest_size, filename);
30283f64091Sbellard     }
30383f64091Sbellard }
30483f64091Sbellard 
305dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
306dc5a1371SPaolo Bonzini {
307dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
308dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
309dc5a1371SPaolo Bonzini     } else {
310dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
311dc5a1371SPaolo Bonzini     }
312dc5a1371SPaolo Bonzini }
313dc5a1371SPaolo Bonzini 
3145efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
315ea2384d3Sbellard {
3168c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
3178c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
318f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
319f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
320f9f05dc5SKevin Wolf 
321f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
322f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
323f8c35c1dSStefan Hajnoczi          */
324f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
32583f64091Sbellard             /* add AIO emulation layer */
326f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
327f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
32883f64091Sbellard         }
329f9f05dc5SKevin Wolf     }
330b2e12bc6SChristoph Hellwig 
3318a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
332ea2384d3Sbellard }
333b338082bSbellard 
334b338082bSbellard /* create a new block device (by default it is empty) */
335b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
336fc01f7e7Sbellard {
3371b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
338b338082bSbellard 
3397267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
340e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
341b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
342ea2384d3Sbellard     if (device_name[0] != '\0') {
343dc364f4cSBenoît Canet         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
344ea2384d3Sbellard     }
34528a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
346d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
347d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
348cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
349cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3509fcb0251SFam Zheng     bs->refcnt = 1;
351d7d512f6SPaolo Bonzini 
352b338082bSbellard     return bs;
353b338082bSbellard }
354b338082bSbellard 
355d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
356d7d512f6SPaolo Bonzini {
357d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
358d7d512f6SPaolo Bonzini }
359d7d512f6SPaolo Bonzini 
360ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
361ea2384d3Sbellard {
362ea2384d3Sbellard     BlockDriver *drv1;
3638a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3648a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
365ea2384d3Sbellard             return drv1;
366ea2384d3Sbellard         }
3678a22f02aSStefan Hajnoczi     }
368ea2384d3Sbellard     return NULL;
369ea2384d3Sbellard }
370ea2384d3Sbellard 
371b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
372eb852011SMarkus Armbruster {
373b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
374b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
375b64ec4e4SFam Zheng     };
376b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
377b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
378eb852011SMarkus Armbruster     };
379eb852011SMarkus Armbruster     const char **p;
380eb852011SMarkus Armbruster 
381b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
382eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
383b64ec4e4SFam Zheng     }
384eb852011SMarkus Armbruster 
385b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
386eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
387eb852011SMarkus Armbruster             return 1;
388eb852011SMarkus Armbruster         }
389eb852011SMarkus Armbruster     }
390b64ec4e4SFam Zheng     if (read_only) {
391b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
392b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
393b64ec4e4SFam Zheng                 return 1;
394b64ec4e4SFam Zheng             }
395b64ec4e4SFam Zheng         }
396b64ec4e4SFam Zheng     }
397eb852011SMarkus Armbruster     return 0;
398eb852011SMarkus Armbruster }
399eb852011SMarkus Armbruster 
400b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
401b64ec4e4SFam Zheng                                           bool read_only)
402eb852011SMarkus Armbruster {
403eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
404b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
405eb852011SMarkus Armbruster }
406eb852011SMarkus Armbruster 
4075b7e1542SZhi Yong Wu typedef struct CreateCo {
4085b7e1542SZhi Yong Wu     BlockDriver *drv;
4095b7e1542SZhi Yong Wu     char *filename;
4105b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
4115b7e1542SZhi Yong Wu     int ret;
412cc84d90fSMax Reitz     Error *err;
4135b7e1542SZhi Yong Wu } CreateCo;
4145b7e1542SZhi Yong Wu 
4155b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4165b7e1542SZhi Yong Wu {
417cc84d90fSMax Reitz     Error *local_err = NULL;
418cc84d90fSMax Reitz     int ret;
419cc84d90fSMax Reitz 
4205b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4215b7e1542SZhi Yong Wu     assert(cco->drv);
4225b7e1542SZhi Yong Wu 
423cc84d90fSMax Reitz     ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
42484d18f06SMarkus Armbruster     if (local_err) {
425cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
426cc84d90fSMax Reitz     }
427cc84d90fSMax Reitz     cco->ret = ret;
4285b7e1542SZhi Yong Wu }
4295b7e1542SZhi Yong Wu 
4300e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
431cc84d90fSMax Reitz     QEMUOptionParameter *options, Error **errp)
432ea2384d3Sbellard {
4335b7e1542SZhi Yong Wu     int ret;
4340e7e1989SKevin Wolf 
4355b7e1542SZhi Yong Wu     Coroutine *co;
4365b7e1542SZhi Yong Wu     CreateCo cco = {
4375b7e1542SZhi Yong Wu         .drv = drv,
4385b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
4395b7e1542SZhi Yong Wu         .options = options,
4405b7e1542SZhi Yong Wu         .ret = NOT_DONE,
441cc84d90fSMax Reitz         .err = NULL,
4425b7e1542SZhi Yong Wu     };
4435b7e1542SZhi Yong Wu 
4445b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
445cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
44680168bffSLuiz Capitulino         ret = -ENOTSUP;
44780168bffSLuiz Capitulino         goto out;
4485b7e1542SZhi Yong Wu     }
4495b7e1542SZhi Yong Wu 
4505b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4515b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4525b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4535b7e1542SZhi Yong Wu     } else {
4545b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4555b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4565b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4575b7e1542SZhi Yong Wu             qemu_aio_wait();
4585b7e1542SZhi Yong Wu         }
4595b7e1542SZhi Yong Wu     }
4605b7e1542SZhi Yong Wu 
4615b7e1542SZhi Yong Wu     ret = cco.ret;
462cc84d90fSMax Reitz     if (ret < 0) {
46384d18f06SMarkus Armbruster         if (cco.err) {
464cc84d90fSMax Reitz             error_propagate(errp, cco.err);
465cc84d90fSMax Reitz         } else {
466cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
467cc84d90fSMax Reitz         }
468cc84d90fSMax Reitz     }
4695b7e1542SZhi Yong Wu 
47080168bffSLuiz Capitulino out:
47180168bffSLuiz Capitulino     g_free(cco.filename);
4725b7e1542SZhi Yong Wu     return ret;
473ea2384d3Sbellard }
474ea2384d3Sbellard 
475cc84d90fSMax Reitz int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
476cc84d90fSMax Reitz                      Error **errp)
47784a12e66SChristoph Hellwig {
47884a12e66SChristoph Hellwig     BlockDriver *drv;
479cc84d90fSMax Reitz     Error *local_err = NULL;
480cc84d90fSMax Reitz     int ret;
48184a12e66SChristoph Hellwig 
48298289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
48384a12e66SChristoph Hellwig     if (drv == NULL) {
484cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
48516905d71SStefan Hajnoczi         return -ENOENT;
48684a12e66SChristoph Hellwig     }
48784a12e66SChristoph Hellwig 
488cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, options, &local_err);
48984d18f06SMarkus Armbruster     if (local_err) {
490cc84d90fSMax Reitz         error_propagate(errp, local_err);
491cc84d90fSMax Reitz     }
492cc84d90fSMax Reitz     return ret;
49384a12e66SChristoph Hellwig }
49484a12e66SChristoph Hellwig 
495355ef4acSKevin Wolf int bdrv_refresh_limits(BlockDriverState *bs)
496d34682cdSKevin Wolf {
497d34682cdSKevin Wolf     BlockDriver *drv = bs->drv;
498d34682cdSKevin Wolf 
499d34682cdSKevin Wolf     memset(&bs->bl, 0, sizeof(bs->bl));
500d34682cdSKevin Wolf 
501466ad822SKevin Wolf     if (!drv) {
502466ad822SKevin Wolf         return 0;
503466ad822SKevin Wolf     }
504466ad822SKevin Wolf 
505466ad822SKevin Wolf     /* Take some limits from the children as a default */
506466ad822SKevin Wolf     if (bs->file) {
507466ad822SKevin Wolf         bdrv_refresh_limits(bs->file);
508466ad822SKevin Wolf         bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
509339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
510339064d5SKevin Wolf     } else {
511339064d5SKevin Wolf         bs->bl.opt_mem_alignment = 512;
512466ad822SKevin Wolf     }
513466ad822SKevin Wolf 
514466ad822SKevin Wolf     if (bs->backing_hd) {
515466ad822SKevin Wolf         bdrv_refresh_limits(bs->backing_hd);
516466ad822SKevin Wolf         bs->bl.opt_transfer_length =
517466ad822SKevin Wolf             MAX(bs->bl.opt_transfer_length,
518466ad822SKevin Wolf                 bs->backing_hd->bl.opt_transfer_length);
519339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
520339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
521339064d5SKevin Wolf                 bs->backing_hd->bl.opt_mem_alignment);
522466ad822SKevin Wolf     }
523466ad822SKevin Wolf 
524466ad822SKevin Wolf     /* Then let the driver override it */
525466ad822SKevin Wolf     if (drv->bdrv_refresh_limits) {
526d34682cdSKevin Wolf         return drv->bdrv_refresh_limits(bs);
527d34682cdSKevin Wolf     }
528d34682cdSKevin Wolf 
529d34682cdSKevin Wolf     return 0;
530d34682cdSKevin Wolf }
531d34682cdSKevin Wolf 
532eba25057SJim Meyering /*
533eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
534eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
535eba25057SJim Meyering  */
536eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
537eba25057SJim Meyering {
538d5249393Sbellard #ifdef _WIN32
5393b9f94e1Sbellard     char temp_dir[MAX_PATH];
540eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
541eba25057SJim Meyering        have length MAX_PATH or greater.  */
542eba25057SJim Meyering     assert(size >= MAX_PATH);
543eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
544eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
545eba25057SJim Meyering             ? 0 : -GetLastError());
546d5249393Sbellard #else
547ea2384d3Sbellard     int fd;
5487ccfb2ebSblueswir1     const char *tmpdir;
5490badc1eeSaurel32     tmpdir = getenv("TMPDIR");
55069bef793SAmit Shah     if (!tmpdir) {
55169bef793SAmit Shah         tmpdir = "/var/tmp";
55269bef793SAmit Shah     }
553eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
554eba25057SJim Meyering         return -EOVERFLOW;
555ea2384d3Sbellard     }
556eba25057SJim Meyering     fd = mkstemp(filename);
557fe235a06SDunrong Huang     if (fd < 0) {
558fe235a06SDunrong Huang         return -errno;
559fe235a06SDunrong Huang     }
560fe235a06SDunrong Huang     if (close(fd) != 0) {
561fe235a06SDunrong Huang         unlink(filename);
562eba25057SJim Meyering         return -errno;
563eba25057SJim Meyering     }
564eba25057SJim Meyering     return 0;
565d5249393Sbellard #endif
566eba25057SJim Meyering }
567ea2384d3Sbellard 
568f3a5d3f8SChristoph Hellwig /*
569f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
570f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
571f3a5d3f8SChristoph Hellwig  */
572f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
573f3a5d3f8SChristoph Hellwig {
574508c7cb3SChristoph Hellwig     int score_max = 0, score;
575508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
576f3a5d3f8SChristoph Hellwig 
5778a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
578508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
579508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
580508c7cb3SChristoph Hellwig             if (score > score_max) {
581508c7cb3SChristoph Hellwig                 score_max = score;
582508c7cb3SChristoph Hellwig                 drv = d;
583f3a5d3f8SChristoph Hellwig             }
584508c7cb3SChristoph Hellwig         }
585f3a5d3f8SChristoph Hellwig     }
586f3a5d3f8SChristoph Hellwig 
587508c7cb3SChristoph Hellwig     return drv;
588f3a5d3f8SChristoph Hellwig }
589f3a5d3f8SChristoph Hellwig 
59098289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
59198289620SKevin Wolf                                 bool allow_protocol_prefix)
59284a12e66SChristoph Hellwig {
59384a12e66SChristoph Hellwig     BlockDriver *drv1;
59484a12e66SChristoph Hellwig     char protocol[128];
59584a12e66SChristoph Hellwig     int len;
59684a12e66SChristoph Hellwig     const char *p;
59784a12e66SChristoph Hellwig 
59866f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
59966f82ceeSKevin Wolf 
60039508e7aSChristoph Hellwig     /*
60139508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
60239508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
60339508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
60439508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
60539508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
60639508e7aSChristoph Hellwig      */
60784a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
60839508e7aSChristoph Hellwig     if (drv1) {
60984a12e66SChristoph Hellwig         return drv1;
61084a12e66SChristoph Hellwig     }
61139508e7aSChristoph Hellwig 
61298289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
61339508e7aSChristoph Hellwig         return bdrv_find_format("file");
61439508e7aSChristoph Hellwig     }
61598289620SKevin Wolf 
6169e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
6179e0b22f4SStefan Hajnoczi     assert(p != NULL);
61884a12e66SChristoph Hellwig     len = p - filename;
61984a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
62084a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
62184a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
62284a12e66SChristoph Hellwig     protocol[len] = '\0';
62384a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
62484a12e66SChristoph Hellwig         if (drv1->protocol_name &&
62584a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
62684a12e66SChristoph Hellwig             return drv1;
62784a12e66SChristoph Hellwig         }
62884a12e66SChristoph Hellwig     }
62984a12e66SChristoph Hellwig     return NULL;
63084a12e66SChristoph Hellwig }
63184a12e66SChristoph Hellwig 
632f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
63334b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
634ea2384d3Sbellard {
635f500a6d3SKevin Wolf     int score, score_max;
636ea2384d3Sbellard     BlockDriver *drv1, *drv;
63783f64091Sbellard     uint8_t buf[2048];
638f500a6d3SKevin Wolf     int ret = 0;
639f8ea0b00SNicholas Bellinger 
64008a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
6418e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
642c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
643c98ac35dSStefan Weil         if (!drv) {
64434b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
645c98ac35dSStefan Weil             ret = -ENOENT;
646c98ac35dSStefan Weil         }
647c98ac35dSStefan Weil         *pdrv = drv;
648c98ac35dSStefan Weil         return ret;
6491a396859SNicholas A. Bellinger     }
650f8ea0b00SNicholas Bellinger 
65183f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
652ea2384d3Sbellard     if (ret < 0) {
65334b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
65434b5d2c6SMax Reitz                          "format");
655c98ac35dSStefan Weil         *pdrv = NULL;
656c98ac35dSStefan Weil         return ret;
657ea2384d3Sbellard     }
658ea2384d3Sbellard 
659ea2384d3Sbellard     score_max = 0;
66084a12e66SChristoph Hellwig     drv = NULL;
6618a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
66283f64091Sbellard         if (drv1->bdrv_probe) {
663ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
664ea2384d3Sbellard             if (score > score_max) {
665ea2384d3Sbellard                 score_max = score;
666ea2384d3Sbellard                 drv = drv1;
667ea2384d3Sbellard             }
668ea2384d3Sbellard         }
66983f64091Sbellard     }
670c98ac35dSStefan Weil     if (!drv) {
67134b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
67234b5d2c6SMax Reitz                    "driver found");
673c98ac35dSStefan Weil         ret = -ENOENT;
674c98ac35dSStefan Weil     }
675c98ac35dSStefan Weil     *pdrv = drv;
676c98ac35dSStefan Weil     return ret;
677ea2384d3Sbellard }
678ea2384d3Sbellard 
67951762288SStefan Hajnoczi /**
68051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
68151762288SStefan Hajnoczi  */
68251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
68351762288SStefan Hajnoczi {
68451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
68551762288SStefan Hajnoczi 
686396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
687396759adSNicholas Bellinger     if (bs->sg)
688396759adSNicholas Bellinger         return 0;
689396759adSNicholas Bellinger 
69051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
69151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
69251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
69351762288SStefan Hajnoczi         if (length < 0) {
69451762288SStefan Hajnoczi             return length;
69551762288SStefan Hajnoczi         }
6967e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
69751762288SStefan Hajnoczi     }
69851762288SStefan Hajnoczi 
69951762288SStefan Hajnoczi     bs->total_sectors = hint;
70051762288SStefan Hajnoczi     return 0;
70151762288SStefan Hajnoczi }
70251762288SStefan Hajnoczi 
703c3993cdcSStefan Hajnoczi /**
7049e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
7059e8f1835SPaolo Bonzini  *
7069e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
7079e8f1835SPaolo Bonzini  */
7089e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
7099e8f1835SPaolo Bonzini {
7109e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
7119e8f1835SPaolo Bonzini 
7129e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
7139e8f1835SPaolo Bonzini         /* do nothing */
7149e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
7159e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
7169e8f1835SPaolo Bonzini     } else {
7179e8f1835SPaolo Bonzini         return -1;
7189e8f1835SPaolo Bonzini     }
7199e8f1835SPaolo Bonzini 
7209e8f1835SPaolo Bonzini     return 0;
7219e8f1835SPaolo Bonzini }
7229e8f1835SPaolo Bonzini 
7239e8f1835SPaolo Bonzini /**
724c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
725c3993cdcSStefan Hajnoczi  *
726c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
727c3993cdcSStefan Hajnoczi  */
728c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
729c3993cdcSStefan Hajnoczi {
730c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
731c3993cdcSStefan Hajnoczi 
732c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
733c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
73492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
73592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
736c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
737c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
738c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
739c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
740c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
741c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
742c3993cdcSStefan Hajnoczi         /* this is the default */
743c3993cdcSStefan Hajnoczi     } else {
744c3993cdcSStefan Hajnoczi         return -1;
745c3993cdcSStefan Hajnoczi     }
746c3993cdcSStefan Hajnoczi 
747c3993cdcSStefan Hajnoczi     return 0;
748c3993cdcSStefan Hajnoczi }
749c3993cdcSStefan Hajnoczi 
75053fec9d3SStefan Hajnoczi /**
75153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
75253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
75353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
75453fec9d3SStefan Hajnoczi  */
75553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
75653fec9d3SStefan Hajnoczi {
75753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
75853fec9d3SStefan Hajnoczi }
75953fec9d3SStefan Hajnoczi 
76053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
76153fec9d3SStefan Hajnoczi {
76253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
76353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
76453fec9d3SStefan Hajnoczi }
76553fec9d3SStefan Hajnoczi 
7667b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7677b272452SKevin Wolf {
7687b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7697b272452SKevin Wolf 
770b998875dSKevin Wolf     /* The backing file of a temporary snapshot is read-only */
771b998875dSKevin Wolf     if (flags & BDRV_O_SNAPSHOT) {
772b998875dSKevin Wolf         open_flags &= ~BDRV_O_RDWR;
773b998875dSKevin Wolf     }
774b998875dSKevin Wolf 
7757b272452SKevin Wolf     /*
7767b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7777b272452SKevin Wolf      * image.
7787b272452SKevin Wolf      */
7797b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7807b272452SKevin Wolf 
7817b272452SKevin Wolf     /*
7827b272452SKevin Wolf      * Snapshots should be writable.
7837b272452SKevin Wolf      */
7847b272452SKevin Wolf     if (bs->is_temporary) {
7857b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7867b272452SKevin Wolf     }
7877b272452SKevin Wolf 
7887b272452SKevin Wolf     return open_flags;
7897b272452SKevin Wolf }
7907b272452SKevin Wolf 
7916913c0c2SBenoît Canet static int bdrv_assign_node_name(BlockDriverState *bs,
7926913c0c2SBenoît Canet                                  const char *node_name,
7936913c0c2SBenoît Canet                                  Error **errp)
7946913c0c2SBenoît Canet {
7956913c0c2SBenoît Canet     if (!node_name) {
7966913c0c2SBenoît Canet         return 0;
7976913c0c2SBenoît Canet     }
7986913c0c2SBenoît Canet 
7996913c0c2SBenoît Canet     /* empty string node name is invalid */
8006913c0c2SBenoît Canet     if (node_name[0] == '\0') {
8016913c0c2SBenoît Canet         error_setg(errp, "Empty node name");
8026913c0c2SBenoît Canet         return -EINVAL;
8036913c0c2SBenoît Canet     }
8046913c0c2SBenoît Canet 
8050c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8060c5e94eeSBenoît Canet     if (bdrv_find(node_name)) {
8070c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8080c5e94eeSBenoît Canet                    node_name);
8090c5e94eeSBenoît Canet         return -EINVAL;
8100c5e94eeSBenoît Canet     }
8110c5e94eeSBenoît Canet 
8126913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8136913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8146913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
8156913c0c2SBenoît Canet         return -EINVAL;
8166913c0c2SBenoît Canet     }
8176913c0c2SBenoît Canet 
8186913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8196913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8206913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
8216913c0c2SBenoît Canet 
8226913c0c2SBenoît Canet     return 0;
8236913c0c2SBenoît Canet }
8246913c0c2SBenoît Canet 
825b6ce07aaSKevin Wolf /*
82657915332SKevin Wolf  * Common part for opening disk images and files
827b6ad491aSKevin Wolf  *
828b6ad491aSKevin Wolf  * Removes all processed options from *options.
82957915332SKevin Wolf  */
830f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
83134b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
83257915332SKevin Wolf {
83357915332SKevin Wolf     int ret, open_flags;
834035fccdfSKevin Wolf     const char *filename;
8356913c0c2SBenoît Canet     const char *node_name = NULL;
83634b5d2c6SMax Reitz     Error *local_err = NULL;
83757915332SKevin Wolf 
83857915332SKevin Wolf     assert(drv != NULL);
8396405875cSPaolo Bonzini     assert(bs->file == NULL);
840707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
84157915332SKevin Wolf 
84245673671SKevin Wolf     if (file != NULL) {
84345673671SKevin Wolf         filename = file->filename;
84445673671SKevin Wolf     } else {
84545673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
84645673671SKevin Wolf     }
84745673671SKevin Wolf 
848765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
849765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
850765003dbSKevin Wolf                    drv->format_name);
851765003dbSKevin Wolf         return -EINVAL;
852765003dbSKevin Wolf     }
853765003dbSKevin Wolf 
85445673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
85528dcee10SStefan Hajnoczi 
8566913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
8576913c0c2SBenoît Canet     ret = bdrv_assign_node_name(bs, node_name, errp);
8586913c0c2SBenoît Canet     if (ret < 0) {
8596913c0c2SBenoît Canet         return ret;
8606913c0c2SBenoît Canet     }
8616913c0c2SBenoît Canet     qdict_del(options, "node-name");
8626913c0c2SBenoît Canet 
8635d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
8645d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
8655d186eb0SKevin Wolf      * and return immediately. */
8665d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
8675d186eb0SKevin Wolf         bdrv_swap(file, bs);
8685d186eb0SKevin Wolf         return 0;
8695d186eb0SKevin Wolf     }
8705d186eb0SKevin Wolf 
87157915332SKevin Wolf     bs->open_flags = flags;
8721b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
873c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8740d51b4deSAsias He     bs->zero_beyond_eof = true;
875b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
876b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
877b64ec4e4SFam Zheng 
878b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8798f94a6e4SKevin Wolf         error_setg(errp,
8808f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8818f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8828f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8838f94a6e4SKevin Wolf                    drv->format_name);
884b64ec4e4SFam Zheng         return -ENOTSUP;
885b64ec4e4SFam Zheng     }
88657915332SKevin Wolf 
88753fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8880ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8890ebd24e0SKevin Wolf         if (!bs->read_only) {
89053fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8910ebd24e0SKevin Wolf         } else {
8920ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
8930ebd24e0SKevin Wolf             return -EINVAL;
8940ebd24e0SKevin Wolf         }
89553fec9d3SStefan Hajnoczi     }
89653fec9d3SStefan Hajnoczi 
897c2ad1b0cSKevin Wolf     if (filename != NULL) {
89857915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
899c2ad1b0cSKevin Wolf     } else {
900c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
901c2ad1b0cSKevin Wolf     }
90257915332SKevin Wolf 
90357915332SKevin Wolf     bs->drv = drv;
9047267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
90557915332SKevin Wolf 
90603f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
907e7c63796SStefan Hajnoczi 
90866f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
90966f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9105d186eb0SKevin Wolf         assert(file == NULL);
911030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
91234b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
913f500a6d3SKevin Wolf     } else {
9142af5ef70SKevin Wolf         if (file == NULL) {
91534b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
91634b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9172af5ef70SKevin Wolf             ret = -EINVAL;
9182af5ef70SKevin Wolf             goto free_and_fail;
9192af5ef70SKevin Wolf         }
920f500a6d3SKevin Wolf         bs->file = file;
92134b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
92266f82ceeSKevin Wolf     }
92366f82ceeSKevin Wolf 
92457915332SKevin Wolf     if (ret < 0) {
92584d18f06SMarkus Armbruster         if (local_err) {
92634b5d2c6SMax Reitz             error_propagate(errp, local_err);
9272fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9282fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
92934b5d2c6SMax Reitz         } else {
93034b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
93134b5d2c6SMax Reitz         }
93257915332SKevin Wolf         goto free_and_fail;
93357915332SKevin Wolf     }
93457915332SKevin Wolf 
93551762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
93651762288SStefan Hajnoczi     if (ret < 0) {
93734b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
93851762288SStefan Hajnoczi         goto free_and_fail;
93957915332SKevin Wolf     }
94051762288SStefan Hajnoczi 
941d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
942c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
94347ea2de2SKevin Wolf     assert((bs->request_alignment != 0) || bs->sg);
944d34682cdSKevin Wolf 
94557915332SKevin Wolf #ifndef _WIN32
94657915332SKevin Wolf     if (bs->is_temporary) {
947d4cea8dfSDunrong Huang         assert(bs->filename[0] != '\0');
948d4cea8dfSDunrong Huang         unlink(bs->filename);
94957915332SKevin Wolf     }
95057915332SKevin Wolf #endif
95157915332SKevin Wolf     return 0;
95257915332SKevin Wolf 
95357915332SKevin Wolf free_and_fail:
95466f82ceeSKevin Wolf     bs->file = NULL;
9557267c094SAnthony Liguori     g_free(bs->opaque);
95657915332SKevin Wolf     bs->opaque = NULL;
95757915332SKevin Wolf     bs->drv = NULL;
95857915332SKevin Wolf     return ret;
95957915332SKevin Wolf }
96057915332SKevin Wolf 
96157915332SKevin Wolf /*
962b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
963787e4a85SKevin Wolf  *
9645acd9d81SMax Reitz  * options is an indirect pointer to a QDict of options to pass to the block
9655acd9d81SMax Reitz  * drivers, or pointer to NULL for an empty set of options. If this function
9665acd9d81SMax Reitz  * takes ownership of the QDict reference, it will set *options to NULL;
9675acd9d81SMax Reitz  * otherwise, it will contain unused/unrecognized options after this function
9685acd9d81SMax Reitz  * returns. Then, the caller is responsible for freeing it. If it intends to
9695acd9d81SMax Reitz  * reuse the QDict, QINCREF() should be called beforehand.
970b6ce07aaSKevin Wolf  */
971d4446eaeSMax Reitz static int bdrv_file_open(BlockDriverState *bs, const char *filename,
9725acd9d81SMax Reitz                           QDict **options, int flags, Error **errp)
973b338082bSbellard {
9746db95603SChristoph Hellwig     BlockDriver *drv;
975c2ad1b0cSKevin Wolf     const char *drvname;
976e3fa4bfaSKevin Wolf     bool parse_filename = false;
97734b5d2c6SMax Reitz     Error *local_err = NULL;
97883f64091Sbellard     int ret;
9793b0d4f61Sbellard 
980035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
981035fccdfSKevin Wolf     if (!filename) {
9825acd9d81SMax Reitz         filename = qdict_get_try_str(*options, "filename");
9835acd9d81SMax Reitz     } else if (filename && !qdict_haskey(*options, "filename")) {
9845acd9d81SMax Reitz         qdict_put(*options, "filename", qstring_from_str(filename));
985e3fa4bfaSKevin Wolf         parse_filename = true;
986035fccdfSKevin Wolf     } else {
98734b5d2c6SMax Reitz         error_setg(errp, "Can't specify 'file' and 'filename' options at the "
98834b5d2c6SMax Reitz                    "same time");
989035fccdfSKevin Wolf         ret = -EINVAL;
990035fccdfSKevin Wolf         goto fail;
991035fccdfSKevin Wolf     }
992035fccdfSKevin Wolf 
993c2ad1b0cSKevin Wolf     /* Find the right block driver */
9945acd9d81SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
995c2ad1b0cSKevin Wolf     if (drvname) {
9968f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
99734b5d2c6SMax Reitz         if (!drv) {
99834b5d2c6SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
99934b5d2c6SMax Reitz         }
10005acd9d81SMax Reitz         qdict_del(*options, "driver");
1001c2ad1b0cSKevin Wolf     } else if (filename) {
1002e3fa4bfaSKevin Wolf         drv = bdrv_find_protocol(filename, parse_filename);
100398289620SKevin Wolf         if (!drv) {
100434b5d2c6SMax Reitz             error_setg(errp, "Unknown protocol");
100598289620SKevin Wolf         }
1006c2ad1b0cSKevin Wolf     } else {
100734b5d2c6SMax Reitz         error_setg(errp, "Must specify either driver or file");
1008c2ad1b0cSKevin Wolf         drv = NULL;
1009c2ad1b0cSKevin Wolf     }
1010c2ad1b0cSKevin Wolf 
1011c2ad1b0cSKevin Wolf     if (!drv) {
101234b5d2c6SMax Reitz         /* errp has been set already */
1013c2ad1b0cSKevin Wolf         ret = -ENOENT;
1014c2ad1b0cSKevin Wolf         goto fail;
1015c2ad1b0cSKevin Wolf     }
1016c2ad1b0cSKevin Wolf 
1017c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
1018e3fa4bfaSKevin Wolf     if (drv->bdrv_parse_filename && parse_filename) {
10195acd9d81SMax Reitz         drv->bdrv_parse_filename(filename, *options, &local_err);
102084d18f06SMarkus Armbruster         if (local_err) {
102134b5d2c6SMax Reitz             error_propagate(errp, local_err);
10226963a30dSKevin Wolf             ret = -EINVAL;
10236963a30dSKevin Wolf             goto fail;
10246963a30dSKevin Wolf         }
1025cd5d031eSMax Reitz 
1026cd5d031eSMax Reitz         if (!drv->bdrv_needs_filename) {
10275acd9d81SMax Reitz             qdict_del(*options, "filename");
1028cd5d031eSMax Reitz         } else {
1029cd5d031eSMax Reitz             filename = qdict_get_str(*options, "filename");
1030cd5d031eSMax Reitz         }
10316963a30dSKevin Wolf     }
10326963a30dSKevin Wolf 
1033505d7583SMax Reitz     if (!drv->bdrv_file_open) {
10345acd9d81SMax Reitz         ret = bdrv_open(&bs, filename, NULL, *options, flags, drv, &local_err);
10355acd9d81SMax Reitz         *options = NULL;
1036505d7583SMax Reitz     } else {
10375acd9d81SMax Reitz         ret = bdrv_open_common(bs, NULL, *options, flags, drv, &local_err);
1038505d7583SMax Reitz     }
1039707ff828SKevin Wolf     if (ret < 0) {
104034b5d2c6SMax Reitz         error_propagate(errp, local_err);
1041707ff828SKevin Wolf         goto fail;
1042707ff828SKevin Wolf     }
1043707ff828SKevin Wolf 
104471d0770cSaliguori     bs->growable = 1;
104583f64091Sbellard     return 0;
1046707ff828SKevin Wolf 
1047707ff828SKevin Wolf fail:
1048707ff828SKevin Wolf     return ret;
10493b0d4f61Sbellard }
10503b0d4f61Sbellard 
105131ca6d07SKevin Wolf /*
105231ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
105331ca6d07SKevin Wolf  *
105431ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
105531ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
105631ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
105731ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
105831ca6d07SKevin Wolf  */
105934b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
10609156df12SPaolo Bonzini {
10619156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
10629156df12SPaolo Bonzini     int back_flags, ret;
10639156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
106434b5d2c6SMax Reitz     Error *local_err = NULL;
10659156df12SPaolo Bonzini 
10669156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
106731ca6d07SKevin Wolf         QDECREF(options);
10689156df12SPaolo Bonzini         return 0;
10699156df12SPaolo Bonzini     }
10709156df12SPaolo Bonzini 
107131ca6d07SKevin Wolf     /* NULL means an empty set of options */
107231ca6d07SKevin Wolf     if (options == NULL) {
107331ca6d07SKevin Wolf         options = qdict_new();
107431ca6d07SKevin Wolf     }
107531ca6d07SKevin Wolf 
10769156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
10771cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
10781cb6f506SKevin Wolf         backing_filename[0] = '\0';
10791cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
108031ca6d07SKevin Wolf         QDECREF(options);
10819156df12SPaolo Bonzini         return 0;
1082dbecebddSFam Zheng     } else {
1083dbecebddSFam Zheng         bdrv_get_full_backing_filename(bs, backing_filename,
1084dbecebddSFam Zheng                                        sizeof(backing_filename));
10859156df12SPaolo Bonzini     }
10869156df12SPaolo Bonzini 
10879156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
10889156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
10899156df12SPaolo Bonzini     }
10909156df12SPaolo Bonzini 
10919156df12SPaolo Bonzini     /* backing files always opened read-only */
109287a5debdSThibaut LAURENT     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
109387a5debdSThibaut LAURENT                                     BDRV_O_COPY_ON_READ);
10949156df12SPaolo Bonzini 
1095f67503e5SMax Reitz     assert(bs->backing_hd == NULL);
1096f67503e5SMax Reitz     ret = bdrv_open(&bs->backing_hd,
1097ddf5636dSMax Reitz                     *backing_filename ? backing_filename : NULL, NULL, options,
109834b5d2c6SMax Reitz                     back_flags, back_drv, &local_err);
10999156df12SPaolo Bonzini     if (ret < 0) {
11009156df12SPaolo Bonzini         bs->backing_hd = NULL;
11019156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1102b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1103b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1104b04b6b6eSFam Zheng         error_free(local_err);
11059156df12SPaolo Bonzini         return ret;
11069156df12SPaolo Bonzini     }
1107d80ac658SPeter Feiner 
1108d80ac658SPeter Feiner     if (bs->backing_hd->file) {
110961ed2684SMax Reitz         pstrcpy(bs->backing_file, sizeof(bs->backing_file),
111061ed2684SMax Reitz                 bs->backing_hd->file->filename);
1111d80ac658SPeter Feiner     }
1112d80ac658SPeter Feiner 
1113d34682cdSKevin Wolf     /* Recalculate the BlockLimits with the backing file */
1114d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
1115d34682cdSKevin Wolf 
11169156df12SPaolo Bonzini     return 0;
11179156df12SPaolo Bonzini }
11189156df12SPaolo Bonzini 
1119b6ce07aaSKevin Wolf /*
1120da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1121da557aacSMax Reitz  * device's options.
1122da557aacSMax Reitz  *
1123da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1124da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1125da557aacSMax Reitz  *
1126da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1127da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1128da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1129da557aacSMax Reitz  * BlockdevRef.
1130da557aacSMax Reitz  *
1131da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1132f67503e5SMax Reitz  *
1133f67503e5SMax Reitz  * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
1134da557aacSMax Reitz  */
1135da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1136da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1137f7d9fd8cSMax Reitz                     bool allow_none, Error **errp)
1138da557aacSMax Reitz {
1139da557aacSMax Reitz     QDict *image_options;
1140da557aacSMax Reitz     int ret;
1141da557aacSMax Reitz     char *bdref_key_dot;
1142da557aacSMax Reitz     const char *reference;
1143da557aacSMax Reitz 
1144f67503e5SMax Reitz     assert(pbs);
1145f67503e5SMax Reitz     assert(*pbs == NULL);
1146f67503e5SMax Reitz 
1147da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1148da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1149da557aacSMax Reitz     g_free(bdref_key_dot);
1150da557aacSMax Reitz 
1151da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1152da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1153da557aacSMax Reitz         if (allow_none) {
1154da557aacSMax Reitz             ret = 0;
1155da557aacSMax Reitz         } else {
1156da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1157da557aacSMax Reitz                        bdref_key);
1158da557aacSMax Reitz             ret = -EINVAL;
1159da557aacSMax Reitz         }
1160da557aacSMax Reitz         goto done;
1161da557aacSMax Reitz     }
1162da557aacSMax Reitz 
1163f7d9fd8cSMax Reitz     ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
1164da557aacSMax Reitz 
1165da557aacSMax Reitz done:
1166da557aacSMax Reitz     qdict_del(options, bdref_key);
1167da557aacSMax Reitz     return ret;
1168da557aacSMax Reitz }
1169da557aacSMax Reitz 
1170b998875dSKevin Wolf void bdrv_append_temp_snapshot(BlockDriverState *bs, Error **errp)
1171b998875dSKevin Wolf {
1172b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
1173b998875dSKevin Wolf     char tmp_filename[PATH_MAX + 1];
1174b998875dSKevin Wolf 
1175b998875dSKevin Wolf     int64_t total_size;
1176b998875dSKevin Wolf     BlockDriver *bdrv_qcow2;
1177b998875dSKevin Wolf     QEMUOptionParameter *create_options;
1178b998875dSKevin Wolf     QDict *snapshot_options;
1179b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1180b998875dSKevin Wolf     Error *local_err;
1181b998875dSKevin Wolf     int ret;
1182b998875dSKevin Wolf 
1183b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1184b998875dSKevin Wolf        instead of opening 'filename' directly */
1185b998875dSKevin Wolf 
1186b998875dSKevin Wolf     /* Get the required size from the image */
1187*f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1188*f187743aSKevin Wolf     if (total_size < 0) {
1189*f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
1190*f187743aSKevin Wolf         return;
1191*f187743aSKevin Wolf     }
1192*f187743aSKevin Wolf     total_size &= BDRV_SECTOR_MASK;
1193b998875dSKevin Wolf 
1194b998875dSKevin Wolf     /* Create the temporary image */
1195b998875dSKevin Wolf     ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1196b998875dSKevin Wolf     if (ret < 0) {
1197b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
1198b998875dSKevin Wolf         return;
1199b998875dSKevin Wolf     }
1200b998875dSKevin Wolf 
1201b998875dSKevin Wolf     bdrv_qcow2 = bdrv_find_format("qcow2");
1202b998875dSKevin Wolf     create_options = parse_option_parameters("", bdrv_qcow2->create_options,
1203b998875dSKevin Wolf                                              NULL);
1204b998875dSKevin Wolf 
1205b998875dSKevin Wolf     set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
1206b998875dSKevin Wolf 
1207b998875dSKevin Wolf     ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
1208b998875dSKevin Wolf     free_option_parameters(create_options);
1209b998875dSKevin Wolf     if (ret < 0) {
1210b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1211b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1212b998875dSKevin Wolf                          error_get_pretty(local_err));
1213b998875dSKevin Wolf         error_free(local_err);
1214b998875dSKevin Wolf         return;
1215b998875dSKevin Wolf     }
1216b998875dSKevin Wolf 
1217b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1218b998875dSKevin Wolf     snapshot_options = qdict_new();
1219b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1220b998875dSKevin Wolf               qstring_from_str("file"));
1221b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1222b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1223b998875dSKevin Wolf 
1224b998875dSKevin Wolf     bs_snapshot = bdrv_new("");
1225b998875dSKevin Wolf     bs_snapshot->is_temporary = 1;
1226b998875dSKevin Wolf 
1227b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
1228b998875dSKevin Wolf                     bs->open_flags & ~BDRV_O_SNAPSHOT, bdrv_qcow2, &local_err);
1229b998875dSKevin Wolf     if (ret < 0) {
1230b998875dSKevin Wolf         error_propagate(errp, local_err);
1231b998875dSKevin Wolf         return;
1232b998875dSKevin Wolf     }
1233b998875dSKevin Wolf 
1234b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
1235b998875dSKevin Wolf }
1236b998875dSKevin Wolf 
1237da557aacSMax Reitz /*
1238b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1239de9c0cecSKevin Wolf  *
1240de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1241de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1242de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1243de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1244f67503e5SMax Reitz  *
1245f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1246f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1247ddf5636dSMax Reitz  *
1248ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1249ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1250ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1251b6ce07aaSKevin Wolf  */
1252ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename,
1253ddf5636dSMax Reitz               const char *reference, QDict *options, int flags,
1254ddf5636dSMax Reitz               BlockDriver *drv, Error **errp)
1255ea2384d3Sbellard {
1256b6ce07aaSKevin Wolf     int ret;
1257f67503e5SMax Reitz     BlockDriverState *file = NULL, *bs;
125874fe54f2SKevin Wolf     const char *drvname;
125934b5d2c6SMax Reitz     Error *local_err = NULL;
126033e3963eSbellard 
1261f67503e5SMax Reitz     assert(pbs);
1262f67503e5SMax Reitz 
1263ddf5636dSMax Reitz     if (reference) {
1264ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1265ddf5636dSMax Reitz         QDECREF(options);
1266ddf5636dSMax Reitz 
1267ddf5636dSMax Reitz         if (*pbs) {
1268ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1269ddf5636dSMax Reitz                        "another block device");
1270ddf5636dSMax Reitz             return -EINVAL;
1271ddf5636dSMax Reitz         }
1272ddf5636dSMax Reitz 
1273ddf5636dSMax Reitz         if (filename || options_non_empty) {
1274ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1275ddf5636dSMax Reitz                        "additional options or a new filename");
1276ddf5636dSMax Reitz             return -EINVAL;
1277ddf5636dSMax Reitz         }
1278ddf5636dSMax Reitz 
1279ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1280ddf5636dSMax Reitz         if (!bs) {
1281ddf5636dSMax Reitz             return -ENODEV;
1282ddf5636dSMax Reitz         }
1283ddf5636dSMax Reitz         bdrv_ref(bs);
1284ddf5636dSMax Reitz         *pbs = bs;
1285ddf5636dSMax Reitz         return 0;
1286ddf5636dSMax Reitz     }
1287ddf5636dSMax Reitz 
1288f67503e5SMax Reitz     if (*pbs) {
1289f67503e5SMax Reitz         bs = *pbs;
1290f67503e5SMax Reitz     } else {
1291f67503e5SMax Reitz         bs = bdrv_new("");
1292f67503e5SMax Reitz     }
1293f67503e5SMax Reitz 
1294de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1295de9c0cecSKevin Wolf     if (options == NULL) {
1296de9c0cecSKevin Wolf         options = qdict_new();
1297de9c0cecSKevin Wolf     }
1298de9c0cecSKevin Wolf 
1299de9c0cecSKevin Wolf     bs->options = options;
1300b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1301de9c0cecSKevin Wolf 
13025469a2a6SMax Reitz     if (flags & BDRV_O_PROTOCOL) {
13035469a2a6SMax Reitz         assert(!drv);
13045acd9d81SMax Reitz         ret = bdrv_file_open(bs, filename, &options, flags & ~BDRV_O_PROTOCOL,
13055469a2a6SMax Reitz                              &local_err);
13065469a2a6SMax Reitz         if (!ret) {
1307eb909c7fSKevin Wolf             drv = bs->drv;
13085acd9d81SMax Reitz             goto done;
13095469a2a6SMax Reitz         } else if (bs->drv) {
13105469a2a6SMax Reitz             goto close_and_fail;
13115469a2a6SMax Reitz         } else {
13125469a2a6SMax Reitz             goto fail;
13135469a2a6SMax Reitz         }
13145469a2a6SMax Reitz     }
13155469a2a6SMax Reitz 
1316f500a6d3SKevin Wolf     /* Open image file without format layer */
1317be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1318be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1319be028adcSJeff Cody     }
1320be028adcSJeff Cody 
1321f67503e5SMax Reitz     assert(file == NULL);
1322054963f8SMax Reitz     ret = bdrv_open_image(&file, filename, options, "file",
1323f7d9fd8cSMax Reitz                           bdrv_open_flags(bs, flags | BDRV_O_UNMAP) |
1324f7d9fd8cSMax Reitz                           BDRV_O_PROTOCOL, true, &local_err);
1325f500a6d3SKevin Wolf     if (ret < 0) {
13269562f69cSMax Reitz         goto unlink_and_fail;
1327f500a6d3SKevin Wolf     }
1328f500a6d3SKevin Wolf 
1329f500a6d3SKevin Wolf     /* Find the right image format driver */
133074fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
133174fe54f2SKevin Wolf     if (drvname) {
13328f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
133374fe54f2SKevin Wolf         qdict_del(options, "driver");
133406d22aa3SKevin Wolf         if (!drv) {
133506d22aa3SKevin Wolf             error_setg(errp, "Invalid driver: '%s'", drvname);
133606d22aa3SKevin Wolf             ret = -EINVAL;
133706d22aa3SKevin Wolf             goto unlink_and_fail;
133806d22aa3SKevin Wolf         }
133974fe54f2SKevin Wolf     }
134074fe54f2SKevin Wolf 
1341f500a6d3SKevin Wolf     if (!drv) {
13422a05cbe4SMax Reitz         if (file) {
134334b5d2c6SMax Reitz             ret = find_image_format(file, filename, &drv, &local_err);
13442a05cbe4SMax Reitz         } else {
13452a05cbe4SMax Reitz             error_setg(errp, "Must specify either driver or file");
13462a05cbe4SMax Reitz             ret = -EINVAL;
13472a05cbe4SMax Reitz             goto unlink_and_fail;
13482a05cbe4SMax Reitz         }
1349f500a6d3SKevin Wolf     }
1350f500a6d3SKevin Wolf 
1351f500a6d3SKevin Wolf     if (!drv) {
1352f500a6d3SKevin Wolf         goto unlink_and_fail;
1353f500a6d3SKevin Wolf     }
1354f500a6d3SKevin Wolf 
1355b6ce07aaSKevin Wolf     /* Open the image */
135634b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1357b6ce07aaSKevin Wolf     if (ret < 0) {
13586987307cSChristoph Hellwig         goto unlink_and_fail;
13596987307cSChristoph Hellwig     }
13606987307cSChristoph Hellwig 
13612a05cbe4SMax Reitz     if (file && (bs->file != file)) {
13624f6fd349SFam Zheng         bdrv_unref(file);
1363f500a6d3SKevin Wolf         file = NULL;
1364f500a6d3SKevin Wolf     }
1365f500a6d3SKevin Wolf 
1366b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
13679156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
136831ca6d07SKevin Wolf         QDict *backing_options;
136931ca6d07SKevin Wolf 
13705726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
137134b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1372b6ce07aaSKevin Wolf         if (ret < 0) {
1373b6ad491aSKevin Wolf             goto close_and_fail;
1374b6ce07aaSKevin Wolf         }
1375b6ce07aaSKevin Wolf     }
1376b6ce07aaSKevin Wolf 
1377b998875dSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1378b998875dSKevin Wolf      * temporary snapshot afterwards. */
1379b998875dSKevin Wolf     if (flags & BDRV_O_SNAPSHOT) {
1380b998875dSKevin Wolf         bdrv_append_temp_snapshot(bs, &local_err);
1381b998875dSKevin Wolf         if (local_err) {
1382b998875dSKevin Wolf             error_propagate(errp, local_err);
1383b998875dSKevin Wolf             goto close_and_fail;
1384b998875dSKevin Wolf         }
1385b998875dSKevin Wolf     }
1386b998875dSKevin Wolf 
1387b998875dSKevin Wolf 
13885acd9d81SMax Reitz done:
1389b6ad491aSKevin Wolf     /* Check if any unknown options were used */
13905acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1391b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
13925acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
13935acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
13945acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
13955acd9d81SMax Reitz         } else {
139634b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
13975acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
13985acd9d81SMax Reitz                        bs->device_name, entry->key);
13995acd9d81SMax Reitz         }
1400b6ad491aSKevin Wolf 
1401b6ad491aSKevin Wolf         ret = -EINVAL;
1402b6ad491aSKevin Wolf         goto close_and_fail;
1403b6ad491aSKevin Wolf     }
1404b6ad491aSKevin Wolf 
1405b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
14067d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1407c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1408c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1409c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1410c3adb58fSMarkus Armbruster         error_setg(errp,
1411c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1412c3adb58fSMarkus Armbruster         ret = -EBUSY;
1413c3adb58fSMarkus Armbruster         goto close_and_fail;
1414b6ce07aaSKevin Wolf     }
1415b6ce07aaSKevin Wolf 
1416c3adb58fSMarkus Armbruster     QDECREF(options);
1417f67503e5SMax Reitz     *pbs = bs;
1418b6ce07aaSKevin Wolf     return 0;
1419b6ce07aaSKevin Wolf 
1420b6ce07aaSKevin Wolf unlink_and_fail:
1421f500a6d3SKevin Wolf     if (file != NULL) {
14224f6fd349SFam Zheng         bdrv_unref(file);
1423f500a6d3SKevin Wolf     }
1424b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1425b6ce07aaSKevin Wolf         unlink(filename);
1426b6ce07aaSKevin Wolf     }
1427de9c0cecSKevin Wolf fail:
1428de9c0cecSKevin Wolf     QDECREF(bs->options);
1429b6ad491aSKevin Wolf     QDECREF(options);
1430de9c0cecSKevin Wolf     bs->options = NULL;
1431f67503e5SMax Reitz     if (!*pbs) {
1432f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1433f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1434f67503e5SMax Reitz            since it has not really been opened yet. */
1435f67503e5SMax Reitz         bdrv_unref(bs);
1436f67503e5SMax Reitz     }
143784d18f06SMarkus Armbruster     if (local_err) {
143834b5d2c6SMax Reitz         error_propagate(errp, local_err);
143934b5d2c6SMax Reitz     }
1440b6ad491aSKevin Wolf     return ret;
1441de9c0cecSKevin Wolf 
1442b6ad491aSKevin Wolf close_and_fail:
1443f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1444f67503e5SMax Reitz     if (*pbs) {
1445b6ad491aSKevin Wolf         bdrv_close(bs);
1446f67503e5SMax Reitz     } else {
1447f67503e5SMax Reitz         bdrv_unref(bs);
1448f67503e5SMax Reitz     }
1449b6ad491aSKevin Wolf     QDECREF(options);
145084d18f06SMarkus Armbruster     if (local_err) {
145134b5d2c6SMax Reitz         error_propagate(errp, local_err);
145234b5d2c6SMax Reitz     }
1453b6ce07aaSKevin Wolf     return ret;
1454b6ce07aaSKevin Wolf }
1455b6ce07aaSKevin Wolf 
1456e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1457e971aa12SJeff Cody      bool prepared;
1458e971aa12SJeff Cody      BDRVReopenState state;
1459e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1460e971aa12SJeff Cody } BlockReopenQueueEntry;
1461e971aa12SJeff Cody 
1462e971aa12SJeff Cody /*
1463e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1464e971aa12SJeff Cody  * reopen of multiple devices.
1465e971aa12SJeff Cody  *
1466e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1467e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1468e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1469e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1470e971aa12SJeff Cody  * atomic 'set'.
1471e971aa12SJeff Cody  *
1472e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1473e971aa12SJeff Cody  *
1474e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1475e971aa12SJeff Cody  *
1476e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1477e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1478e971aa12SJeff Cody  *
1479e971aa12SJeff Cody  */
1480e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1481e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1482e971aa12SJeff Cody {
1483e971aa12SJeff Cody     assert(bs != NULL);
1484e971aa12SJeff Cody 
1485e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1486e971aa12SJeff Cody     if (bs_queue == NULL) {
1487e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1488e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1489e971aa12SJeff Cody     }
1490e971aa12SJeff Cody 
1491e971aa12SJeff Cody     if (bs->file) {
1492e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1493e971aa12SJeff Cody     }
1494e971aa12SJeff Cody 
1495e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1496e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1497e971aa12SJeff Cody 
1498e971aa12SJeff Cody     bs_entry->state.bs = bs;
1499e971aa12SJeff Cody     bs_entry->state.flags = flags;
1500e971aa12SJeff Cody 
1501e971aa12SJeff Cody     return bs_queue;
1502e971aa12SJeff Cody }
1503e971aa12SJeff Cody 
1504e971aa12SJeff Cody /*
1505e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1506e971aa12SJeff Cody  *
1507e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1508e971aa12SJeff Cody  * via bdrv_reopen_queue().
1509e971aa12SJeff Cody  *
1510e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1511e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1512e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1513e971aa12SJeff Cody  * data cleaned up.
1514e971aa12SJeff Cody  *
1515e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1516e971aa12SJeff Cody  * to all devices.
1517e971aa12SJeff Cody  *
1518e971aa12SJeff Cody  */
1519e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1520e971aa12SJeff Cody {
1521e971aa12SJeff Cody     int ret = -1;
1522e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1523e971aa12SJeff Cody     Error *local_err = NULL;
1524e971aa12SJeff Cody 
1525e971aa12SJeff Cody     assert(bs_queue != NULL);
1526e971aa12SJeff Cody 
1527e971aa12SJeff Cody     bdrv_drain_all();
1528e971aa12SJeff Cody 
1529e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1530e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1531e971aa12SJeff Cody             error_propagate(errp, local_err);
1532e971aa12SJeff Cody             goto cleanup;
1533e971aa12SJeff Cody         }
1534e971aa12SJeff Cody         bs_entry->prepared = true;
1535e971aa12SJeff Cody     }
1536e971aa12SJeff Cody 
1537e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1538e971aa12SJeff Cody      * changes
1539e971aa12SJeff Cody      */
1540e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1541e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1542e971aa12SJeff Cody     }
1543e971aa12SJeff Cody 
1544e971aa12SJeff Cody     ret = 0;
1545e971aa12SJeff Cody 
1546e971aa12SJeff Cody cleanup:
1547e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1548e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1549e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1550e971aa12SJeff Cody         }
1551e971aa12SJeff Cody         g_free(bs_entry);
1552e971aa12SJeff Cody     }
1553e971aa12SJeff Cody     g_free(bs_queue);
1554e971aa12SJeff Cody     return ret;
1555e971aa12SJeff Cody }
1556e971aa12SJeff Cody 
1557e971aa12SJeff Cody 
1558e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1559e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1560e971aa12SJeff Cody {
1561e971aa12SJeff Cody     int ret = -1;
1562e971aa12SJeff Cody     Error *local_err = NULL;
1563e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1564e971aa12SJeff Cody 
1565e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1566e971aa12SJeff Cody     if (local_err != NULL) {
1567e971aa12SJeff Cody         error_propagate(errp, local_err);
1568e971aa12SJeff Cody     }
1569e971aa12SJeff Cody     return ret;
1570e971aa12SJeff Cody }
1571e971aa12SJeff Cody 
1572e971aa12SJeff Cody 
1573e971aa12SJeff Cody /*
1574e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1575e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1576e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1577e971aa12SJeff Cody  *
1578e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1579e971aa12SJeff Cody  * flags are the new open flags
1580e971aa12SJeff Cody  * queue is the reopen queue
1581e971aa12SJeff Cody  *
1582e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1583e971aa12SJeff Cody  * as well.
1584e971aa12SJeff Cody  *
1585e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1586e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1587e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1588e971aa12SJeff Cody  *
1589e971aa12SJeff Cody  */
1590e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1591e971aa12SJeff Cody                         Error **errp)
1592e971aa12SJeff Cody {
1593e971aa12SJeff Cody     int ret = -1;
1594e971aa12SJeff Cody     Error *local_err = NULL;
1595e971aa12SJeff Cody     BlockDriver *drv;
1596e971aa12SJeff Cody 
1597e971aa12SJeff Cody     assert(reopen_state != NULL);
1598e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1599e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1600e971aa12SJeff Cody 
1601e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1602e971aa12SJeff Cody      * to r/w */
1603e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1604e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1605e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1606e971aa12SJeff Cody                   reopen_state->bs->device_name);
1607e971aa12SJeff Cody         goto error;
1608e971aa12SJeff Cody     }
1609e971aa12SJeff Cody 
1610e971aa12SJeff Cody 
1611e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1612e971aa12SJeff Cody     if (ret) {
1613e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1614e971aa12SJeff Cody                   strerror(-ret));
1615e971aa12SJeff Cody         goto error;
1616e971aa12SJeff Cody     }
1617e971aa12SJeff Cody 
1618e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1619e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1620e971aa12SJeff Cody         if (ret) {
1621e971aa12SJeff Cody             if (local_err != NULL) {
1622e971aa12SJeff Cody                 error_propagate(errp, local_err);
1623e971aa12SJeff Cody             } else {
1624d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1625e971aa12SJeff Cody                            reopen_state->bs->filename);
1626e971aa12SJeff Cody             }
1627e971aa12SJeff Cody             goto error;
1628e971aa12SJeff Cody         }
1629e971aa12SJeff Cody     } else {
1630e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1631e971aa12SJeff Cody          * handler for each supported drv. */
1632e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1633e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1634e971aa12SJeff Cody                  "reopening of file");
1635e971aa12SJeff Cody         ret = -1;
1636e971aa12SJeff Cody         goto error;
1637e971aa12SJeff Cody     }
1638e971aa12SJeff Cody 
1639e971aa12SJeff Cody     ret = 0;
1640e971aa12SJeff Cody 
1641e971aa12SJeff Cody error:
1642e971aa12SJeff Cody     return ret;
1643e971aa12SJeff Cody }
1644e971aa12SJeff Cody 
1645e971aa12SJeff Cody /*
1646e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1647e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1648e971aa12SJeff Cody  * the active BlockDriverState contents.
1649e971aa12SJeff Cody  */
1650e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1651e971aa12SJeff Cody {
1652e971aa12SJeff Cody     BlockDriver *drv;
1653e971aa12SJeff Cody 
1654e971aa12SJeff Cody     assert(reopen_state != NULL);
1655e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1656e971aa12SJeff Cody     assert(drv != NULL);
1657e971aa12SJeff Cody 
1658e971aa12SJeff Cody     /* If there are any driver level actions to take */
1659e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1660e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1661e971aa12SJeff Cody     }
1662e971aa12SJeff Cody 
1663e971aa12SJeff Cody     /* set BDS specific flags now */
1664e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1665e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1666e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1667e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1668355ef4acSKevin Wolf 
1669355ef4acSKevin Wolf     bdrv_refresh_limits(reopen_state->bs);
1670e971aa12SJeff Cody }
1671e971aa12SJeff Cody 
1672e971aa12SJeff Cody /*
1673e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1674e971aa12SJeff Cody  * reopen_state
1675e971aa12SJeff Cody  */
1676e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1677e971aa12SJeff Cody {
1678e971aa12SJeff Cody     BlockDriver *drv;
1679e971aa12SJeff Cody 
1680e971aa12SJeff Cody     assert(reopen_state != NULL);
1681e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1682e971aa12SJeff Cody     assert(drv != NULL);
1683e971aa12SJeff Cody 
1684e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1685e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1686e971aa12SJeff Cody     }
1687e971aa12SJeff Cody }
1688e971aa12SJeff Cody 
1689e971aa12SJeff Cody 
1690fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1691fc01f7e7Sbellard {
16923e914655SPaolo Bonzini     if (bs->job) {
16933e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
16943e914655SPaolo Bonzini     }
169558fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
169658fda173SStefan Hajnoczi     bdrv_flush(bs);
169758fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1698d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
16997094f12fSKevin Wolf 
17003cbc002cSPaolo Bonzini     if (bs->drv) {
1701557df6acSStefan Hajnoczi         if (bs->backing_hd) {
17024f6fd349SFam Zheng             bdrv_unref(bs->backing_hd);
1703557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1704557df6acSStefan Hajnoczi         }
1705ea2384d3Sbellard         bs->drv->bdrv_close(bs);
17067267c094SAnthony Liguori         g_free(bs->opaque);
1707ea2384d3Sbellard #ifdef _WIN32
1708ea2384d3Sbellard         if (bs->is_temporary) {
1709ea2384d3Sbellard             unlink(bs->filename);
1710ea2384d3Sbellard         }
171167b915a5Sbellard #endif
1712ea2384d3Sbellard         bs->opaque = NULL;
1713ea2384d3Sbellard         bs->drv = NULL;
171453fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1715a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1716a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
17176405875cSPaolo Bonzini         bs->total_sectors = 0;
17186405875cSPaolo Bonzini         bs->encrypted = 0;
17196405875cSPaolo Bonzini         bs->valid_key = 0;
17206405875cSPaolo Bonzini         bs->sg = 0;
17216405875cSPaolo Bonzini         bs->growable = 0;
17220d51b4deSAsias He         bs->zero_beyond_eof = false;
1723de9c0cecSKevin Wolf         QDECREF(bs->options);
1724de9c0cecSKevin Wolf         bs->options = NULL;
1725b338082bSbellard 
172666f82ceeSKevin Wolf         if (bs->file != NULL) {
17274f6fd349SFam Zheng             bdrv_unref(bs->file);
17280ac9377dSPaolo Bonzini             bs->file = NULL;
172966f82ceeSKevin Wolf         }
17309ca11154SPavel Hrdina     }
173166f82ceeSKevin Wolf 
17327d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
173398f90dbaSZhi Yong Wu 
173498f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
173598f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
173698f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
173798f90dbaSZhi Yong Wu     }
1738b338082bSbellard }
1739b338082bSbellard 
17402bc93fedSMORITA Kazutaka void bdrv_close_all(void)
17412bc93fedSMORITA Kazutaka {
17422bc93fedSMORITA Kazutaka     BlockDriverState *bs;
17432bc93fedSMORITA Kazutaka 
1744dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17452bc93fedSMORITA Kazutaka         bdrv_close(bs);
17462bc93fedSMORITA Kazutaka     }
17472bc93fedSMORITA Kazutaka }
17482bc93fedSMORITA Kazutaka 
174988266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
175088266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
175188266f5aSStefan Hajnoczi {
175288266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
175388266f5aSStefan Hajnoczi         return true;
175488266f5aSStefan Hajnoczi     }
1755cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1756cc0681c4SBenoît Canet         return true;
1757cc0681c4SBenoît Canet     }
1758cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
175988266f5aSStefan Hajnoczi         return true;
176088266f5aSStefan Hajnoczi     }
176188266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
176288266f5aSStefan Hajnoczi         return true;
176388266f5aSStefan Hajnoczi     }
176488266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
176588266f5aSStefan Hajnoczi         return true;
176688266f5aSStefan Hajnoczi     }
176788266f5aSStefan Hajnoczi     return false;
176888266f5aSStefan Hajnoczi }
176988266f5aSStefan Hajnoczi 
177088266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
177188266f5aSStefan Hajnoczi {
177288266f5aSStefan Hajnoczi     BlockDriverState *bs;
1773dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
177488266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
177588266f5aSStefan Hajnoczi             return true;
177688266f5aSStefan Hajnoczi         }
177788266f5aSStefan Hajnoczi     }
177888266f5aSStefan Hajnoczi     return false;
177988266f5aSStefan Hajnoczi }
178088266f5aSStefan Hajnoczi 
1781922453bcSStefan Hajnoczi /*
1782922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1783922453bcSStefan Hajnoczi  *
1784922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1785922453bcSStefan Hajnoczi  * after calling this function.
17864c355d53SZhi Yong Wu  *
17874c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
17884c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
17894c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
17904c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
17914c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1792922453bcSStefan Hajnoczi  */
1793922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1794922453bcSStefan Hajnoczi {
179588266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
179688266f5aSStefan Hajnoczi     bool busy = true;
1797922453bcSStefan Hajnoczi     BlockDriverState *bs;
1798922453bcSStefan Hajnoczi 
179988266f5aSStefan Hajnoczi     while (busy) {
1800dc364f4cSBenoît Canet         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
18010b06ef3bSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
18024c355d53SZhi Yong Wu         }
1803922453bcSStefan Hajnoczi 
180488266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
180588266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1806922453bcSStefan Hajnoczi     }
1807922453bcSStefan Hajnoczi }
1808922453bcSStefan Hajnoczi 
1809dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1810dc364f4cSBenoît Canet  * graph_bdrv_state list.
1811d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1812d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1813d22b2f41SRyan Harper {
1814d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1815dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1816d22b2f41SRyan Harper     }
1817d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1818dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1819dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1820dc364f4cSBenoît Canet     }
1821dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1822d22b2f41SRyan Harper }
1823d22b2f41SRyan Harper 
1824e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1825e023b2e2SPaolo Bonzini {
1826e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1827e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1828e023b2e2SPaolo Bonzini     }
1829e023b2e2SPaolo Bonzini }
1830e023b2e2SPaolo Bonzini 
18314ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
18324ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
18334ddc07caSPaolo Bonzini {
18344ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
18354ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
18364ddc07caSPaolo Bonzini 
18374ddc07caSPaolo Bonzini     /* dev info */
18384ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
18394ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
18404ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
18411b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
18424ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
18434ddc07caSPaolo Bonzini 
18444ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
18454ddc07caSPaolo Bonzini 
1846cc0681c4SBenoît Canet     /* i/o throttled req */
1847cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1848cc0681c4SBenoît Canet            &bs_src->throttle_state,
1849cc0681c4SBenoît Canet            sizeof(ThrottleState));
1850cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1851cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
18524ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
18534ddc07caSPaolo Bonzini 
18544ddc07caSPaolo Bonzini     /* r/w error */
18554ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
18564ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
18574ddc07caSPaolo Bonzini 
18584ddc07caSPaolo Bonzini     /* i/o status */
18594ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
18604ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
18614ddc07caSPaolo Bonzini 
18624ddc07caSPaolo Bonzini     /* dirty bitmap */
1863e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
18644ddc07caSPaolo Bonzini 
18659fcb0251SFam Zheng     /* reference count */
18669fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
18679fcb0251SFam Zheng 
18684ddc07caSPaolo Bonzini     /* job */
18694ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
18704ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
18714ddc07caSPaolo Bonzini 
18724ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
18734ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
18744ddc07caSPaolo Bonzini             bs_src->device_name);
1875dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
18764ddc07caSPaolo Bonzini }
18774ddc07caSPaolo Bonzini 
18784ddc07caSPaolo Bonzini /*
18794ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
18804ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
18814ddc07caSPaolo Bonzini  * actually attached to a device.
18824ddc07caSPaolo Bonzini  *
18834ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
18844ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
18854ddc07caSPaolo Bonzini  *
18864ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
18874ddc07caSPaolo Bonzini  *
18884ddc07caSPaolo Bonzini  * This function does not create any image files.
18894ddc07caSPaolo Bonzini  */
18904ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
18914ddc07caSPaolo Bonzini {
18924ddc07caSPaolo Bonzini     BlockDriverState tmp;
18934ddc07caSPaolo Bonzini 
189490ce8a06SBenoît Canet     /* The code needs to swap the node_name but simply swapping node_list won't
189590ce8a06SBenoît Canet      * work so first remove the nodes from the graph list, do the swap then
189690ce8a06SBenoît Canet      * insert them back if needed.
189790ce8a06SBenoît Canet      */
189890ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
189990ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
190090ce8a06SBenoît Canet     }
190190ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
190290ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
190390ce8a06SBenoît Canet     }
190490ce8a06SBenoît Canet 
19054ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
19064ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
1907e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
19084ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
19094ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
19104ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
19114ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1912cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
19134ddc07caSPaolo Bonzini 
19144ddc07caSPaolo Bonzini     tmp = *bs_new;
19154ddc07caSPaolo Bonzini     *bs_new = *bs_old;
19164ddc07caSPaolo Bonzini     *bs_old = tmp;
19174ddc07caSPaolo Bonzini 
19184ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
19194ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
19204ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
19214ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
19224ddc07caSPaolo Bonzini 
19234ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
19244ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
19254ddc07caSPaolo Bonzini 
19264ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
19274ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
19284ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
19294ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
19304ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1931cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
19324ddc07caSPaolo Bonzini 
193390ce8a06SBenoît Canet     /* insert the nodes back into the graph node list if needed */
193490ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
193590ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
193690ce8a06SBenoît Canet     }
193790ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
193890ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
193990ce8a06SBenoît Canet     }
194090ce8a06SBenoît Canet 
19414ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
19424ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
19434ddc07caSPaolo Bonzini }
19444ddc07caSPaolo Bonzini 
19458802d1fdSJeff Cody /*
19468802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
19478802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
19488802d1fdSJeff Cody  *
19498802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
19508802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
19518802d1fdSJeff Cody  *
1952f6801b83SJeff Cody  * bs_new is required to be anonymous.
1953f6801b83SJeff Cody  *
19548802d1fdSJeff Cody  * This function does not create any image files.
19558802d1fdSJeff Cody  */
19568802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
19578802d1fdSJeff Cody {
19584ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
19598802d1fdSJeff Cody 
19608802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
19618802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
19624ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
19634ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
19644ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
19654ddc07caSPaolo Bonzini             bs_new->filename);
19664ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
19674ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
19688802d1fdSJeff Cody }
19698802d1fdSJeff Cody 
19704f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
1971b338082bSbellard {
1972fa879d62SMarkus Armbruster     assert(!bs->dev);
19733e914655SPaolo Bonzini     assert(!bs->job);
19743e914655SPaolo Bonzini     assert(!bs->in_use);
19754f6fd349SFam Zheng     assert(!bs->refcnt);
1976e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
197718846deeSMarkus Armbruster 
1978e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1979e1b5c52eSStefan Hajnoczi 
19801b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1981d22b2f41SRyan Harper     bdrv_make_anon(bs);
198234c6f050Saurel32 
19837267c094SAnthony Liguori     g_free(bs);
1984fc01f7e7Sbellard }
1985fc01f7e7Sbellard 
1986fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1987fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
198818846deeSMarkus Armbruster {
1989fa879d62SMarkus Armbruster     if (bs->dev) {
199018846deeSMarkus Armbruster         return -EBUSY;
199118846deeSMarkus Armbruster     }
1992fa879d62SMarkus Armbruster     bs->dev = dev;
199328a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
199418846deeSMarkus Armbruster     return 0;
199518846deeSMarkus Armbruster }
199618846deeSMarkus Armbruster 
1997fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1998fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
199918846deeSMarkus Armbruster {
2000fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
2001fa879d62SMarkus Armbruster         abort();
2002fa879d62SMarkus Armbruster     }
2003fa879d62SMarkus Armbruster }
2004fa879d62SMarkus Armbruster 
2005fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
2006fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
2007fa879d62SMarkus Armbruster {
2008fa879d62SMarkus Armbruster     assert(bs->dev == dev);
2009fa879d62SMarkus Armbruster     bs->dev = NULL;
20100e49de52SMarkus Armbruster     bs->dev_ops = NULL;
20110e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
20121b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
201318846deeSMarkus Armbruster }
201418846deeSMarkus Armbruster 
2015fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
2016fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
201718846deeSMarkus Armbruster {
2018fa879d62SMarkus Armbruster     return bs->dev;
201918846deeSMarkus Armbruster }
202018846deeSMarkus Armbruster 
20210e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
20220e49de52SMarkus Armbruster                       void *opaque)
20230e49de52SMarkus Armbruster {
20240e49de52SMarkus Armbruster     bs->dev_ops = ops;
20250e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
20260e49de52SMarkus Armbruster }
20270e49de52SMarkus Armbruster 
202832c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
202932c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
20301ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
2031329c0a48SLuiz Capitulino {
2032329c0a48SLuiz Capitulino     QObject *data;
2033329c0a48SLuiz Capitulino     const char *action_str;
2034329c0a48SLuiz Capitulino 
2035329c0a48SLuiz Capitulino     switch (action) {
2036329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
2037329c0a48SLuiz Capitulino         action_str = "report";
2038329c0a48SLuiz Capitulino         break;
2039329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
2040329c0a48SLuiz Capitulino         action_str = "ignore";
2041329c0a48SLuiz Capitulino         break;
2042329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
2043329c0a48SLuiz Capitulino         action_str = "stop";
2044329c0a48SLuiz Capitulino         break;
2045329c0a48SLuiz Capitulino     default:
2046329c0a48SLuiz Capitulino         abort();
2047329c0a48SLuiz Capitulino     }
2048329c0a48SLuiz Capitulino 
2049329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
2050329c0a48SLuiz Capitulino                               bdrv->device_name,
2051329c0a48SLuiz Capitulino                               action_str,
2052329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
205332c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
2054329c0a48SLuiz Capitulino 
2055329c0a48SLuiz Capitulino     qobject_decref(data);
2056329c0a48SLuiz Capitulino }
2057329c0a48SLuiz Capitulino 
20586f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
20596f382ed2SLuiz Capitulino {
20606f382ed2SLuiz Capitulino     QObject *data;
20616f382ed2SLuiz Capitulino 
20626f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
20636f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
20646f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
20656f382ed2SLuiz Capitulino 
20666f382ed2SLuiz Capitulino     qobject_decref(data);
20676f382ed2SLuiz Capitulino }
20686f382ed2SLuiz Capitulino 
20697d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
20700e49de52SMarkus Armbruster {
2071145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
20726f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
20737d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
20746f382ed2SLuiz Capitulino         if (tray_was_closed) {
20756f382ed2SLuiz Capitulino             /* tray open */
20766f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
20776f382ed2SLuiz Capitulino         }
20786f382ed2SLuiz Capitulino         if (load) {
20796f382ed2SLuiz Capitulino             /* tray close */
20806f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
20816f382ed2SLuiz Capitulino         }
2082145feb17SMarkus Armbruster     }
2083145feb17SMarkus Armbruster }
2084145feb17SMarkus Armbruster 
20852c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
20862c6942faSMarkus Armbruster {
20872c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
20882c6942faSMarkus Armbruster }
20892c6942faSMarkus Armbruster 
2090025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2091025ccaa7SPaolo Bonzini {
2092025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2093025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2094025ccaa7SPaolo Bonzini     }
2095025ccaa7SPaolo Bonzini }
2096025ccaa7SPaolo Bonzini 
2097e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2098e4def80bSMarkus Armbruster {
2099e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2100e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
2101e4def80bSMarkus Armbruster     }
2102e4def80bSMarkus Armbruster     return false;
2103e4def80bSMarkus Armbruster }
2104e4def80bSMarkus Armbruster 
2105145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
2106145feb17SMarkus Armbruster {
2107145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
2108145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
21090e49de52SMarkus Armbruster     }
21100e49de52SMarkus Armbruster }
21110e49de52SMarkus Armbruster 
2112f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2113f107639aSMarkus Armbruster {
2114f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2115f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2116f107639aSMarkus Armbruster     }
2117f107639aSMarkus Armbruster     return false;
2118f107639aSMarkus Armbruster }
2119f107639aSMarkus Armbruster 
2120e97fc193Saliguori /*
2121e97fc193Saliguori  * Run consistency checks on an image
2122e97fc193Saliguori  *
2123e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2124a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2125e076f338SKevin Wolf  * check are stored in res.
2126e97fc193Saliguori  */
21274534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2128e97fc193Saliguori {
2129e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2130e97fc193Saliguori         return -ENOTSUP;
2131e97fc193Saliguori     }
2132e97fc193Saliguori 
2133e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
21344534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2135e97fc193Saliguori }
2136e97fc193Saliguori 
21378a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
21388a426614SKevin Wolf 
213933e3963eSbellard /* commit COW file into the raw image */
214033e3963eSbellard int bdrv_commit(BlockDriverState *bs)
214133e3963eSbellard {
214219cb3738Sbellard     BlockDriver *drv = bs->drv;
214372706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
21448a426614SKevin Wolf     int n, ro, open_flags;
21450bce597dSJeff Cody     int ret = 0;
214672706ea4SJeff Cody     uint8_t *buf = NULL;
2147c2cba3d9SJim Meyering     char filename[PATH_MAX];
214833e3963eSbellard 
214919cb3738Sbellard     if (!drv)
215019cb3738Sbellard         return -ENOMEDIUM;
215133e3963eSbellard 
21524dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
21534dca4b63SNaphtali Sprei         return -ENOTSUP;
21544dca4b63SNaphtali Sprei     }
21554dca4b63SNaphtali Sprei 
21562d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
21572d3735d3SStefan Hajnoczi         return -EBUSY;
21582d3735d3SStefan Hajnoczi     }
21592d3735d3SStefan Hajnoczi 
21604dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2161c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2162c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
21634dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
21644dca4b63SNaphtali Sprei 
21654dca4b63SNaphtali Sprei     if (ro) {
21660bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
21670bce597dSJeff Cody             return -EACCES;
21684dca4b63SNaphtali Sprei         }
2169ea2384d3Sbellard     }
2170ea2384d3Sbellard 
217172706ea4SJeff Cody     length = bdrv_getlength(bs);
217272706ea4SJeff Cody     if (length < 0) {
217372706ea4SJeff Cody         ret = length;
217472706ea4SJeff Cody         goto ro_cleanup;
217572706ea4SJeff Cody     }
217672706ea4SJeff Cody 
217772706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
217872706ea4SJeff Cody     if (backing_length < 0) {
217972706ea4SJeff Cody         ret = backing_length;
218072706ea4SJeff Cody         goto ro_cleanup;
218172706ea4SJeff Cody     }
218272706ea4SJeff Cody 
218372706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
218472706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
218572706ea4SJeff Cody      * we must return an error */
218672706ea4SJeff Cody     if (length > backing_length) {
218772706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
218872706ea4SJeff Cody         if (ret < 0) {
218972706ea4SJeff Cody             goto ro_cleanup;
219072706ea4SJeff Cody         }
219172706ea4SJeff Cody     }
219272706ea4SJeff Cody 
219372706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
21947267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
21958a426614SKevin Wolf 
21968a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2197d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2198d663640cSPaolo Bonzini         if (ret < 0) {
2199d663640cSPaolo Bonzini             goto ro_cleanup;
2200d663640cSPaolo Bonzini         }
2201d663640cSPaolo Bonzini         if (ret) {
2202dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2203dabfa6ccSKevin Wolf             if (ret < 0) {
22044dca4b63SNaphtali Sprei                 goto ro_cleanup;
220533e3963eSbellard             }
220633e3963eSbellard 
2207dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2208dabfa6ccSKevin Wolf             if (ret < 0) {
22094dca4b63SNaphtali Sprei                 goto ro_cleanup;
221033e3963eSbellard             }
221133e3963eSbellard         }
221233e3963eSbellard     }
221395389c86Sbellard 
22141d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
22151d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2216dabfa6ccSKevin Wolf         if (ret < 0) {
2217dabfa6ccSKevin Wolf             goto ro_cleanup;
2218dabfa6ccSKevin Wolf         }
22191d44952fSChristoph Hellwig         bdrv_flush(bs);
22201d44952fSChristoph Hellwig     }
222195389c86Sbellard 
22223f5075aeSChristoph Hellwig     /*
22233f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
22243f5075aeSChristoph Hellwig      * stable on disk.
22253f5075aeSChristoph Hellwig      */
2226dabfa6ccSKevin Wolf     if (bs->backing_hd) {
22273f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2228dabfa6ccSKevin Wolf     }
22294dca4b63SNaphtali Sprei 
2230dabfa6ccSKevin Wolf     ret = 0;
22314dca4b63SNaphtali Sprei ro_cleanup:
22327267c094SAnthony Liguori     g_free(buf);
22334dca4b63SNaphtali Sprei 
22344dca4b63SNaphtali Sprei     if (ro) {
22350bce597dSJeff Cody         /* ignoring error return here */
22360bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
22374dca4b63SNaphtali Sprei     }
22384dca4b63SNaphtali Sprei 
22391d44952fSChristoph Hellwig     return ret;
224033e3963eSbellard }
224133e3963eSbellard 
2242e8877497SStefan Hajnoczi int bdrv_commit_all(void)
22436ab4b5abSMarkus Armbruster {
22446ab4b5abSMarkus Armbruster     BlockDriverState *bs;
22456ab4b5abSMarkus Armbruster 
2246dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2247272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2248e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2249e8877497SStefan Hajnoczi             if (ret < 0) {
2250e8877497SStefan Hajnoczi                 return ret;
22516ab4b5abSMarkus Armbruster             }
22526ab4b5abSMarkus Armbruster         }
2253272d2d8eSJeff Cody     }
2254e8877497SStefan Hajnoczi     return 0;
2255e8877497SStefan Hajnoczi }
22566ab4b5abSMarkus Armbruster 
2257dbffbdcfSStefan Hajnoczi /**
2258dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2259dbffbdcfSStefan Hajnoczi  *
2260dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2261dbffbdcfSStefan Hajnoczi  */
2262dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2263dbffbdcfSStefan Hajnoczi {
22642dbafdc0SKevin Wolf     if (req->serialising) {
22652dbafdc0SKevin Wolf         req->bs->serialising_in_flight--;
22662dbafdc0SKevin Wolf     }
22672dbafdc0SKevin Wolf 
2268dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2269f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2270dbffbdcfSStefan Hajnoczi }
2271dbffbdcfSStefan Hajnoczi 
2272dbffbdcfSStefan Hajnoczi /**
2273dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2274dbffbdcfSStefan Hajnoczi  */
2275dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2276dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2277793ed47aSKevin Wolf                                   int64_t offset,
2278793ed47aSKevin Wolf                                   unsigned int bytes, bool is_write)
2279dbffbdcfSStefan Hajnoczi {
2280dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2281dbffbdcfSStefan Hajnoczi         .bs = bs,
2282793ed47aSKevin Wolf         .offset         = offset,
2283793ed47aSKevin Wolf         .bytes          = bytes,
2284dbffbdcfSStefan Hajnoczi         .is_write       = is_write,
22855f8b6491SStefan Hajnoczi         .co             = qemu_coroutine_self(),
22862dbafdc0SKevin Wolf         .serialising    = false,
22877327145fSKevin Wolf         .overlap_offset = offset,
22887327145fSKevin Wolf         .overlap_bytes  = bytes,
2289dbffbdcfSStefan Hajnoczi     };
2290dbffbdcfSStefan Hajnoczi 
2291f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2292f4658285SStefan Hajnoczi 
2293dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2294dbffbdcfSStefan Hajnoczi }
2295dbffbdcfSStefan Hajnoczi 
2296e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
22972dbafdc0SKevin Wolf {
22987327145fSKevin Wolf     int64_t overlap_offset = req->offset & ~(align - 1);
2299e96126ffSKevin Wolf     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
23007327145fSKevin Wolf                                - overlap_offset;
23017327145fSKevin Wolf 
23022dbafdc0SKevin Wolf     if (!req->serialising) {
23032dbafdc0SKevin Wolf         req->bs->serialising_in_flight++;
23042dbafdc0SKevin Wolf         req->serialising = true;
23052dbafdc0SKevin Wolf     }
23067327145fSKevin Wolf 
23077327145fSKevin Wolf     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
23087327145fSKevin Wolf     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
23092dbafdc0SKevin Wolf }
23102dbafdc0SKevin Wolf 
2311d83947acSStefan Hajnoczi /**
2312d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2313d83947acSStefan Hajnoczi  */
2314343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2315d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2316d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2317d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2318d83947acSStefan Hajnoczi {
2319d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2320d83947acSStefan Hajnoczi 
2321d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2322d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2323d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2324d83947acSStefan Hajnoczi     } else {
2325d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2326d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2327d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2328d83947acSStefan Hajnoczi                                             nb_sectors, c);
2329d83947acSStefan Hajnoczi     }
2330d83947acSStefan Hajnoczi }
2331d83947acSStefan Hajnoczi 
23327327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs)
2333793ed47aSKevin Wolf {
2334793ed47aSKevin Wolf     BlockDriverInfo bdi;
23357327145fSKevin Wolf     int ret;
2336793ed47aSKevin Wolf 
23377327145fSKevin Wolf     ret = bdrv_get_info(bs, &bdi);
23387327145fSKevin Wolf     if (ret < 0 || bdi.cluster_size == 0) {
23397327145fSKevin Wolf         return bs->request_alignment;
2340793ed47aSKevin Wolf     } else {
23417327145fSKevin Wolf         return bdi.cluster_size;
2342793ed47aSKevin Wolf     }
2343793ed47aSKevin Wolf }
2344793ed47aSKevin Wolf 
2345f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2346793ed47aSKevin Wolf                                      int64_t offset, unsigned int bytes)
2347793ed47aSKevin Wolf {
2348d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
23497327145fSKevin Wolf     if (offset >= req->overlap_offset + req->overlap_bytes) {
2350d83947acSStefan Hajnoczi         return false;
2351d83947acSStefan Hajnoczi     }
2352d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
23537327145fSKevin Wolf     if (req->overlap_offset >= offset + bytes) {
2354d83947acSStefan Hajnoczi         return false;
2355d83947acSStefan Hajnoczi     }
2356d83947acSStefan Hajnoczi     return true;
2357f4658285SStefan Hajnoczi }
2358f4658285SStefan Hajnoczi 
235928de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
2360f4658285SStefan Hajnoczi {
23612dbafdc0SKevin Wolf     BlockDriverState *bs = self->bs;
2362f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2363f4658285SStefan Hajnoczi     bool retry;
236428de2dcdSKevin Wolf     bool waited = false;
2365f4658285SStefan Hajnoczi 
23662dbafdc0SKevin Wolf     if (!bs->serialising_in_flight) {
236728de2dcdSKevin Wolf         return false;
23682dbafdc0SKevin Wolf     }
23692dbafdc0SKevin Wolf 
2370f4658285SStefan Hajnoczi     do {
2371f4658285SStefan Hajnoczi         retry = false;
2372f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
23732dbafdc0SKevin Wolf             if (req == self || (!req->serialising && !self->serialising)) {
237465afd211SKevin Wolf                 continue;
237565afd211SKevin Wolf             }
23767327145fSKevin Wolf             if (tracked_request_overlaps(req, self->overlap_offset,
23777327145fSKevin Wolf                                          self->overlap_bytes))
23787327145fSKevin Wolf             {
23795f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
23805f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
23815f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
23825f8b6491SStefan Hajnoczi                  */
23835f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
23845f8b6491SStefan Hajnoczi 
23856460440fSKevin Wolf                 /* If the request is already (indirectly) waiting for us, or
23866460440fSKevin Wolf                  * will wait for us as soon as it wakes up, then just go on
23876460440fSKevin Wolf                  * (instead of producing a deadlock in the former case). */
23886460440fSKevin Wolf                 if (!req->waiting_for) {
23896460440fSKevin Wolf                     self->waiting_for = req;
2390f4658285SStefan Hajnoczi                     qemu_co_queue_wait(&req->wait_queue);
23916460440fSKevin Wolf                     self->waiting_for = NULL;
2392f4658285SStefan Hajnoczi                     retry = true;
239328de2dcdSKevin Wolf                     waited = true;
2394f4658285SStefan Hajnoczi                     break;
2395f4658285SStefan Hajnoczi                 }
2396f4658285SStefan Hajnoczi             }
23976460440fSKevin Wolf         }
2398f4658285SStefan Hajnoczi     } while (retry);
239928de2dcdSKevin Wolf 
240028de2dcdSKevin Wolf     return waited;
2401f4658285SStefan Hajnoczi }
2402f4658285SStefan Hajnoczi 
2403756e6736SKevin Wolf /*
2404756e6736SKevin Wolf  * Return values:
2405756e6736SKevin Wolf  * 0        - success
2406756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2407756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2408756e6736SKevin Wolf  *            image file header
2409756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2410756e6736SKevin Wolf  */
2411756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2412756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2413756e6736SKevin Wolf {
2414756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2415469ef350SPaolo Bonzini     int ret;
2416756e6736SKevin Wolf 
24175f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
24185f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
24195f377794SPaolo Bonzini         return -EINVAL;
24205f377794SPaolo Bonzini     }
24215f377794SPaolo Bonzini 
2422756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2423469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2424756e6736SKevin Wolf     } else {
2425469ef350SPaolo Bonzini         ret = -ENOTSUP;
2426756e6736SKevin Wolf     }
2427469ef350SPaolo Bonzini 
2428469ef350SPaolo Bonzini     if (ret == 0) {
2429469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2430469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2431469ef350SPaolo Bonzini     }
2432469ef350SPaolo Bonzini     return ret;
2433756e6736SKevin Wolf }
2434756e6736SKevin Wolf 
24356ebdcee2SJeff Cody /*
24366ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
24376ebdcee2SJeff Cody  *
24386ebdcee2SJeff Cody  * active is the current topmost image.
24396ebdcee2SJeff Cody  *
24406ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
24416ebdcee2SJeff Cody  * or if active == bs.
24426ebdcee2SJeff Cody  */
24436ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
24446ebdcee2SJeff Cody                                     BlockDriverState *bs)
24456ebdcee2SJeff Cody {
24466ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
24476ebdcee2SJeff Cody     BlockDriverState *intermediate;
24486ebdcee2SJeff Cody 
24496ebdcee2SJeff Cody     assert(active != NULL);
24506ebdcee2SJeff Cody     assert(bs != NULL);
24516ebdcee2SJeff Cody 
24526ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
24536ebdcee2SJeff Cody      */
24546ebdcee2SJeff Cody     if (active == bs) {
24556ebdcee2SJeff Cody         return NULL;
24566ebdcee2SJeff Cody     }
24576ebdcee2SJeff Cody 
24586ebdcee2SJeff Cody     intermediate = active;
24596ebdcee2SJeff Cody     while (intermediate->backing_hd) {
24606ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
24616ebdcee2SJeff Cody             overlay = intermediate;
24626ebdcee2SJeff Cody             break;
24636ebdcee2SJeff Cody         }
24646ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
24656ebdcee2SJeff Cody     }
24666ebdcee2SJeff Cody 
24676ebdcee2SJeff Cody     return overlay;
24686ebdcee2SJeff Cody }
24696ebdcee2SJeff Cody 
24706ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
24716ebdcee2SJeff Cody     BlockDriverState *bs;
24726ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
24736ebdcee2SJeff Cody } BlkIntermediateStates;
24746ebdcee2SJeff Cody 
24756ebdcee2SJeff Cody 
24766ebdcee2SJeff Cody /*
24776ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
24786ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
24796ebdcee2SJeff Cody  *
24806ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
24816ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
24826ebdcee2SJeff Cody  *
24836ebdcee2SJeff Cody  * E.g., this will convert the following chain:
24846ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
24856ebdcee2SJeff Cody  *
24866ebdcee2SJeff Cody  * to
24876ebdcee2SJeff Cody  *
24886ebdcee2SJeff Cody  * bottom <- base <- active
24896ebdcee2SJeff Cody  *
24906ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
24916ebdcee2SJeff Cody  *
24926ebdcee2SJeff Cody  * base <- intermediate <- top <- active
24936ebdcee2SJeff Cody  *
24946ebdcee2SJeff Cody  * to
24956ebdcee2SJeff Cody  *
24966ebdcee2SJeff Cody  * base <- active
24976ebdcee2SJeff Cody  *
24986ebdcee2SJeff Cody  * Error conditions:
24996ebdcee2SJeff Cody  *  if active == top, that is considered an error
25006ebdcee2SJeff Cody  *
25016ebdcee2SJeff Cody  */
25026ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
25036ebdcee2SJeff Cody                            BlockDriverState *base)
25046ebdcee2SJeff Cody {
25056ebdcee2SJeff Cody     BlockDriverState *intermediate;
25066ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
25076ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
25086ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
25096ebdcee2SJeff Cody     int ret = -EIO;
25106ebdcee2SJeff Cody 
25116ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
25126ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
25136ebdcee2SJeff Cody 
25146ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
25156ebdcee2SJeff Cody         goto exit;
25166ebdcee2SJeff Cody     }
25176ebdcee2SJeff Cody 
25186ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
25196ebdcee2SJeff Cody 
25206ebdcee2SJeff Cody     if (new_top_bs == NULL) {
25216ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
25226ebdcee2SJeff Cody         goto exit;
25236ebdcee2SJeff Cody     }
25246ebdcee2SJeff Cody 
25256ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
25266ebdcee2SJeff Cody      * to do, no intermediate images */
25276ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
25286ebdcee2SJeff Cody         ret = 0;
25296ebdcee2SJeff Cody         goto exit;
25306ebdcee2SJeff Cody     }
25316ebdcee2SJeff Cody 
25326ebdcee2SJeff Cody     intermediate = top;
25336ebdcee2SJeff Cody 
25346ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
25356ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
25366ebdcee2SJeff Cody      */
25376ebdcee2SJeff Cody     while (intermediate) {
25386ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
25396ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
25406ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
25416ebdcee2SJeff Cody 
25426ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
25436ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
25446ebdcee2SJeff Cody             break;
25456ebdcee2SJeff Cody         }
25466ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
25476ebdcee2SJeff Cody     }
25486ebdcee2SJeff Cody     if (base_bs == NULL) {
25496ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
25506ebdcee2SJeff Cody          * unravel everything, and exit with error */
25516ebdcee2SJeff Cody         goto exit;
25526ebdcee2SJeff Cody     }
25536ebdcee2SJeff Cody 
25546ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
25556ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
25566ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
25576ebdcee2SJeff Cody     if (ret) {
25586ebdcee2SJeff Cody         goto exit;
25596ebdcee2SJeff Cody     }
25606ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
25616ebdcee2SJeff Cody 
2562355ef4acSKevin Wolf     bdrv_refresh_limits(new_top_bs);
25636ebdcee2SJeff Cody 
25646ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25656ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
25666ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
25674f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
25686ebdcee2SJeff Cody     }
25696ebdcee2SJeff Cody     ret = 0;
25706ebdcee2SJeff Cody 
25716ebdcee2SJeff Cody exit:
25726ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25736ebdcee2SJeff Cody         g_free(intermediate_state);
25746ebdcee2SJeff Cody     }
25756ebdcee2SJeff Cody     return ret;
25766ebdcee2SJeff Cody }
25776ebdcee2SJeff Cody 
25786ebdcee2SJeff Cody 
257971d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
258071d0770cSaliguori                                    size_t size)
258171d0770cSaliguori {
258271d0770cSaliguori     int64_t len;
258371d0770cSaliguori 
258471d0770cSaliguori     if (!bdrv_is_inserted(bs))
258571d0770cSaliguori         return -ENOMEDIUM;
258671d0770cSaliguori 
258771d0770cSaliguori     if (bs->growable)
258871d0770cSaliguori         return 0;
258971d0770cSaliguori 
259071d0770cSaliguori     len = bdrv_getlength(bs);
259171d0770cSaliguori 
2592fbb7b4e0SKevin Wolf     if (offset < 0)
2593fbb7b4e0SKevin Wolf         return -EIO;
2594fbb7b4e0SKevin Wolf 
2595fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
259671d0770cSaliguori         return -EIO;
259771d0770cSaliguori 
259871d0770cSaliguori     return 0;
259971d0770cSaliguori }
260071d0770cSaliguori 
260171d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
260271d0770cSaliguori                               int nb_sectors)
260371d0770cSaliguori {
26048f4754edSKevin Wolf     if (nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
26058f4754edSKevin Wolf         return -EIO;
26068f4754edSKevin Wolf     }
26078f4754edSKevin Wolf 
2608eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2609eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
261071d0770cSaliguori }
261171d0770cSaliguori 
26121c9805a3SStefan Hajnoczi typedef struct RwCo {
26131c9805a3SStefan Hajnoczi     BlockDriverState *bs;
2614775aa8b6SKevin Wolf     int64_t offset;
26151c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
26161c9805a3SStefan Hajnoczi     bool is_write;
26171c9805a3SStefan Hajnoczi     int ret;
26184105eaaaSPeter Lieven     BdrvRequestFlags flags;
26191c9805a3SStefan Hajnoczi } RwCo;
26201c9805a3SStefan Hajnoczi 
26211c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2622fc01f7e7Sbellard {
26231c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2624fc01f7e7Sbellard 
26251c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
2626775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2627775aa8b6SKevin Wolf                                       rwco->qiov->size, rwco->qiov,
26284105eaaaSPeter Lieven                                       rwco->flags);
26291c9805a3SStefan Hajnoczi     } else {
2630775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2631775aa8b6SKevin Wolf                                        rwco->qiov->size, rwco->qiov,
26324105eaaaSPeter Lieven                                        rwco->flags);
26331c9805a3SStefan Hajnoczi     }
26341c9805a3SStefan Hajnoczi }
2635e7a8a783SKevin Wolf 
26361c9805a3SStefan Hajnoczi /*
26378d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
26381c9805a3SStefan Hajnoczi  */
2639775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
26404105eaaaSPeter Lieven                         QEMUIOVector *qiov, bool is_write,
26414105eaaaSPeter Lieven                         BdrvRequestFlags flags)
26421c9805a3SStefan Hajnoczi {
26431c9805a3SStefan Hajnoczi     Coroutine *co;
26441c9805a3SStefan Hajnoczi     RwCo rwco = {
26451c9805a3SStefan Hajnoczi         .bs = bs,
2646775aa8b6SKevin Wolf         .offset = offset,
26478d3b1a2dSKevin Wolf         .qiov = qiov,
26481c9805a3SStefan Hajnoczi         .is_write = is_write,
26491c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
26504105eaaaSPeter Lieven         .flags = flags,
26511c9805a3SStefan Hajnoczi     };
26521c9805a3SStefan Hajnoczi 
2653498e386cSZhi Yong Wu     /**
2654498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2655498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2656498e386cSZhi Yong Wu      * if it has been enabled.
2657498e386cSZhi Yong Wu      */
2658498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2659498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2660498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2661498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2662498e386cSZhi Yong Wu     }
2663498e386cSZhi Yong Wu 
26641c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
26651c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
26661c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
26671c9805a3SStefan Hajnoczi     } else {
26681c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
26691c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
26701c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
26711c9805a3SStefan Hajnoczi             qemu_aio_wait();
26721c9805a3SStefan Hajnoczi         }
26731c9805a3SStefan Hajnoczi     }
26741c9805a3SStefan Hajnoczi     return rwco.ret;
2675e7a8a783SKevin Wolf }
2676e7a8a783SKevin Wolf 
26778d3b1a2dSKevin Wolf /*
26788d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
26798d3b1a2dSKevin Wolf  */
26808d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
26814105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
26828d3b1a2dSKevin Wolf {
26838d3b1a2dSKevin Wolf     QEMUIOVector qiov;
26848d3b1a2dSKevin Wolf     struct iovec iov = {
26858d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
26868d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
26878d3b1a2dSKevin Wolf     };
26888d3b1a2dSKevin Wolf 
26898d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2690775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2691775aa8b6SKevin Wolf                         &qiov, is_write, flags);
26928d3b1a2dSKevin Wolf }
26938d3b1a2dSKevin Wolf 
26941c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
26951c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
26961c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
26971c9805a3SStefan Hajnoczi {
26984105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
269983f64091Sbellard }
2700fc01f7e7Sbellard 
270107d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
270207d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
270307d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
270407d27a44SMarkus Armbruster {
270507d27a44SMarkus Armbruster     bool enabled;
270607d27a44SMarkus Armbruster     int ret;
270707d27a44SMarkus Armbruster 
270807d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
270907d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
27104e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
271107d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
271207d27a44SMarkus Armbruster     return ret;
271307d27a44SMarkus Armbruster }
271407d27a44SMarkus Armbruster 
271519cb3738Sbellard /* Return < 0 if error. Important errors are:
271619cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
271719cb3738Sbellard   -ENOMEDIUM   No media inserted.
271819cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
271919cb3738Sbellard   -EACCES      Trying to write a read-only device
272019cb3738Sbellard */
2721fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2722fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2723fc01f7e7Sbellard {
27244105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
272583f64091Sbellard }
272683f64091Sbellard 
2727aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2728aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
27294105eaaaSPeter Lieven {
27304105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2731aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
27328d3b1a2dSKevin Wolf }
27338d3b1a2dSKevin Wolf 
2734d75cbb5eSPeter Lieven /*
2735d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2736d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2737d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2738d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2739d75cbb5eSPeter Lieven  *
2740d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2741d75cbb5eSPeter Lieven  */
2742d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2743d75cbb5eSPeter Lieven {
2744d75cbb5eSPeter Lieven     int64_t target_size = bdrv_getlength(bs) / BDRV_SECTOR_SIZE;
2745d75cbb5eSPeter Lieven     int64_t ret, nb_sectors, sector_num = 0;
2746d75cbb5eSPeter Lieven     int n;
2747d75cbb5eSPeter Lieven 
2748d75cbb5eSPeter Lieven     for (;;) {
2749d75cbb5eSPeter Lieven         nb_sectors = target_size - sector_num;
2750d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2751d75cbb5eSPeter Lieven             return 0;
2752d75cbb5eSPeter Lieven         }
2753d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2754d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2755d75cbb5eSPeter Lieven         }
2756d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
27573d94ce60SPeter Lieven         if (ret < 0) {
27583d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
27593d94ce60SPeter Lieven                          sector_num, strerror(-ret));
27603d94ce60SPeter Lieven             return ret;
27613d94ce60SPeter Lieven         }
2762d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2763d75cbb5eSPeter Lieven             sector_num += n;
2764d75cbb5eSPeter Lieven             continue;
2765d75cbb5eSPeter Lieven         }
2766d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2767d75cbb5eSPeter Lieven         if (ret < 0) {
2768d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2769d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2770d75cbb5eSPeter Lieven             return ret;
2771d75cbb5eSPeter Lieven         }
2772d75cbb5eSPeter Lieven         sector_num += n;
2773d75cbb5eSPeter Lieven     }
2774d75cbb5eSPeter Lieven }
2775d75cbb5eSPeter Lieven 
2776a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
277783f64091Sbellard {
2778a3ef6571SKevin Wolf     QEMUIOVector qiov;
2779a3ef6571SKevin Wolf     struct iovec iov = {
2780a3ef6571SKevin Wolf         .iov_base = (void *)buf,
2781a3ef6571SKevin Wolf         .iov_len = bytes,
2782a3ef6571SKevin Wolf     };
27839a8c4cceSKevin Wolf     int ret;
278483f64091Sbellard 
2785a3ef6571SKevin Wolf     if (bytes < 0) {
2786a3ef6571SKevin Wolf         return -EINVAL;
278783f64091Sbellard     }
278883f64091Sbellard 
2789a3ef6571SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2790a3ef6571SKevin Wolf     ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
2791a3ef6571SKevin Wolf     if (ret < 0) {
27929a8c4cceSKevin Wolf         return ret;
279383f64091Sbellard     }
279483f64091Sbellard 
2795a3ef6571SKevin Wolf     return bytes;
279683f64091Sbellard }
279783f64091Sbellard 
27988d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
279983f64091Sbellard {
28009a8c4cceSKevin Wolf     int ret;
280183f64091Sbellard 
28028407d5d7SKevin Wolf     ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
28038d3b1a2dSKevin Wolf     if (ret < 0) {
28049a8c4cceSKevin Wolf         return ret;
28058d3b1a2dSKevin Wolf     }
28068d3b1a2dSKevin Wolf 
28078d3b1a2dSKevin Wolf     return qiov->size;
28088d3b1a2dSKevin Wolf }
28098d3b1a2dSKevin Wolf 
28108d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
28118407d5d7SKevin Wolf                 const void *buf, int bytes)
28128d3b1a2dSKevin Wolf {
28138d3b1a2dSKevin Wolf     QEMUIOVector qiov;
28148d3b1a2dSKevin Wolf     struct iovec iov = {
28158d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
28168407d5d7SKevin Wolf         .iov_len    = bytes,
28178d3b1a2dSKevin Wolf     };
28188d3b1a2dSKevin Wolf 
28198407d5d7SKevin Wolf     if (bytes < 0) {
28208407d5d7SKevin Wolf         return -EINVAL;
28218407d5d7SKevin Wolf     }
28228407d5d7SKevin Wolf 
28238d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
28248d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
282583f64091Sbellard }
282683f64091Sbellard 
2827f08145feSKevin Wolf /*
2828f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2829f08145feSKevin Wolf  * request (acts as a barrier)
2830f08145feSKevin Wolf  *
2831f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2832f08145feSKevin Wolf  */
2833f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2834f08145feSKevin Wolf     const void *buf, int count)
2835f08145feSKevin Wolf {
2836f08145feSKevin Wolf     int ret;
2837f08145feSKevin Wolf 
2838f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2839f08145feSKevin Wolf     if (ret < 0) {
2840f08145feSKevin Wolf         return ret;
2841f08145feSKevin Wolf     }
2842f08145feSKevin Wolf 
2843f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2844f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2845f08145feSKevin Wolf         bdrv_flush(bs);
2846f08145feSKevin Wolf     }
2847f08145feSKevin Wolf 
2848f08145feSKevin Wolf     return 0;
2849f08145feSKevin Wolf }
2850f08145feSKevin Wolf 
2851470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2852ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2853ab185921SStefan Hajnoczi {
2854ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2855ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2856ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2857ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2858ab185921SStefan Hajnoczi      */
2859ab185921SStefan Hajnoczi     void *bounce_buffer;
2860ab185921SStefan Hajnoczi 
286179c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2862ab185921SStefan Hajnoczi     struct iovec iov;
2863ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2864ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2865ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2866ab185921SStefan Hajnoczi     size_t skip_bytes;
2867ab185921SStefan Hajnoczi     int ret;
2868ab185921SStefan Hajnoczi 
2869ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2870ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2871ab185921SStefan Hajnoczi      */
2872343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2873ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2874ab185921SStefan Hajnoczi 
2875470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2876ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2877ab185921SStefan Hajnoczi 
2878ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2879ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2880ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2881ab185921SStefan Hajnoczi 
288279c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2883ab185921SStefan Hajnoczi                              &bounce_qiov);
2884ab185921SStefan Hajnoczi     if (ret < 0) {
2885ab185921SStefan Hajnoczi         goto err;
2886ab185921SStefan Hajnoczi     }
2887ab185921SStefan Hajnoczi 
288879c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
288979c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2890621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2891aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
289279c053bdSStefan Hajnoczi     } else {
2893f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2894f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2895f05fa4adSPaolo Bonzini          */
289679c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2897ab185921SStefan Hajnoczi                                   &bounce_qiov);
289879c053bdSStefan Hajnoczi     }
289979c053bdSStefan Hajnoczi 
2900ab185921SStefan Hajnoczi     if (ret < 0) {
2901ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2902ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2903ab185921SStefan Hajnoczi          * Simply report it in all cases.
2904ab185921SStefan Hajnoczi          */
2905ab185921SStefan Hajnoczi         goto err;
2906ab185921SStefan Hajnoczi     }
2907ab185921SStefan Hajnoczi 
2908ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
290903396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2910ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2911ab185921SStefan Hajnoczi 
2912ab185921SStefan Hajnoczi err:
2913ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2914ab185921SStefan Hajnoczi     return ret;
2915ab185921SStefan Hajnoczi }
2916ab185921SStefan Hajnoczi 
2917c5fbe571SStefan Hajnoczi /*
2918d0c7f642SKevin Wolf  * Forwards an already correctly aligned request to the BlockDriver. This
2919d0c7f642SKevin Wolf  * handles copy on read and zeroing after EOF; any other features must be
2920d0c7f642SKevin Wolf  * implemented by the caller.
2921c5fbe571SStefan Hajnoczi  */
2922d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
292365afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
2924ec746e10SKevin Wolf     int64_t align, QEMUIOVector *qiov, int flags)
2925da1fa91dSKevin Wolf {
2926da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2927dbffbdcfSStefan Hajnoczi     int ret;
2928da1fa91dSKevin Wolf 
2929d0c7f642SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
2930d0c7f642SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
2931da1fa91dSKevin Wolf 
2932d0c7f642SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2933d0c7f642SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
2934d0c7f642SKevin Wolf 
2935d0c7f642SKevin Wolf     /* Handle Copy on Read and associated serialisation */
2936470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
29377327145fSKevin Wolf         /* If we touch the same cluster it counts as an overlap.  This
29387327145fSKevin Wolf          * guarantees that allocating writes will be serialized and not race
29397327145fSKevin Wolf          * with each other for the same cluster.  For example, in copy-on-read
29407327145fSKevin Wolf          * it ensures that the CoR read and write operations are atomic and
29417327145fSKevin Wolf          * guest writes cannot interleave between them. */
29427327145fSKevin Wolf         mark_request_serialising(req, bdrv_get_cluster_size(bs));
2943470c0504SStefan Hajnoczi     }
2944470c0504SStefan Hajnoczi 
29452dbafdc0SKevin Wolf     wait_serialising_requests(req);
2946f4658285SStefan Hajnoczi 
2947470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2948ab185921SStefan Hajnoczi         int pnum;
2949ab185921SStefan Hajnoczi 
2950bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2951ab185921SStefan Hajnoczi         if (ret < 0) {
2952ab185921SStefan Hajnoczi             goto out;
2953ab185921SStefan Hajnoczi         }
2954ab185921SStefan Hajnoczi 
2955ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2956470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2957ab185921SStefan Hajnoczi             goto out;
2958ab185921SStefan Hajnoczi         }
2959ab185921SStefan Hajnoczi     }
2960ab185921SStefan Hajnoczi 
2961d0c7f642SKevin Wolf     /* Forward the request to the BlockDriver */
2962893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2963dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2964893a8f62SMORITA Kazutaka     } else {
2965893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2966893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2967893a8f62SMORITA Kazutaka 
2968893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2969893a8f62SMORITA Kazutaka         if (len < 0) {
2970893a8f62SMORITA Kazutaka             ret = len;
2971893a8f62SMORITA Kazutaka             goto out;
2972893a8f62SMORITA Kazutaka         }
2973893a8f62SMORITA Kazutaka 
2974d055a1feSFam Zheng         total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
29755f5bcd80SKevin Wolf         max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
29765f5bcd80SKevin Wolf                                   align >> BDRV_SECTOR_BITS);
2977893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
2978893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
2979893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
2980893a8f62SMORITA Kazutaka         } else {
2981893a8f62SMORITA Kazutaka             ret = 0;
2982893a8f62SMORITA Kazutaka         }
2983893a8f62SMORITA Kazutaka 
2984893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
2985893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2986893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
2987893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
2988893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
2989893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
2990893a8f62SMORITA Kazutaka         }
2991893a8f62SMORITA Kazutaka     }
2992ab185921SStefan Hajnoczi 
2993ab185921SStefan Hajnoczi out:
2994dbffbdcfSStefan Hajnoczi     return ret;
2995da1fa91dSKevin Wolf }
2996da1fa91dSKevin Wolf 
2997d0c7f642SKevin Wolf /*
2998d0c7f642SKevin Wolf  * Handle a read request in coroutine context
2999d0c7f642SKevin Wolf  */
30001b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
30011b0288aeSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3002d0c7f642SKevin Wolf     BdrvRequestFlags flags)
3003d0c7f642SKevin Wolf {
3004d0c7f642SKevin Wolf     BlockDriver *drv = bs->drv;
300565afd211SKevin Wolf     BdrvTrackedRequest req;
300665afd211SKevin Wolf 
30071b0288aeSKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
30081b0288aeSKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
30091b0288aeSKevin Wolf     uint8_t *head_buf = NULL;
30101b0288aeSKevin Wolf     uint8_t *tail_buf = NULL;
30111b0288aeSKevin Wolf     QEMUIOVector local_qiov;
30121b0288aeSKevin Wolf     bool use_local_qiov = false;
3013d0c7f642SKevin Wolf     int ret;
3014d0c7f642SKevin Wolf 
3015d0c7f642SKevin Wolf     if (!drv) {
3016d0c7f642SKevin Wolf         return -ENOMEDIUM;
3017d0c7f642SKevin Wolf     }
30181b0288aeSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3019d0c7f642SKevin Wolf         return -EIO;
3020d0c7f642SKevin Wolf     }
3021d0c7f642SKevin Wolf 
3022d0c7f642SKevin Wolf     if (bs->copy_on_read) {
3023d0c7f642SKevin Wolf         flags |= BDRV_REQ_COPY_ON_READ;
3024d0c7f642SKevin Wolf     }
3025d0c7f642SKevin Wolf 
3026d0c7f642SKevin Wolf     /* throttling disk I/O */
3027d0c7f642SKevin Wolf     if (bs->io_limits_enabled) {
3028d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, false);
3029d0c7f642SKevin Wolf     }
3030d0c7f642SKevin Wolf 
30311b0288aeSKevin Wolf     /* Align read if necessary by padding qiov */
30321b0288aeSKevin Wolf     if (offset & (align - 1)) {
30331b0288aeSKevin Wolf         head_buf = qemu_blockalign(bs, align);
30341b0288aeSKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
30351b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
30361b0288aeSKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30371b0288aeSKevin Wolf         use_local_qiov = true;
30381b0288aeSKevin Wolf 
30391b0288aeSKevin Wolf         bytes += offset & (align - 1);
30401b0288aeSKevin Wolf         offset = offset & ~(align - 1);
30411b0288aeSKevin Wolf     }
30421b0288aeSKevin Wolf 
30431b0288aeSKevin Wolf     if ((offset + bytes) & (align - 1)) {
30441b0288aeSKevin Wolf         if (!use_local_qiov) {
30451b0288aeSKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
30461b0288aeSKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30471b0288aeSKevin Wolf             use_local_qiov = true;
30481b0288aeSKevin Wolf         }
30491b0288aeSKevin Wolf         tail_buf = qemu_blockalign(bs, align);
30501b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf,
30511b0288aeSKevin Wolf                        align - ((offset + bytes) & (align - 1)));
30521b0288aeSKevin Wolf 
30531b0288aeSKevin Wolf         bytes = ROUND_UP(bytes, align);
30541b0288aeSKevin Wolf     }
30551b0288aeSKevin Wolf 
305665afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, false);
3057ec746e10SKevin Wolf     ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
30581b0288aeSKevin Wolf                               use_local_qiov ? &local_qiov : qiov,
30591b0288aeSKevin Wolf                               flags);
306065afd211SKevin Wolf     tracked_request_end(&req);
30611b0288aeSKevin Wolf 
30621b0288aeSKevin Wolf     if (use_local_qiov) {
30631b0288aeSKevin Wolf         qemu_iovec_destroy(&local_qiov);
30641b0288aeSKevin Wolf         qemu_vfree(head_buf);
30651b0288aeSKevin Wolf         qemu_vfree(tail_buf);
30661b0288aeSKevin Wolf     }
30671b0288aeSKevin Wolf 
3068d0c7f642SKevin Wolf     return ret;
3069d0c7f642SKevin Wolf }
3070d0c7f642SKevin Wolf 
30711b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
30721b0288aeSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
30731b0288aeSKevin Wolf     BdrvRequestFlags flags)
30741b0288aeSKevin Wolf {
30751b0288aeSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
30761b0288aeSKevin Wolf         return -EINVAL;
30771b0288aeSKevin Wolf     }
30781b0288aeSKevin Wolf 
30791b0288aeSKevin Wolf     return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
30801b0288aeSKevin Wolf                              nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
30811b0288aeSKevin Wolf }
30821b0288aeSKevin Wolf 
3083c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
3084da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
3085da1fa91dSKevin Wolf {
3086c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
3087da1fa91dSKevin Wolf 
3088470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3089470c0504SStefan Hajnoczi }
3090470c0504SStefan Hajnoczi 
3091470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3092470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3093470c0504SStefan Hajnoczi {
3094470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3095470c0504SStefan Hajnoczi 
3096470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3097470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
3098c5fbe571SStefan Hajnoczi }
3099c5fbe571SStefan Hajnoczi 
3100c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
3101c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
3102c31cb707SPeter Lieven  */
3103c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
3104c31cb707SPeter Lieven 
3105f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
3106aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
3107f08f2ddaSStefan Hajnoczi {
3108f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3109f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3110c31cb707SPeter Lieven     struct iovec iov = {0};
3111c31cb707SPeter Lieven     int ret = 0;
3112f08f2ddaSStefan Hajnoczi 
3113c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3114c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3115621f0589SKevin Wolf 
3116c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3117c31cb707SPeter Lieven         int num = nb_sectors;
3118c31cb707SPeter Lieven 
3119b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3120b8d71c09SPaolo Bonzini          * to be aligned.
3121b8d71c09SPaolo Bonzini          */
3122b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3123b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3124b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3125b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3126c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3127c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3128b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3129b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3130b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3131b8d71c09SPaolo Bonzini                  */
3132b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3133b8d71c09SPaolo Bonzini             }
3134c31cb707SPeter Lieven         }
3135c31cb707SPeter Lieven 
3136c31cb707SPeter Lieven         /* limit request size */
3137c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3138c31cb707SPeter Lieven             num = max_write_zeroes;
3139c31cb707SPeter Lieven         }
3140c31cb707SPeter Lieven 
3141c31cb707SPeter Lieven         ret = -ENOTSUP;
3142f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3143f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3144c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3145f08f2ddaSStefan Hajnoczi         }
3146f08f2ddaSStefan Hajnoczi 
3147c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3148f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3149c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3150c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3151b8d71c09SPaolo Bonzini                 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
3152b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3153c31cb707SPeter Lieven             }
3154f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3155f08f2ddaSStefan Hajnoczi 
3156c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3157b8d71c09SPaolo Bonzini 
3158b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3159b8d71c09SPaolo Bonzini              * all future requests.
3160b8d71c09SPaolo Bonzini              */
3161b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3162b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3163b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3164b8d71c09SPaolo Bonzini             }
3165c31cb707SPeter Lieven         }
3166c31cb707SPeter Lieven 
3167c31cb707SPeter Lieven         sector_num += num;
3168c31cb707SPeter Lieven         nb_sectors -= num;
3169c31cb707SPeter Lieven     }
3170f08f2ddaSStefan Hajnoczi 
3171f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3172f08f2ddaSStefan Hajnoczi     return ret;
3173f08f2ddaSStefan Hajnoczi }
3174f08f2ddaSStefan Hajnoczi 
3175c5fbe571SStefan Hajnoczi /*
3176b404f720SKevin Wolf  * Forwards an already correctly aligned write request to the BlockDriver.
3177c5fbe571SStefan Hajnoczi  */
3178b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
317965afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
318065afd211SKevin Wolf     QEMUIOVector *qiov, int flags)
3181c5fbe571SStefan Hajnoczi {
3182c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
318328de2dcdSKevin Wolf     bool waited;
31846b7cb247SStefan Hajnoczi     int ret;
3185da1fa91dSKevin Wolf 
3186b404f720SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3187b404f720SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3188da1fa91dSKevin Wolf 
3189b404f720SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3190b404f720SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3191cc0681c4SBenoît Canet 
319228de2dcdSKevin Wolf     waited = wait_serialising_requests(req);
319328de2dcdSKevin Wolf     assert(!waited || !req->serialising);
3194af91f9a7SKevin Wolf     assert(req->overlap_offset <= offset);
3195af91f9a7SKevin Wolf     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
3196244eadefSKevin Wolf 
319765afd211SKevin Wolf     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
3198d616b224SStefan Hajnoczi 
3199d616b224SStefan Hajnoczi     if (ret < 0) {
3200d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3201d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
32029e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
3203aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3204f08f2ddaSStefan Hajnoczi     } else {
32059e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
32066b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3207f08f2ddaSStefan Hajnoczi     }
32089e1cb96dSKevin Wolf     BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
32096b7cb247SStefan Hajnoczi 
3210f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3211f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3212f05fa4adSPaolo Bonzini     }
3213f05fa4adSPaolo Bonzini 
32141755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3215da1fa91dSKevin Wolf 
3216da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
3217da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
3218da1fa91dSKevin Wolf     }
3219df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3220df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3221df2a6f29SPaolo Bonzini     }
3222da1fa91dSKevin Wolf 
32236b7cb247SStefan Hajnoczi     return ret;
3224da1fa91dSKevin Wolf }
3225da1fa91dSKevin Wolf 
3226b404f720SKevin Wolf /*
3227b404f720SKevin Wolf  * Handle a write request in coroutine context
3228b404f720SKevin Wolf  */
32296601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
32306601553eSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3231b404f720SKevin Wolf     BdrvRequestFlags flags)
3232b404f720SKevin Wolf {
323365afd211SKevin Wolf     BdrvTrackedRequest req;
32343b8242e0SKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
32353b8242e0SKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
32363b8242e0SKevin Wolf     uint8_t *head_buf = NULL;
32373b8242e0SKevin Wolf     uint8_t *tail_buf = NULL;
32383b8242e0SKevin Wolf     QEMUIOVector local_qiov;
32393b8242e0SKevin Wolf     bool use_local_qiov = false;
3240b404f720SKevin Wolf     int ret;
3241b404f720SKevin Wolf 
3242b404f720SKevin Wolf     if (!bs->drv) {
3243b404f720SKevin Wolf         return -ENOMEDIUM;
3244b404f720SKevin Wolf     }
3245b404f720SKevin Wolf     if (bs->read_only) {
3246b404f720SKevin Wolf         return -EACCES;
3247b404f720SKevin Wolf     }
32486601553eSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3249b404f720SKevin Wolf         return -EIO;
3250b404f720SKevin Wolf     }
3251b404f720SKevin Wolf 
3252b404f720SKevin Wolf     /* throttling disk I/O */
3253b404f720SKevin Wolf     if (bs->io_limits_enabled) {
3254d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, true);
3255b404f720SKevin Wolf     }
3256b404f720SKevin Wolf 
32573b8242e0SKevin Wolf     /*
32583b8242e0SKevin Wolf      * Align write if necessary by performing a read-modify-write cycle.
32593b8242e0SKevin Wolf      * Pad qiov with the read parts and be sure to have a tracked request not
32603b8242e0SKevin Wolf      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
32613b8242e0SKevin Wolf      */
326265afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, true);
32633b8242e0SKevin Wolf 
32643b8242e0SKevin Wolf     if (offset & (align - 1)) {
32653b8242e0SKevin Wolf         QEMUIOVector head_qiov;
32663b8242e0SKevin Wolf         struct iovec head_iov;
32673b8242e0SKevin Wolf 
32683b8242e0SKevin Wolf         mark_request_serialising(&req, align);
32693b8242e0SKevin Wolf         wait_serialising_requests(&req);
32703b8242e0SKevin Wolf 
32713b8242e0SKevin Wolf         head_buf = qemu_blockalign(bs, align);
32723b8242e0SKevin Wolf         head_iov = (struct iovec) {
32733b8242e0SKevin Wolf             .iov_base   = head_buf,
32743b8242e0SKevin Wolf             .iov_len    = align,
32753b8242e0SKevin Wolf         };
32763b8242e0SKevin Wolf         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
32773b8242e0SKevin Wolf 
32789e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
32793b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
32803b8242e0SKevin Wolf                                   align, &head_qiov, 0);
32813b8242e0SKevin Wolf         if (ret < 0) {
32823b8242e0SKevin Wolf             goto fail;
32833b8242e0SKevin Wolf         }
32849e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
32853b8242e0SKevin Wolf 
32863b8242e0SKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
32873b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
32883b8242e0SKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
32893b8242e0SKevin Wolf         use_local_qiov = true;
32903b8242e0SKevin Wolf 
32913b8242e0SKevin Wolf         bytes += offset & (align - 1);
32923b8242e0SKevin Wolf         offset = offset & ~(align - 1);
32933b8242e0SKevin Wolf     }
32943b8242e0SKevin Wolf 
32953b8242e0SKevin Wolf     if ((offset + bytes) & (align - 1)) {
32963b8242e0SKevin Wolf         QEMUIOVector tail_qiov;
32973b8242e0SKevin Wolf         struct iovec tail_iov;
32983b8242e0SKevin Wolf         size_t tail_bytes;
329928de2dcdSKevin Wolf         bool waited;
33003b8242e0SKevin Wolf 
33013b8242e0SKevin Wolf         mark_request_serialising(&req, align);
330228de2dcdSKevin Wolf         waited = wait_serialising_requests(&req);
330328de2dcdSKevin Wolf         assert(!waited || !use_local_qiov);
33043b8242e0SKevin Wolf 
33053b8242e0SKevin Wolf         tail_buf = qemu_blockalign(bs, align);
33063b8242e0SKevin Wolf         tail_iov = (struct iovec) {
33073b8242e0SKevin Wolf             .iov_base   = tail_buf,
33083b8242e0SKevin Wolf             .iov_len    = align,
33093b8242e0SKevin Wolf         };
33103b8242e0SKevin Wolf         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
33113b8242e0SKevin Wolf 
33129e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
33133b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
33143b8242e0SKevin Wolf                                   align, &tail_qiov, 0);
33153b8242e0SKevin Wolf         if (ret < 0) {
33163b8242e0SKevin Wolf             goto fail;
33173b8242e0SKevin Wolf         }
33189e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
33193b8242e0SKevin Wolf 
33203b8242e0SKevin Wolf         if (!use_local_qiov) {
33213b8242e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
33223b8242e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
33233b8242e0SKevin Wolf             use_local_qiov = true;
33243b8242e0SKevin Wolf         }
33253b8242e0SKevin Wolf 
33263b8242e0SKevin Wolf         tail_bytes = (offset + bytes) & (align - 1);
33273b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
33283b8242e0SKevin Wolf 
33293b8242e0SKevin Wolf         bytes = ROUND_UP(bytes, align);
33303b8242e0SKevin Wolf     }
33313b8242e0SKevin Wolf 
33323b8242e0SKevin Wolf     ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
33333b8242e0SKevin Wolf                                use_local_qiov ? &local_qiov : qiov,
33343b8242e0SKevin Wolf                                flags);
33353b8242e0SKevin Wolf 
33363b8242e0SKevin Wolf fail:
333765afd211SKevin Wolf     tracked_request_end(&req);
3338b404f720SKevin Wolf 
33393b8242e0SKevin Wolf     if (use_local_qiov) {
33403b8242e0SKevin Wolf         qemu_iovec_destroy(&local_qiov);
334199c4a85cSKevin Wolf     }
33423b8242e0SKevin Wolf     qemu_vfree(head_buf);
33433b8242e0SKevin Wolf     qemu_vfree(tail_buf);
33443b8242e0SKevin Wolf 
3345b404f720SKevin Wolf     return ret;
3346b404f720SKevin Wolf }
3347b404f720SKevin Wolf 
33486601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
33496601553eSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
33506601553eSKevin Wolf     BdrvRequestFlags flags)
33516601553eSKevin Wolf {
33526601553eSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
33536601553eSKevin Wolf         return -EINVAL;
33546601553eSKevin Wolf     }
33556601553eSKevin Wolf 
33566601553eSKevin Wolf     return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
33576601553eSKevin Wolf                               nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
33586601553eSKevin Wolf }
33596601553eSKevin Wolf 
3360c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3361c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3362c5fbe571SStefan Hajnoczi {
3363c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3364c5fbe571SStefan Hajnoczi 
3365f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3366f08f2ddaSStefan Hajnoczi }
3367f08f2ddaSStefan Hajnoczi 
3368f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3369aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3370aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3371f08f2ddaSStefan Hajnoczi {
337294d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3373f08f2ddaSStefan Hajnoczi 
3374d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3375d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3376d32f35cbSPeter Lieven     }
3377d32f35cbSPeter Lieven 
3378f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3379aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3380c5fbe571SStefan Hajnoczi }
3381c5fbe571SStefan Hajnoczi 
338283f64091Sbellard /**
338383f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
338483f64091Sbellard  */
338583f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
338683f64091Sbellard {
338783f64091Sbellard     BlockDriver *drv = bs->drv;
338851762288SStefan Hajnoczi     int ret;
338983f64091Sbellard     if (!drv)
339019cb3738Sbellard         return -ENOMEDIUM;
339183f64091Sbellard     if (!drv->bdrv_truncate)
339283f64091Sbellard         return -ENOTSUP;
339359f2689dSNaphtali Sprei     if (bs->read_only)
339459f2689dSNaphtali Sprei         return -EACCES;
33958591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
33968591675fSMarcelo Tosatti         return -EBUSY;
339751762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
339851762288SStefan Hajnoczi     if (ret == 0) {
339951762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3400145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
340151762288SStefan Hajnoczi     }
340251762288SStefan Hajnoczi     return ret;
340383f64091Sbellard }
340483f64091Sbellard 
340583f64091Sbellard /**
34064a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
34074a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
34084a1d5e1fSFam Zheng  */
34094a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
34104a1d5e1fSFam Zheng {
34114a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
34124a1d5e1fSFam Zheng     if (!drv) {
34134a1d5e1fSFam Zheng         return -ENOMEDIUM;
34144a1d5e1fSFam Zheng     }
34154a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
34164a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
34174a1d5e1fSFam Zheng     }
34184a1d5e1fSFam Zheng     if (bs->file) {
34194a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
34204a1d5e1fSFam Zheng     }
34214a1d5e1fSFam Zheng     return -ENOTSUP;
34224a1d5e1fSFam Zheng }
34234a1d5e1fSFam Zheng 
34244a1d5e1fSFam Zheng /**
342583f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
342683f64091Sbellard  */
342783f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
342883f64091Sbellard {
342983f64091Sbellard     BlockDriver *drv = bs->drv;
343083f64091Sbellard     if (!drv)
343119cb3738Sbellard         return -ENOMEDIUM;
343251762288SStefan Hajnoczi 
3433b94a2610SKevin Wolf     if (drv->has_variable_length) {
3434b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3435b94a2610SKevin Wolf         if (ret < 0) {
3436b94a2610SKevin Wolf             return ret;
3437fc01f7e7Sbellard         }
343846a4e4e6SStefan Hajnoczi     }
343946a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
344046a4e4e6SStefan Hajnoczi }
3441fc01f7e7Sbellard 
344219cb3738Sbellard /* return 0 as number of sectors if no device present or error */
344396b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3444fc01f7e7Sbellard {
344519cb3738Sbellard     int64_t length;
344619cb3738Sbellard     length = bdrv_getlength(bs);
344719cb3738Sbellard     if (length < 0)
344819cb3738Sbellard         length = 0;
344919cb3738Sbellard     else
34506ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
345119cb3738Sbellard     *nb_sectors_ptr = length;
3452fc01f7e7Sbellard }
3453cf98951bSbellard 
3454ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3455ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3456abd7f68dSMarkus Armbruster {
3457abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3458abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3459abd7f68dSMarkus Armbruster }
3460abd7f68dSMarkus Armbruster 
34611ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3462abd7f68dSMarkus Armbruster {
3463abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3464abd7f68dSMarkus Armbruster }
3465abd7f68dSMarkus Armbruster 
34663e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
34673e1caa5fSPaolo Bonzini {
34683e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
34693e1caa5fSPaolo Bonzini 
34703e1caa5fSPaolo Bonzini     switch (on_err) {
34713e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
34723e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
34733e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
34743e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
34753e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
34763e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
34773e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
34783e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
34793e1caa5fSPaolo Bonzini     default:
34803e1caa5fSPaolo Bonzini         abort();
34813e1caa5fSPaolo Bonzini     }
34823e1caa5fSPaolo Bonzini }
34833e1caa5fSPaolo Bonzini 
34843e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
34853e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
34863e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
34873e1caa5fSPaolo Bonzini  */
34883e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
34893e1caa5fSPaolo Bonzini                        bool is_read, int error)
34903e1caa5fSPaolo Bonzini {
34913e1caa5fSPaolo Bonzini     assert(error >= 0);
349232c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
34933e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
34943e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
34953e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
34963e1caa5fSPaolo Bonzini     }
34973e1caa5fSPaolo Bonzini }
34983e1caa5fSPaolo Bonzini 
3499b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3500b338082bSbellard {
3501b338082bSbellard     return bs->read_only;
3502b338082bSbellard }
3503b338082bSbellard 
3504985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3505985a03b0Sths {
3506985a03b0Sths     return bs->sg;
3507985a03b0Sths }
3508985a03b0Sths 
3509e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3510e900a7b7SChristoph Hellwig {
3511e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3512e900a7b7SChristoph Hellwig }
3513e900a7b7SChristoph Hellwig 
3514425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3515425b0148SPaolo Bonzini {
3516425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
351755b110f2SJeff Cody 
351855b110f2SJeff Cody     /* so a reopen() will preserve wce */
351955b110f2SJeff Cody     if (wce) {
352055b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
352155b110f2SJeff Cody     } else {
352255b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
352355b110f2SJeff Cody     }
3524425b0148SPaolo Bonzini }
3525425b0148SPaolo Bonzini 
3526ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3527ea2384d3Sbellard {
3528ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3529ea2384d3Sbellard         return 1;
3530ea2384d3Sbellard     return bs->encrypted;
3531ea2384d3Sbellard }
3532ea2384d3Sbellard 
3533c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3534c0f4ce77Saliguori {
3535c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3536c0f4ce77Saliguori 
3537c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3538c0f4ce77Saliguori         return 1;
3539c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3540c0f4ce77Saliguori }
3541c0f4ce77Saliguori 
3542ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3543ea2384d3Sbellard {
3544ea2384d3Sbellard     int ret;
3545ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3546ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3547ea2384d3Sbellard         if (ret < 0)
3548ea2384d3Sbellard             return ret;
3549ea2384d3Sbellard         if (!bs->encrypted)
3550ea2384d3Sbellard             return 0;
3551ea2384d3Sbellard     }
3552fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3553fd04a2aeSShahar Havivi         return -EINVAL;
3554fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3555fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3556fd04a2aeSShahar Havivi     }
3557c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3558bb5fc20fSaliguori     if (ret < 0) {
3559bb5fc20fSaliguori         bs->valid_key = 0;
3560bb5fc20fSaliguori     } else if (!bs->valid_key) {
3561bb5fc20fSaliguori         bs->valid_key = 1;
3562bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
35637d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3564bb5fc20fSaliguori     }
3565c0f4ce77Saliguori     return ret;
3566ea2384d3Sbellard }
3567ea2384d3Sbellard 
3568f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3569ea2384d3Sbellard {
3570f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3571ea2384d3Sbellard }
3572ea2384d3Sbellard 
3573ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3574ea2384d3Sbellard                          void *opaque)
3575ea2384d3Sbellard {
3576ea2384d3Sbellard     BlockDriver *drv;
3577ea2384d3Sbellard 
35788a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3579ea2384d3Sbellard         it(opaque, drv->format_name);
3580ea2384d3Sbellard     }
3581ea2384d3Sbellard }
3582ea2384d3Sbellard 
3583dc364f4cSBenoît Canet /* This function is to find block backend bs */
3584b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3585b338082bSbellard {
3586b338082bSbellard     BlockDriverState *bs;
3587b338082bSbellard 
3588dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
35891b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3590b338082bSbellard             return bs;
3591b338082bSbellard         }
35921b7bdbc1SStefan Hajnoczi     }
3593b338082bSbellard     return NULL;
3594b338082bSbellard }
3595b338082bSbellard 
3596dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3597dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3598dc364f4cSBenoît Canet {
3599dc364f4cSBenoît Canet     BlockDriverState *bs;
3600dc364f4cSBenoît Canet 
3601dc364f4cSBenoît Canet     assert(node_name);
3602dc364f4cSBenoît Canet 
3603dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3604dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3605dc364f4cSBenoît Canet             return bs;
3606dc364f4cSBenoît Canet         }
3607dc364f4cSBenoît Canet     }
3608dc364f4cSBenoît Canet     return NULL;
3609dc364f4cSBenoît Canet }
3610dc364f4cSBenoît Canet 
3611c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3612c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3613c13163fbSBenoît Canet {
3614c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3615c13163fbSBenoît Canet     BlockDriverState *bs;
3616c13163fbSBenoît Canet 
3617c13163fbSBenoît Canet     list = NULL;
3618c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3619c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3620c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3621c13163fbSBenoît Canet         entry->next = list;
3622c13163fbSBenoît Canet         list = entry;
3623c13163fbSBenoît Canet     }
3624c13163fbSBenoît Canet 
3625c13163fbSBenoît Canet     return list;
3626c13163fbSBenoît Canet }
3627c13163fbSBenoît Canet 
362812d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
362912d3ba82SBenoît Canet                                  const char *node_name,
363012d3ba82SBenoît Canet                                  Error **errp)
363112d3ba82SBenoît Canet {
363212d3ba82SBenoît Canet     BlockDriverState *bs = NULL;
363312d3ba82SBenoît Canet 
363412d3ba82SBenoît Canet     if (device) {
363512d3ba82SBenoît Canet         bs = bdrv_find(device);
363612d3ba82SBenoît Canet 
3637dd67fa50SBenoît Canet         if (bs) {
363812d3ba82SBenoît Canet             return bs;
363912d3ba82SBenoît Canet         }
3640dd67fa50SBenoît Canet     }
364112d3ba82SBenoît Canet 
3642dd67fa50SBenoît Canet     if (node_name) {
364312d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
364412d3ba82SBenoît Canet 
3645dd67fa50SBenoît Canet         if (bs) {
3646dd67fa50SBenoît Canet             return bs;
3647dd67fa50SBenoît Canet         }
364812d3ba82SBenoît Canet     }
364912d3ba82SBenoît Canet 
3650dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
3651dd67fa50SBenoît Canet                      device ? device : "",
3652dd67fa50SBenoît Canet                      node_name ? node_name : "");
3653dd67fa50SBenoît Canet     return NULL;
365412d3ba82SBenoît Canet }
365512d3ba82SBenoît Canet 
36562f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
36572f399b0aSMarkus Armbruster {
36582f399b0aSMarkus Armbruster     if (!bs) {
36592f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
36602f399b0aSMarkus Armbruster     }
3661dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
36622f399b0aSMarkus Armbruster }
36632f399b0aSMarkus Armbruster 
366451de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
366581d0912dSbellard {
366681d0912dSbellard     BlockDriverState *bs;
366781d0912dSbellard 
3668dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
366951de9760Saliguori         it(opaque, bs);
367081d0912dSbellard     }
367181d0912dSbellard }
367281d0912dSbellard 
3673ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3674ea2384d3Sbellard {
3675ea2384d3Sbellard     return bs->device_name;
3676ea2384d3Sbellard }
3677ea2384d3Sbellard 
3678c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3679c8433287SMarkus Armbruster {
3680c8433287SMarkus Armbruster     return bs->open_flags;
3681c8433287SMarkus Armbruster }
3682c8433287SMarkus Armbruster 
3683f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3684c6ca28d6Saliguori {
3685c6ca28d6Saliguori     BlockDriverState *bs;
3686f0f0fdfeSKevin Wolf     int result = 0;
3687c6ca28d6Saliguori 
3688dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3689f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3690f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3691f0f0fdfeSKevin Wolf             result = ret;
3692c6ca28d6Saliguori         }
36931b7bdbc1SStefan Hajnoczi     }
3694c6ca28d6Saliguori 
3695f0f0fdfeSKevin Wolf     return result;
3696f0f0fdfeSKevin Wolf }
3697f0f0fdfeSKevin Wolf 
36983ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
36993ac21627SPeter Lieven {
37003ac21627SPeter Lieven     return 1;
37013ac21627SPeter Lieven }
37023ac21627SPeter Lieven 
3703f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3704f2feebbdSKevin Wolf {
3705f2feebbdSKevin Wolf     assert(bs->drv);
3706f2feebbdSKevin Wolf 
370711212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
370811212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
370911212d8fSPaolo Bonzini     if (bs->backing_hd) {
371011212d8fSPaolo Bonzini         return 0;
371111212d8fSPaolo Bonzini     }
3712336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3713336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3714f2feebbdSKevin Wolf     }
3715f2feebbdSKevin Wolf 
37163ac21627SPeter Lieven     /* safe default */
37173ac21627SPeter Lieven     return 0;
3718f2feebbdSKevin Wolf }
3719f2feebbdSKevin Wolf 
37204ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
37214ce78691SPeter Lieven {
37224ce78691SPeter Lieven     BlockDriverInfo bdi;
37234ce78691SPeter Lieven 
37244ce78691SPeter Lieven     if (bs->backing_hd) {
37254ce78691SPeter Lieven         return false;
37264ce78691SPeter Lieven     }
37274ce78691SPeter Lieven 
37284ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
37294ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
37304ce78691SPeter Lieven     }
37314ce78691SPeter Lieven 
37324ce78691SPeter Lieven     return false;
37334ce78691SPeter Lieven }
37344ce78691SPeter Lieven 
37354ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
37364ce78691SPeter Lieven {
37374ce78691SPeter Lieven     BlockDriverInfo bdi;
37384ce78691SPeter Lieven 
37394ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
37404ce78691SPeter Lieven         return false;
37414ce78691SPeter Lieven     }
37424ce78691SPeter Lieven 
37434ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
37444ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
37454ce78691SPeter Lieven     }
37464ce78691SPeter Lieven 
37474ce78691SPeter Lieven     return false;
37484ce78691SPeter Lieven }
37494ce78691SPeter Lieven 
3750b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3751376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3752b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3753376ae3f1SStefan Hajnoczi     int64_t sector_num;
3754376ae3f1SStefan Hajnoczi     int nb_sectors;
3755376ae3f1SStefan Hajnoczi     int *pnum;
3756b6b8a333SPaolo Bonzini     int64_t ret;
3757376ae3f1SStefan Hajnoczi     bool done;
3758b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3759376ae3f1SStefan Hajnoczi 
3760f58c7b35Sths /*
3761f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3762f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3763f58c7b35Sths  * hence all their sectors are reported as allocated.
3764f58c7b35Sths  *
3765bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3766bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3767bd9533e3SStefan Hajnoczi  *
3768f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3769f58c7b35Sths  * the specified sector) that are known to be in the same
3770f58c7b35Sths  * allocated/unallocated state.
3771f58c7b35Sths  *
3772bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3773bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3774f58c7b35Sths  */
3775b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3776bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3777060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3778f58c7b35Sths {
3779617ccb46SPaolo Bonzini     int64_t length;
3780f58c7b35Sths     int64_t n;
37815daa74a6SPaolo Bonzini     int64_t ret, ret2;
3782bd9533e3SStefan Hajnoczi 
3783617ccb46SPaolo Bonzini     length = bdrv_getlength(bs);
3784617ccb46SPaolo Bonzini     if (length < 0) {
3785617ccb46SPaolo Bonzini         return length;
3786617ccb46SPaolo Bonzini     }
3787617ccb46SPaolo Bonzini 
3788617ccb46SPaolo Bonzini     if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
37896aebab14SStefan Hajnoczi         *pnum = 0;
37906aebab14SStefan Hajnoczi         return 0;
37916aebab14SStefan Hajnoczi     }
3792bd9533e3SStefan Hajnoczi 
37936aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3794bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3795bd9533e3SStefan Hajnoczi         nb_sectors = n;
3796bd9533e3SStefan Hajnoczi     }
3797bd9533e3SStefan Hajnoczi 
3798b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3799bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3800918e92d7SPaolo Bonzini         ret = BDRV_BLOCK_DATA;
3801918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3802918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3803918e92d7SPaolo Bonzini         }
3804918e92d7SPaolo Bonzini         return ret;
38056aebab14SStefan Hajnoczi     }
38066aebab14SStefan Hajnoczi 
3807415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3808415b5b01SPaolo Bonzini     if (ret < 0) {
38093e0a233dSPeter Lieven         *pnum = 0;
3810415b5b01SPaolo Bonzini         return ret;
3811415b5b01SPaolo Bonzini     }
3812415b5b01SPaolo Bonzini 
381392bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
381492bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
381592bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
381692bc50a5SPeter Lieven                                      *pnum, pnum);
381792bc50a5SPeter Lieven     }
381892bc50a5SPeter Lieven 
3819c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3820c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
3821415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
38221f9db224SPeter Lieven         } else if (bs->backing_hd) {
3823f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
3824f0ad5712SPaolo Bonzini             int64_t length2 = bdrv_getlength(bs2);
3825f0ad5712SPaolo Bonzini             if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3826f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3827f0ad5712SPaolo Bonzini             }
3828f0ad5712SPaolo Bonzini         }
3829415b5b01SPaolo Bonzini     }
38305daa74a6SPaolo Bonzini 
38315daa74a6SPaolo Bonzini     if (bs->file &&
38325daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
38335daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
38345daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
38355daa74a6SPaolo Bonzini                                         *pnum, pnum);
38365daa74a6SPaolo Bonzini         if (ret2 >= 0) {
38375daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
38385daa74a6SPaolo Bonzini              * is useful but not necessary.
38395daa74a6SPaolo Bonzini              */
38405daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
38415daa74a6SPaolo Bonzini         }
38425daa74a6SPaolo Bonzini     }
38435daa74a6SPaolo Bonzini 
3844415b5b01SPaolo Bonzini     return ret;
3845060f51c9SStefan Hajnoczi }
3846060f51c9SStefan Hajnoczi 
3847b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3848b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3849060f51c9SStefan Hajnoczi {
3850b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3851060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3852060f51c9SStefan Hajnoczi 
3853b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3854060f51c9SStefan Hajnoczi                                          data->pnum);
3855060f51c9SStefan Hajnoczi     data->done = true;
3856060f51c9SStefan Hajnoczi }
3857060f51c9SStefan Hajnoczi 
3858060f51c9SStefan Hajnoczi /*
3859b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3860060f51c9SStefan Hajnoczi  *
3861b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
3862060f51c9SStefan Hajnoczi  */
3863b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3864b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
3865060f51c9SStefan Hajnoczi {
3866376ae3f1SStefan Hajnoczi     Coroutine *co;
3867b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
3868376ae3f1SStefan Hajnoczi         .bs = bs,
3869376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3870376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3871376ae3f1SStefan Hajnoczi         .pnum = pnum,
3872376ae3f1SStefan Hajnoczi         .done = false,
3873376ae3f1SStefan Hajnoczi     };
3874376ae3f1SStefan Hajnoczi 
3875bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
3876bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
3877b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
3878bdad13b9SPaolo Bonzini     } else {
3879b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
3880376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
3881376ae3f1SStefan Hajnoczi         while (!data.done) {
3882376ae3f1SStefan Hajnoczi             qemu_aio_wait();
3883376ae3f1SStefan Hajnoczi         }
3884bdad13b9SPaolo Bonzini     }
3885376ae3f1SStefan Hajnoczi     return data.ret;
3886376ae3f1SStefan Hajnoczi }
3887f58c7b35Sths 
3888b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
3889b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
3890b6b8a333SPaolo Bonzini {
38914333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
38924333bb71SPaolo Bonzini     if (ret < 0) {
38934333bb71SPaolo Bonzini         return ret;
38944333bb71SPaolo Bonzini     }
38954333bb71SPaolo Bonzini     return
38964333bb71SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) ||
38974333bb71SPaolo Bonzini         ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
3898b6b8a333SPaolo Bonzini }
3899b6b8a333SPaolo Bonzini 
3900188a7bbfSPaolo Bonzini /*
3901188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3902188a7bbfSPaolo Bonzini  *
3903188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3904188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3905188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3906188a7bbfSPaolo Bonzini  *
3907188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3908188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3909188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3910188a7bbfSPaolo Bonzini  *
3911188a7bbfSPaolo Bonzini  */
39124f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
3913188a7bbfSPaolo Bonzini                             BlockDriverState *base,
3914188a7bbfSPaolo Bonzini                             int64_t sector_num,
3915188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
3916188a7bbfSPaolo Bonzini {
3917188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3918188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3919188a7bbfSPaolo Bonzini 
3920188a7bbfSPaolo Bonzini     intermediate = top;
3921188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3922188a7bbfSPaolo Bonzini         int pnum_inter;
3923bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
3924188a7bbfSPaolo Bonzini                                 &pnum_inter);
3925188a7bbfSPaolo Bonzini         if (ret < 0) {
3926188a7bbfSPaolo Bonzini             return ret;
3927188a7bbfSPaolo Bonzini         } else if (ret) {
3928188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3929188a7bbfSPaolo Bonzini             return 1;
3930188a7bbfSPaolo Bonzini         }
3931188a7bbfSPaolo Bonzini 
3932188a7bbfSPaolo Bonzini         /*
3933188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3934188a7bbfSPaolo Bonzini          * might have
3935188a7bbfSPaolo Bonzini          *
3936188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3937188a7bbfSPaolo Bonzini          */
393863ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
393963ba17d3SVishvananda Ishaya             (intermediate == top ||
394063ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3941188a7bbfSPaolo Bonzini             n = pnum_inter;
3942188a7bbfSPaolo Bonzini         }
3943188a7bbfSPaolo Bonzini 
3944188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3945188a7bbfSPaolo Bonzini     }
3946188a7bbfSPaolo Bonzini 
3947188a7bbfSPaolo Bonzini     *pnum = n;
3948188a7bbfSPaolo Bonzini     return 0;
3949188a7bbfSPaolo Bonzini }
3950188a7bbfSPaolo Bonzini 
3951045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3952045df330Saliguori {
3953045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3954045df330Saliguori         return bs->backing_file;
3955045df330Saliguori     else if (bs->encrypted)
3956045df330Saliguori         return bs->filename;
3957045df330Saliguori     else
3958045df330Saliguori         return NULL;
3959045df330Saliguori }
3960045df330Saliguori 
396183f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
396283f64091Sbellard                                char *filename, int filename_size)
396383f64091Sbellard {
396483f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
396583f64091Sbellard }
396683f64091Sbellard 
3967faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3968faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3969faea38e7Sbellard {
3970faea38e7Sbellard     BlockDriver *drv = bs->drv;
3971faea38e7Sbellard     if (!drv)
397219cb3738Sbellard         return -ENOMEDIUM;
3973faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3974faea38e7Sbellard         return -ENOTSUP;
3975fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3976fbb7b4e0SKevin Wolf         return -EIO;
39777cd1e32aSlirans@il.ibm.com 
3978e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
39797cd1e32aSlirans@il.ibm.com 
3980faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3981faea38e7Sbellard }
3982faea38e7Sbellard 
3983faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3984faea38e7Sbellard {
3985faea38e7Sbellard     BlockDriver *drv = bs->drv;
3986faea38e7Sbellard     if (!drv)
398719cb3738Sbellard         return -ENOMEDIUM;
3988faea38e7Sbellard     if (!drv->bdrv_get_info)
3989faea38e7Sbellard         return -ENOTSUP;
3990faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3991faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3992faea38e7Sbellard }
3993faea38e7Sbellard 
3994eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3995eae041feSMax Reitz {
3996eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3997eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3998eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3999eae041feSMax Reitz     }
4000eae041feSMax Reitz     return NULL;
4001eae041feSMax Reitz }
4002eae041feSMax Reitz 
400345566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
400445566e9cSChristoph Hellwig                       int64_t pos, int size)
4005178e08a5Saliguori {
4006cf8074b3SKevin Wolf     QEMUIOVector qiov;
4007cf8074b3SKevin Wolf     struct iovec iov = {
4008cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
4009cf8074b3SKevin Wolf         .iov_len    = size,
4010cf8074b3SKevin Wolf     };
4011cf8074b3SKevin Wolf 
4012cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
4013cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
4014cf8074b3SKevin Wolf }
4015cf8074b3SKevin Wolf 
4016cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
4017cf8074b3SKevin Wolf {
4018178e08a5Saliguori     BlockDriver *drv = bs->drv;
4019cf8074b3SKevin Wolf 
4020cf8074b3SKevin Wolf     if (!drv) {
4021178e08a5Saliguori         return -ENOMEDIUM;
4022cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
4023cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
4024cf8074b3SKevin Wolf     } else if (bs->file) {
4025cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
4026cf8074b3SKevin Wolf     }
4027cf8074b3SKevin Wolf 
40287cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4029178e08a5Saliguori }
4030178e08a5Saliguori 
403145566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
403245566e9cSChristoph Hellwig                       int64_t pos, int size)
4033178e08a5Saliguori {
4034178e08a5Saliguori     BlockDriver *drv = bs->drv;
4035178e08a5Saliguori     if (!drv)
4036178e08a5Saliguori         return -ENOMEDIUM;
40377cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
403845566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
40397cdb1f6dSMORITA Kazutaka     if (bs->file)
40407cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
40417cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4042178e08a5Saliguori }
4043178e08a5Saliguori 
40448b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
40458b9b0cc2SKevin Wolf {
4046bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
40478b9b0cc2SKevin Wolf         return;
40488b9b0cc2SKevin Wolf     }
40498b9b0cc2SKevin Wolf 
4050bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
405141c695c7SKevin Wolf }
40528b9b0cc2SKevin Wolf 
405341c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
405441c695c7SKevin Wolf                           const char *tag)
405541c695c7SKevin Wolf {
405641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
405741c695c7SKevin Wolf         bs = bs->file;
405841c695c7SKevin Wolf     }
405941c695c7SKevin Wolf 
406041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
406141c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
406241c695c7SKevin Wolf     }
406341c695c7SKevin Wolf 
406441c695c7SKevin Wolf     return -ENOTSUP;
406541c695c7SKevin Wolf }
406641c695c7SKevin Wolf 
40674cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
40684cc70e93SFam Zheng {
40694cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
40704cc70e93SFam Zheng         bs = bs->file;
40714cc70e93SFam Zheng     }
40724cc70e93SFam Zheng 
40734cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
40744cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
40754cc70e93SFam Zheng     }
40764cc70e93SFam Zheng 
40774cc70e93SFam Zheng     return -ENOTSUP;
40784cc70e93SFam Zheng }
40794cc70e93SFam Zheng 
408041c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
408141c695c7SKevin Wolf {
4082938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
408341c695c7SKevin Wolf         bs = bs->file;
408441c695c7SKevin Wolf     }
408541c695c7SKevin Wolf 
408641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
408741c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
408841c695c7SKevin Wolf     }
408941c695c7SKevin Wolf 
409041c695c7SKevin Wolf     return -ENOTSUP;
409141c695c7SKevin Wolf }
409241c695c7SKevin Wolf 
409341c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
409441c695c7SKevin Wolf {
409541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
409641c695c7SKevin Wolf         bs = bs->file;
409741c695c7SKevin Wolf     }
409841c695c7SKevin Wolf 
409941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
410041c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
410141c695c7SKevin Wolf     }
410241c695c7SKevin Wolf 
410341c695c7SKevin Wolf     return false;
41048b9b0cc2SKevin Wolf }
41058b9b0cc2SKevin Wolf 
4106199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
4107199630b6SBlue Swirl {
4108199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4109199630b6SBlue Swirl }
4110199630b6SBlue Swirl 
4111b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
4112b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
4113b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
4114b1b1d783SJeff Cody  * the CWD rather than the chain. */
4115e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4116e8a6bb9cSMarcelo Tosatti         const char *backing_file)
4117e8a6bb9cSMarcelo Tosatti {
4118b1b1d783SJeff Cody     char *filename_full = NULL;
4119b1b1d783SJeff Cody     char *backing_file_full = NULL;
4120b1b1d783SJeff Cody     char *filename_tmp = NULL;
4121b1b1d783SJeff Cody     int is_protocol = 0;
4122b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
4123b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
4124b1b1d783SJeff Cody 
4125b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
4126e8a6bb9cSMarcelo Tosatti         return NULL;
4127e8a6bb9cSMarcelo Tosatti     }
4128e8a6bb9cSMarcelo Tosatti 
4129b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
4130b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
4131b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
4132b1b1d783SJeff Cody 
4133b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
4134b1b1d783SJeff Cody 
4135b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4136b1b1d783SJeff Cody 
4137b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
4138b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
4139b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4140b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4141b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4142b1b1d783SJeff Cody                 break;
4143b1b1d783SJeff Cody             }
4144e8a6bb9cSMarcelo Tosatti         } else {
4145b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
4146b1b1d783SJeff Cody              * image's filename path */
4147b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4148b1b1d783SJeff Cody                          backing_file);
4149b1b1d783SJeff Cody 
4150b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
4151b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
4152b1b1d783SJeff Cody                 continue;
4153b1b1d783SJeff Cody             }
4154b1b1d783SJeff Cody 
4155b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
4156b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
4157b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4158b1b1d783SJeff Cody                          curr_bs->backing_file);
4159b1b1d783SJeff Cody 
4160b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
4161b1b1d783SJeff Cody                 continue;
4162b1b1d783SJeff Cody             }
4163b1b1d783SJeff Cody 
4164b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
4165b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4166b1b1d783SJeff Cody                 break;
4167b1b1d783SJeff Cody             }
4168e8a6bb9cSMarcelo Tosatti         }
4169e8a6bb9cSMarcelo Tosatti     }
4170e8a6bb9cSMarcelo Tosatti 
4171b1b1d783SJeff Cody     g_free(filename_full);
4172b1b1d783SJeff Cody     g_free(backing_file_full);
4173b1b1d783SJeff Cody     g_free(filename_tmp);
4174b1b1d783SJeff Cody     return retval;
4175e8a6bb9cSMarcelo Tosatti }
4176e8a6bb9cSMarcelo Tosatti 
4177f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
4178f198fd1cSBenoît Canet {
4179f198fd1cSBenoît Canet     if (!bs->drv) {
4180f198fd1cSBenoît Canet         return 0;
4181f198fd1cSBenoît Canet     }
4182f198fd1cSBenoît Canet 
4183f198fd1cSBenoît Canet     if (!bs->backing_hd) {
4184f198fd1cSBenoît Canet         return 0;
4185f198fd1cSBenoît Canet     }
4186f198fd1cSBenoît Canet 
4187f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4188f198fd1cSBenoît Canet }
4189f198fd1cSBenoît Canet 
419079fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
419179fac568SJeff Cody {
419279fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
419379fac568SJeff Cody 
419479fac568SJeff Cody     if (!bs) {
419579fac568SJeff Cody         return NULL;
419679fac568SJeff Cody     }
419779fac568SJeff Cody 
419879fac568SJeff Cody     curr_bs = bs;
419979fac568SJeff Cody 
420079fac568SJeff Cody     while (curr_bs->backing_hd) {
420179fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
420279fac568SJeff Cody     }
420379fac568SJeff Cody     return curr_bs;
420479fac568SJeff Cody }
420579fac568SJeff Cody 
4206ea2384d3Sbellard /**************************************************************/
420783f64091Sbellard /* async I/Os */
4208ea2384d3Sbellard 
42093b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
4210f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
421183f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
4212ea2384d3Sbellard {
4213bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4214bbf0a440SStefan Hajnoczi 
4215d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
42168c5873d6SStefan Hajnoczi                                  cb, opaque, false);
421783f64091Sbellard }
421883f64091Sbellard 
4219f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4220f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
422183f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
42227674e7bfSbellard {
4223bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4224bbf0a440SStefan Hajnoczi 
4225d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
42268c5873d6SStefan Hajnoczi                                  cb, opaque, true);
422783f64091Sbellard }
422883f64091Sbellard 
4229d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4230d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4231d5ef94d4SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
4232d5ef94d4SPaolo Bonzini {
4233d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4234d5ef94d4SPaolo Bonzini 
4235d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4236d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4237d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4238d5ef94d4SPaolo Bonzini }
4239d5ef94d4SPaolo Bonzini 
424040b4f539SKevin Wolf 
424140b4f539SKevin Wolf typedef struct MultiwriteCB {
424240b4f539SKevin Wolf     int error;
424340b4f539SKevin Wolf     int num_requests;
424440b4f539SKevin Wolf     int num_callbacks;
424540b4f539SKevin Wolf     struct {
424640b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
424740b4f539SKevin Wolf         void *opaque;
424840b4f539SKevin Wolf         QEMUIOVector *free_qiov;
424940b4f539SKevin Wolf     } callbacks[];
425040b4f539SKevin Wolf } MultiwriteCB;
425140b4f539SKevin Wolf 
425240b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
425340b4f539SKevin Wolf {
425440b4f539SKevin Wolf     int i;
425540b4f539SKevin Wolf 
425640b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
425740b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
42581e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
42591e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
42601e1ea48dSStefan Hajnoczi         }
42617267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
426240b4f539SKevin Wolf     }
426340b4f539SKevin Wolf }
426440b4f539SKevin Wolf 
426540b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
426640b4f539SKevin Wolf {
426740b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
426840b4f539SKevin Wolf 
42696d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
42706d519a5fSStefan Hajnoczi 
4271cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
427240b4f539SKevin Wolf         mcb->error = ret;
427340b4f539SKevin Wolf     }
427440b4f539SKevin Wolf 
427540b4f539SKevin Wolf     mcb->num_requests--;
427640b4f539SKevin Wolf     if (mcb->num_requests == 0) {
427740b4f539SKevin Wolf         multiwrite_user_cb(mcb);
42787267c094SAnthony Liguori         g_free(mcb);
427940b4f539SKevin Wolf     }
428040b4f539SKevin Wolf }
428140b4f539SKevin Wolf 
428240b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
428340b4f539SKevin Wolf {
428477be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
428577be4366SChristoph Hellwig 
428677be4366SChristoph Hellwig     /*
428777be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
428877be4366SChristoph Hellwig      * here as that could overflow the return value.
428977be4366SChristoph Hellwig      */
429077be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
429177be4366SChristoph Hellwig         return 1;
429277be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
429377be4366SChristoph Hellwig         return -1;
429477be4366SChristoph Hellwig     } else {
429577be4366SChristoph Hellwig         return 0;
429677be4366SChristoph Hellwig     }
429740b4f539SKevin Wolf }
429840b4f539SKevin Wolf 
429940b4f539SKevin Wolf /*
430040b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
430140b4f539SKevin Wolf  * requests that remain after merging.
430240b4f539SKevin Wolf  */
430340b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
430440b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
430540b4f539SKevin Wolf {
430640b4f539SKevin Wolf     int i, outidx;
430740b4f539SKevin Wolf 
430840b4f539SKevin Wolf     // Sort requests by start sector
430940b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
431040b4f539SKevin Wolf 
431140b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
431240b4f539SKevin Wolf     // filling up gaps with zero sectors.
431340b4f539SKevin Wolf     outidx = 0;
431440b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
431540b4f539SKevin Wolf         int merge = 0;
431640b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
431740b4f539SKevin Wolf 
4318b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
431940b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
432040b4f539SKevin Wolf             merge = 1;
432140b4f539SKevin Wolf         }
432240b4f539SKevin Wolf 
4323e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4324e2a305fbSChristoph Hellwig             merge = 0;
4325e2a305fbSChristoph Hellwig         }
4326e2a305fbSChristoph Hellwig 
432740b4f539SKevin Wolf         if (merge) {
432840b4f539SKevin Wolf             size_t size;
43297267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
433040b4f539SKevin Wolf             qemu_iovec_init(qiov,
433140b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
433240b4f539SKevin Wolf 
433340b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
433440b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
433540b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
43361b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
433740b4f539SKevin Wolf 
4338b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4339b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
434040b4f539SKevin Wolf 
434140b4f539SKevin Wolf             // Add the second request
43421b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
434340b4f539SKevin Wolf 
4344cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
434540b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
434640b4f539SKevin Wolf 
434740b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
434840b4f539SKevin Wolf         } else {
434940b4f539SKevin Wolf             outidx++;
435040b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
435140b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
435240b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
435340b4f539SKevin Wolf         }
435440b4f539SKevin Wolf     }
435540b4f539SKevin Wolf 
435640b4f539SKevin Wolf     return outidx + 1;
435740b4f539SKevin Wolf }
435840b4f539SKevin Wolf 
435940b4f539SKevin Wolf /*
436040b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
436140b4f539SKevin Wolf  *
436240b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
436340b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
436440b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
436540b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
436640b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
436740b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
436840b4f539SKevin Wolf  *
436940b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
437040b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
437140b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
437240b4f539SKevin Wolf  */
437340b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
437440b4f539SKevin Wolf {
437540b4f539SKevin Wolf     MultiwriteCB *mcb;
437640b4f539SKevin Wolf     int i;
437740b4f539SKevin Wolf 
4378301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4379301db7c2SRyan Harper     if (bs->drv == NULL) {
4380301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4381301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4382301db7c2SRyan Harper         }
4383301db7c2SRyan Harper         return -1;
4384301db7c2SRyan Harper     }
4385301db7c2SRyan Harper 
438640b4f539SKevin Wolf     if (num_reqs == 0) {
438740b4f539SKevin Wolf         return 0;
438840b4f539SKevin Wolf     }
438940b4f539SKevin Wolf 
439040b4f539SKevin Wolf     // Create MultiwriteCB structure
43917267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
439240b4f539SKevin Wolf     mcb->num_requests = 0;
439340b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
439440b4f539SKevin Wolf 
439540b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
439640b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
439740b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
439840b4f539SKevin Wolf     }
439940b4f539SKevin Wolf 
440040b4f539SKevin Wolf     // Check for mergable requests
440140b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
440240b4f539SKevin Wolf 
44036d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
44046d519a5fSStefan Hajnoczi 
4405df9309fbSPaolo Bonzini     /* Run the aio requests. */
4406df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
440740b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4408d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4409d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4410d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4411d20d9b7cSPaolo Bonzini                               true);
441240b4f539SKevin Wolf     }
441340b4f539SKevin Wolf 
441440b4f539SKevin Wolf     return 0;
441540b4f539SKevin Wolf }
441640b4f539SKevin Wolf 
441783f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
441883f64091Sbellard {
4419d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
442083f64091Sbellard }
442183f64091Sbellard 
442283f64091Sbellard /**************************************************************/
442383f64091Sbellard /* async block device emulation */
442483f64091Sbellard 
4425c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4426c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4427c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4428c16b5a2cSChristoph Hellwig     int ret;
4429c16b5a2cSChristoph Hellwig     /* vector translation state */
4430c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4431c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4432c16b5a2cSChristoph Hellwig     int is_write;
4433c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4434c16b5a2cSChristoph Hellwig 
4435c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4436c16b5a2cSChristoph Hellwig {
4437b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
4438b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
44396a7ad299SDor Laor     qemu_bh_delete(acb->bh);
444036afc451SAvi Kivity     acb->bh = NULL;
4441c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
4442c16b5a2cSChristoph Hellwig }
4443c16b5a2cSChristoph Hellwig 
4444d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4445c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4446c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
4447c16b5a2cSChristoph Hellwig };
4448c16b5a2cSChristoph Hellwig 
444983f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4450beac80cdSbellard {
4451ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4452f141eafeSaliguori 
4453f141eafeSaliguori     if (!acb->is_write)
445403396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4455ceb42de8Saliguori     qemu_vfree(acb->bounce);
4456ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
44576a7ad299SDor Laor     qemu_bh_delete(acb->bh);
445836afc451SAvi Kivity     acb->bh = NULL;
4459ce1a14dcSpbrook     qemu_aio_release(acb);
4460beac80cdSbellard }
4461beac80cdSbellard 
4462f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4463f141eafeSaliguori                                             int64_t sector_num,
4464f141eafeSaliguori                                             QEMUIOVector *qiov,
4465f141eafeSaliguori                                             int nb_sectors,
4466f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4467f141eafeSaliguori                                             void *opaque,
4468f141eafeSaliguori                                             int is_write)
4469f141eafeSaliguori 
4470ea2384d3Sbellard {
4471ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
447283f64091Sbellard 
4473d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4474f141eafeSaliguori     acb->is_write = is_write;
4475f141eafeSaliguori     acb->qiov = qiov;
4476e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
4477ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4478f141eafeSaliguori 
4479f141eafeSaliguori     if (is_write) {
4480d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
44811ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4482f141eafeSaliguori     } else {
44831ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4484f141eafeSaliguori     }
4485f141eafeSaliguori 
4486ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4487f141eafeSaliguori 
4488ce1a14dcSpbrook     return &acb->common;
44897a6cba61Spbrook }
44907a6cba61Spbrook 
4491f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4492f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4493ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
449483f64091Sbellard {
4495f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
449683f64091Sbellard }
449783f64091Sbellard 
4498f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4499f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4500f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4501f141eafeSaliguori {
4502f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4503f141eafeSaliguori }
4504f141eafeSaliguori 
450568485420SKevin Wolf 
450668485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
450768485420SKevin Wolf     BlockDriverAIOCB common;
450868485420SKevin Wolf     BlockRequest req;
450968485420SKevin Wolf     bool is_write;
4510d318aea9SKevin Wolf     bool *done;
451168485420SKevin Wolf     QEMUBH* bh;
451268485420SKevin Wolf } BlockDriverAIOCBCoroutine;
451368485420SKevin Wolf 
451468485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
451568485420SKevin Wolf {
4516d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
4517d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4518d318aea9SKevin Wolf     bool done = false;
4519d318aea9SKevin Wolf 
4520d318aea9SKevin Wolf     acb->done = &done;
4521d318aea9SKevin Wolf     while (!done) {
4522d318aea9SKevin Wolf         qemu_aio_wait();
4523d318aea9SKevin Wolf     }
452468485420SKevin Wolf }
452568485420SKevin Wolf 
4526d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
452768485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
452868485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
452968485420SKevin Wolf };
453068485420SKevin Wolf 
453135246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
453268485420SKevin Wolf {
453368485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
453468485420SKevin Wolf 
453568485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4536d318aea9SKevin Wolf 
4537d318aea9SKevin Wolf     if (acb->done) {
4538d318aea9SKevin Wolf         *acb->done = true;
4539d318aea9SKevin Wolf     }
4540d318aea9SKevin Wolf 
454168485420SKevin Wolf     qemu_bh_delete(acb->bh);
454268485420SKevin Wolf     qemu_aio_release(acb);
454368485420SKevin Wolf }
454468485420SKevin Wolf 
4545b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4546b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4547b2a61371SStefan Hajnoczi {
4548b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4549b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4550b2a61371SStefan Hajnoczi 
4551b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4552b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4553d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4554b2a61371SStefan Hajnoczi     } else {
4555b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4556d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4557b2a61371SStefan Hajnoczi     }
4558b2a61371SStefan Hajnoczi 
455935246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4560b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4561b2a61371SStefan Hajnoczi }
4562b2a61371SStefan Hajnoczi 
456368485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
456468485420SKevin Wolf                                                int64_t sector_num,
456568485420SKevin Wolf                                                QEMUIOVector *qiov,
456668485420SKevin Wolf                                                int nb_sectors,
4567d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
456868485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
456968485420SKevin Wolf                                                void *opaque,
45708c5873d6SStefan Hajnoczi                                                bool is_write)
457168485420SKevin Wolf {
457268485420SKevin Wolf     Coroutine *co;
457368485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
457468485420SKevin Wolf 
4575d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
457668485420SKevin Wolf     acb->req.sector = sector_num;
457768485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
457868485420SKevin Wolf     acb->req.qiov = qiov;
4579d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
458068485420SKevin Wolf     acb->is_write = is_write;
4581d318aea9SKevin Wolf     acb->done = NULL;
458268485420SKevin Wolf 
45838c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
458468485420SKevin Wolf     qemu_coroutine_enter(co, acb);
458568485420SKevin Wolf 
458668485420SKevin Wolf     return &acb->common;
458768485420SKevin Wolf }
458868485420SKevin Wolf 
458907f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4590b2e12bc6SChristoph Hellwig {
459107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
459207f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4593b2e12bc6SChristoph Hellwig 
459407f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
459507f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4596b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4597b2e12bc6SChristoph Hellwig }
4598b2e12bc6SChristoph Hellwig 
459907f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4600016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4601016f5cf6SAlexander Graf {
460207f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4603016f5cf6SAlexander Graf 
460407f07615SPaolo Bonzini     Coroutine *co;
460507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4606016f5cf6SAlexander Graf 
4607d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4608d318aea9SKevin Wolf     acb->done = NULL;
4609d318aea9SKevin Wolf 
461007f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
461107f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4612016f5cf6SAlexander Graf 
4613016f5cf6SAlexander Graf     return &acb->common;
4614016f5cf6SAlexander Graf }
4615016f5cf6SAlexander Graf 
46164265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
46174265d620SPaolo Bonzini {
46184265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
46194265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
46204265d620SPaolo Bonzini 
46214265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
46224265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
46234265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
46244265d620SPaolo Bonzini }
46254265d620SPaolo Bonzini 
46264265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
46274265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
46284265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
46294265d620SPaolo Bonzini {
46304265d620SPaolo Bonzini     Coroutine *co;
46314265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
46324265d620SPaolo Bonzini 
46334265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
46344265d620SPaolo Bonzini 
4635d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
46364265d620SPaolo Bonzini     acb->req.sector = sector_num;
46374265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4638d318aea9SKevin Wolf     acb->done = NULL;
46394265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
46404265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
46414265d620SPaolo Bonzini 
46424265d620SPaolo Bonzini     return &acb->common;
46434265d620SPaolo Bonzini }
46444265d620SPaolo Bonzini 
4645ea2384d3Sbellard void bdrv_init(void)
4646ea2384d3Sbellard {
46475efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4648ea2384d3Sbellard }
4649ce1a14dcSpbrook 
4650eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4651eb852011SMarkus Armbruster {
4652eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4653eb852011SMarkus Armbruster     bdrv_init();
4654eb852011SMarkus Armbruster }
4655eb852011SMarkus Armbruster 
4656d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
46576bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
46586bbff9a0Saliguori {
4659ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4660ce1a14dcSpbrook 
4661d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4662d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4663ce1a14dcSpbrook     acb->bs = bs;
4664ce1a14dcSpbrook     acb->cb = cb;
4665ce1a14dcSpbrook     acb->opaque = opaque;
4666ce1a14dcSpbrook     return acb;
4667ce1a14dcSpbrook }
4668ce1a14dcSpbrook 
4669ce1a14dcSpbrook void qemu_aio_release(void *p)
4670ce1a14dcSpbrook {
4671d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4672d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4673ce1a14dcSpbrook }
467419cb3738Sbellard 
467519cb3738Sbellard /**************************************************************/
4676f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4677f9f05dc5SKevin Wolf 
4678f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4679f9f05dc5SKevin Wolf     Coroutine *coroutine;
4680f9f05dc5SKevin Wolf     int ret;
4681f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4682f9f05dc5SKevin Wolf 
4683f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4684f9f05dc5SKevin Wolf {
4685f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4686f9f05dc5SKevin Wolf 
4687f9f05dc5SKevin Wolf     co->ret = ret;
4688f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4689f9f05dc5SKevin Wolf }
4690f9f05dc5SKevin Wolf 
4691f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4692f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4693f9f05dc5SKevin Wolf                                       bool is_write)
4694f9f05dc5SKevin Wolf {
4695f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4696f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4697f9f05dc5SKevin Wolf     };
4698f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4699f9f05dc5SKevin Wolf 
4700f9f05dc5SKevin Wolf     if (is_write) {
4701a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4702f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4703f9f05dc5SKevin Wolf     } else {
4704a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4705f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4706f9f05dc5SKevin Wolf     }
4707f9f05dc5SKevin Wolf 
470859370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4709f9f05dc5SKevin Wolf     if (!acb) {
4710f9f05dc5SKevin Wolf         return -EIO;
4711f9f05dc5SKevin Wolf     }
4712f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4713f9f05dc5SKevin Wolf 
4714f9f05dc5SKevin Wolf     return co.ret;
4715f9f05dc5SKevin Wolf }
4716f9f05dc5SKevin Wolf 
4717f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4718f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4719f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4720f9f05dc5SKevin Wolf {
4721f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4722f9f05dc5SKevin Wolf }
4723f9f05dc5SKevin Wolf 
4724f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4725f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4726f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4727f9f05dc5SKevin Wolf {
4728f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4729f9f05dc5SKevin Wolf }
4730f9f05dc5SKevin Wolf 
473107f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4732e7a8a783SKevin Wolf {
473307f07615SPaolo Bonzini     RwCo *rwco = opaque;
473407f07615SPaolo Bonzini 
473507f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
473607f07615SPaolo Bonzini }
473707f07615SPaolo Bonzini 
473807f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
473907f07615SPaolo Bonzini {
4740eb489bb1SKevin Wolf     int ret;
4741eb489bb1SKevin Wolf 
474229cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
474307f07615SPaolo Bonzini         return 0;
4744eb489bb1SKevin Wolf     }
4745eb489bb1SKevin Wolf 
4746ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4747bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4748eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4749eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4750eb489bb1SKevin Wolf         if (ret < 0) {
4751eb489bb1SKevin Wolf             return ret;
4752eb489bb1SKevin Wolf         }
4753eb489bb1SKevin Wolf     }
4754eb489bb1SKevin Wolf 
4755ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4756ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4757d4c82329SKevin Wolf         goto flush_parent;
4758ca716364SKevin Wolf     }
4759ca716364SKevin Wolf 
4760bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4761eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
476229cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
476307f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
476407f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4765e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4766e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4767e7a8a783SKevin Wolf         };
4768e7a8a783SKevin Wolf 
476907f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
477007f07615SPaolo Bonzini         if (acb == NULL) {
477129cdb251SPaolo Bonzini             ret = -EIO;
477207f07615SPaolo Bonzini         } else {
4773e7a8a783SKevin Wolf             qemu_coroutine_yield();
477429cdb251SPaolo Bonzini             ret = co.ret;
4775e7a8a783SKevin Wolf         }
477607f07615SPaolo Bonzini     } else {
477707f07615SPaolo Bonzini         /*
477807f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
477907f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
478007f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
478107f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
478207f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
478307f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
478407f07615SPaolo Bonzini          * mode.
478507f07615SPaolo Bonzini          *
478607f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
478707f07615SPaolo Bonzini          */
478829cdb251SPaolo Bonzini         ret = 0;
478907f07615SPaolo Bonzini     }
479029cdb251SPaolo Bonzini     if (ret < 0) {
479129cdb251SPaolo Bonzini         return ret;
479229cdb251SPaolo Bonzini     }
479329cdb251SPaolo Bonzini 
479429cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
479529cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
479629cdb251SPaolo Bonzini      */
4797d4c82329SKevin Wolf flush_parent:
479829cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
479907f07615SPaolo Bonzini }
480007f07615SPaolo Bonzini 
48015a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
48020f15423cSAnthony Liguori {
48035a8a30dbSKevin Wolf     Error *local_err = NULL;
48045a8a30dbSKevin Wolf     int ret;
48055a8a30dbSKevin Wolf 
48063456a8d1SKevin Wolf     if (!bs->drv)  {
48073456a8d1SKevin Wolf         return;
48080f15423cSAnthony Liguori     }
48093456a8d1SKevin Wolf 
48103456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
48115a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
48123456a8d1SKevin Wolf     } else if (bs->file) {
48135a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs->file, &local_err);
48145a8a30dbSKevin Wolf     }
48155a8a30dbSKevin Wolf     if (local_err) {
48165a8a30dbSKevin Wolf         error_propagate(errp, local_err);
48175a8a30dbSKevin Wolf         return;
48183456a8d1SKevin Wolf     }
48193456a8d1SKevin Wolf 
48205a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
48215a8a30dbSKevin Wolf     if (ret < 0) {
48225a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
48235a8a30dbSKevin Wolf         return;
48245a8a30dbSKevin Wolf     }
48250f15423cSAnthony Liguori }
48260f15423cSAnthony Liguori 
48275a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
48280f15423cSAnthony Liguori {
48290f15423cSAnthony Liguori     BlockDriverState *bs;
48305a8a30dbSKevin Wolf     Error *local_err = NULL;
48310f15423cSAnthony Liguori 
4832dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
48335a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
48345a8a30dbSKevin Wolf         if (local_err) {
48355a8a30dbSKevin Wolf             error_propagate(errp, local_err);
48365a8a30dbSKevin Wolf             return;
48375a8a30dbSKevin Wolf         }
48380f15423cSAnthony Liguori     }
48390f15423cSAnthony Liguori }
48400f15423cSAnthony Liguori 
484107789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
484207789269SBenoît Canet {
484307789269SBenoît Canet     BlockDriverState *bs;
484407789269SBenoît Canet 
4845dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
484607789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
484707789269SBenoît Canet     }
484807789269SBenoît Canet }
484907789269SBenoît Canet 
485007f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
485107f07615SPaolo Bonzini {
485207f07615SPaolo Bonzini     Coroutine *co;
485307f07615SPaolo Bonzini     RwCo rwco = {
485407f07615SPaolo Bonzini         .bs = bs,
485507f07615SPaolo Bonzini         .ret = NOT_DONE,
485607f07615SPaolo Bonzini     };
485707f07615SPaolo Bonzini 
485807f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
485907f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
486007f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
486107f07615SPaolo Bonzini     } else {
486207f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
486307f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
486407f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
486507f07615SPaolo Bonzini             qemu_aio_wait();
486607f07615SPaolo Bonzini         }
486707f07615SPaolo Bonzini     }
486807f07615SPaolo Bonzini 
486907f07615SPaolo Bonzini     return rwco.ret;
487007f07615SPaolo Bonzini }
4871e7a8a783SKevin Wolf 
4872775aa8b6SKevin Wolf typedef struct DiscardCo {
4873775aa8b6SKevin Wolf     BlockDriverState *bs;
4874775aa8b6SKevin Wolf     int64_t sector_num;
4875775aa8b6SKevin Wolf     int nb_sectors;
4876775aa8b6SKevin Wolf     int ret;
4877775aa8b6SKevin Wolf } DiscardCo;
48784265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
48794265d620SPaolo Bonzini {
4880775aa8b6SKevin Wolf     DiscardCo *rwco = opaque;
48814265d620SPaolo Bonzini 
48824265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
48834265d620SPaolo Bonzini }
48844265d620SPaolo Bonzini 
48856f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
48866f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
48876f14da52SPeter Lieven  */
48886f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
48896f14da52SPeter Lieven 
48904265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
48914265d620SPaolo Bonzini                                  int nb_sectors)
48924265d620SPaolo Bonzini {
4893d51e9fe5SPaolo Bonzini     int max_discard;
4894d51e9fe5SPaolo Bonzini 
48954265d620SPaolo Bonzini     if (!bs->drv) {
48964265d620SPaolo Bonzini         return -ENOMEDIUM;
48974265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
48984265d620SPaolo Bonzini         return -EIO;
48994265d620SPaolo Bonzini     } else if (bs->read_only) {
49004265d620SPaolo Bonzini         return -EROFS;
4901df702c9bSPaolo Bonzini     }
4902df702c9bSPaolo Bonzini 
49038f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
4904df702c9bSPaolo Bonzini 
49059e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
49069e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
49079e8f1835SPaolo Bonzini         return 0;
49089e8f1835SPaolo Bonzini     }
49099e8f1835SPaolo Bonzini 
4910d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
4911d51e9fe5SPaolo Bonzini         return 0;
4912d51e9fe5SPaolo Bonzini     }
49136f14da52SPeter Lieven 
4914d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
49156f14da52SPeter Lieven     while (nb_sectors > 0) {
49166f14da52SPeter Lieven         int ret;
49176f14da52SPeter Lieven         int num = nb_sectors;
49186f14da52SPeter Lieven 
49196f14da52SPeter Lieven         /* align request */
49206f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
49216f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
49226f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
49236f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
49246f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
49256f14da52SPeter Lieven             }
49266f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
49276f14da52SPeter Lieven         }
49286f14da52SPeter Lieven 
49296f14da52SPeter Lieven         /* limit request size */
49306f14da52SPeter Lieven         if (num > max_discard) {
49316f14da52SPeter Lieven             num = max_discard;
49326f14da52SPeter Lieven         }
49336f14da52SPeter Lieven 
4934d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
49356f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
4936d51e9fe5SPaolo Bonzini         } else {
49374265d620SPaolo Bonzini             BlockDriverAIOCB *acb;
49384265d620SPaolo Bonzini             CoroutineIOCompletion co = {
49394265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
49404265d620SPaolo Bonzini             };
49414265d620SPaolo Bonzini 
49424265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
49434265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
49444265d620SPaolo Bonzini             if (acb == NULL) {
49454265d620SPaolo Bonzini                 return -EIO;
49464265d620SPaolo Bonzini             } else {
49474265d620SPaolo Bonzini                 qemu_coroutine_yield();
4948d51e9fe5SPaolo Bonzini                 ret = co.ret;
49494265d620SPaolo Bonzini             }
4950d51e9fe5SPaolo Bonzini         }
49517ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
4952d51e9fe5SPaolo Bonzini             return ret;
4953d51e9fe5SPaolo Bonzini         }
4954d51e9fe5SPaolo Bonzini 
4955d51e9fe5SPaolo Bonzini         sector_num += num;
4956d51e9fe5SPaolo Bonzini         nb_sectors -= num;
4957d51e9fe5SPaolo Bonzini     }
49584265d620SPaolo Bonzini     return 0;
49594265d620SPaolo Bonzini }
49604265d620SPaolo Bonzini 
49614265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
49624265d620SPaolo Bonzini {
49634265d620SPaolo Bonzini     Coroutine *co;
4964775aa8b6SKevin Wolf     DiscardCo rwco = {
49654265d620SPaolo Bonzini         .bs = bs,
49664265d620SPaolo Bonzini         .sector_num = sector_num,
49674265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
49684265d620SPaolo Bonzini         .ret = NOT_DONE,
49694265d620SPaolo Bonzini     };
49704265d620SPaolo Bonzini 
49714265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
49724265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
49734265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
49744265d620SPaolo Bonzini     } else {
49754265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
49764265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
49774265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
49784265d620SPaolo Bonzini             qemu_aio_wait();
49794265d620SPaolo Bonzini         }
49804265d620SPaolo Bonzini     }
49814265d620SPaolo Bonzini 
49824265d620SPaolo Bonzini     return rwco.ret;
49834265d620SPaolo Bonzini }
49844265d620SPaolo Bonzini 
4985f9f05dc5SKevin Wolf /**************************************************************/
498619cb3738Sbellard /* removable device support */
498719cb3738Sbellard 
498819cb3738Sbellard /**
498919cb3738Sbellard  * Return TRUE if the media is present
499019cb3738Sbellard  */
499119cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
499219cb3738Sbellard {
499319cb3738Sbellard     BlockDriver *drv = bs->drv;
4994a1aff5bfSMarkus Armbruster 
499519cb3738Sbellard     if (!drv)
499619cb3738Sbellard         return 0;
499719cb3738Sbellard     if (!drv->bdrv_is_inserted)
4998a1aff5bfSMarkus Armbruster         return 1;
4999a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
500019cb3738Sbellard }
500119cb3738Sbellard 
500219cb3738Sbellard /**
50038e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
50048e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
500519cb3738Sbellard  */
500619cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
500719cb3738Sbellard {
500819cb3738Sbellard     BlockDriver *drv = bs->drv;
500919cb3738Sbellard 
50108e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
50118e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
50128e49ca46SMarkus Armbruster     }
50138e49ca46SMarkus Armbruster     return -ENOTSUP;
501419cb3738Sbellard }
501519cb3738Sbellard 
501619cb3738Sbellard /**
501719cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
501819cb3738Sbellard  */
5019f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
502019cb3738Sbellard {
502119cb3738Sbellard     BlockDriver *drv = bs->drv;
502219cb3738Sbellard 
5023822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
5024822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
502519cb3738Sbellard     }
50266f382ed2SLuiz Capitulino 
50276f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
50286f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
50296f382ed2SLuiz Capitulino     }
503019cb3738Sbellard }
503119cb3738Sbellard 
503219cb3738Sbellard /**
503319cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
503419cb3738Sbellard  * to eject it manually).
503519cb3738Sbellard  */
5036025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
503719cb3738Sbellard {
503819cb3738Sbellard     BlockDriver *drv = bs->drv;
503919cb3738Sbellard 
5040025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
5041b8c6d095SStefan Hajnoczi 
5042025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
5043025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
504419cb3738Sbellard     }
504519cb3738Sbellard }
5046985a03b0Sths 
5047985a03b0Sths /* needed for generic scsi interface */
5048985a03b0Sths 
5049985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
5050985a03b0Sths {
5051985a03b0Sths     BlockDriver *drv = bs->drv;
5052985a03b0Sths 
5053985a03b0Sths     if (drv && drv->bdrv_ioctl)
5054985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
5055985a03b0Sths     return -ENOTSUP;
5056985a03b0Sths }
50577d780669Saliguori 
5058221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
5059221f715dSaliguori         unsigned long int req, void *buf,
50607d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
50617d780669Saliguori {
5062221f715dSaliguori     BlockDriver *drv = bs->drv;
50637d780669Saliguori 
5064221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
5065221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
5066221f715dSaliguori     return NULL;
50677d780669Saliguori }
5068e268ca52Saliguori 
50691b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
50707b6f9300SMarkus Armbruster {
50711b7fd729SPaolo Bonzini     bs->guest_block_size = align;
50727b6f9300SMarkus Armbruster }
50737cd1e32aSlirans@il.ibm.com 
5074e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
5075e268ca52Saliguori {
5076339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
5077e268ca52Saliguori }
50787cd1e32aSlirans@il.ibm.com 
5079c53b1c51SStefan Hajnoczi /*
5080c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
5081c53b1c51SStefan Hajnoczi  */
5082c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5083c53b1c51SStefan Hajnoczi {
5084c53b1c51SStefan Hajnoczi     int i;
5085339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
5086c53b1c51SStefan Hajnoczi 
5087c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
5088339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
5089c53b1c51SStefan Hajnoczi             return false;
5090c53b1c51SStefan Hajnoczi         }
5091339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
50921ff735bdSKevin Wolf             return false;
50931ff735bdSKevin Wolf         }
5094c53b1c51SStefan Hajnoczi     }
5095c53b1c51SStefan Hajnoczi 
5096c53b1c51SStefan Hajnoczi     return true;
5097c53b1c51SStefan Hajnoczi }
5098c53b1c51SStefan Hajnoczi 
5099e4654d2dSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity)
51007cd1e32aSlirans@il.ibm.com {
51017cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
5102e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5103a55eb92cSJan Kiszka 
510450717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
510550717e94SPaolo Bonzini 
510650717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
5107e4654d2dSFam Zheng     assert(granularity);
51088f0720ecSPaolo Bonzini     bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
5109e4654d2dSFam Zheng     bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
5110e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5111e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5112e4654d2dSFam Zheng     return bitmap;
5113e4654d2dSFam Zheng }
5114e4654d2dSFam Zheng 
5115e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5116e4654d2dSFam Zheng {
5117e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
5118e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5119e4654d2dSFam Zheng         if (bm == bitmap) {
5120e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
5121e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
5122e4654d2dSFam Zheng             g_free(bitmap);
5123e4654d2dSFam Zheng             return;
51247cd1e32aSlirans@il.ibm.com         }
51257cd1e32aSlirans@il.ibm.com     }
51267cd1e32aSlirans@il.ibm.com }
51277cd1e32aSlirans@il.ibm.com 
512821b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
512921b56835SFam Zheng {
513021b56835SFam Zheng     BdrvDirtyBitmap *bm;
513121b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
513221b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
513321b56835SFam Zheng 
513421b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
513521b56835SFam Zheng         BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
513621b56835SFam Zheng         BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
513721b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
513821b56835SFam Zheng         info->granularity =
513921b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
514021b56835SFam Zheng         entry->value = info;
514121b56835SFam Zheng         *plist = entry;
514221b56835SFam Zheng         plist = &entry->next;
514321b56835SFam Zheng     }
514421b56835SFam Zheng 
514521b56835SFam Zheng     return list;
514621b56835SFam Zheng }
514721b56835SFam Zheng 
5148e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
51497cd1e32aSlirans@il.ibm.com {
5150e4654d2dSFam Zheng     if (bitmap) {
5151e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
51527cd1e32aSlirans@il.ibm.com     } else {
51537cd1e32aSlirans@il.ibm.com         return 0;
51547cd1e32aSlirans@il.ibm.com     }
51557cd1e32aSlirans@il.ibm.com }
51567cd1e32aSlirans@il.ibm.com 
5157e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
5158e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
51591755da16SPaolo Bonzini {
5160e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
51611755da16SPaolo Bonzini }
51621755da16SPaolo Bonzini 
51631755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
51641755da16SPaolo Bonzini                     int nr_sectors)
51651755da16SPaolo Bonzini {
5166e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5167e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5168e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5169e4654d2dSFam Zheng     }
51701755da16SPaolo Bonzini }
51711755da16SPaolo Bonzini 
5172e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
51737cd1e32aSlirans@il.ibm.com {
5174e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5175e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5176e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5177e4654d2dSFam Zheng     }
51787cd1e32aSlirans@il.ibm.com }
5179aaa0eb75SLiran Schour 
5180e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5181aaa0eb75SLiran Schour {
5182e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
5183aaa0eb75SLiran Schour }
5184f88e1a42SJes Sorensen 
51859fcb0251SFam Zheng /* Get a reference to bs */
51869fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
51879fcb0251SFam Zheng {
51889fcb0251SFam Zheng     bs->refcnt++;
51899fcb0251SFam Zheng }
51909fcb0251SFam Zheng 
51919fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
51929fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
51939fcb0251SFam Zheng  * deleted. */
51949fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
51959fcb0251SFam Zheng {
51969fcb0251SFam Zheng     assert(bs->refcnt > 0);
51979fcb0251SFam Zheng     if (--bs->refcnt == 0) {
51989fcb0251SFam Zheng         bdrv_delete(bs);
51999fcb0251SFam Zheng     }
52009fcb0251SFam Zheng }
52019fcb0251SFam Zheng 
5202db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
5203db593f25SMarcelo Tosatti {
5204db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
5205db593f25SMarcelo Tosatti     bs->in_use = in_use;
5206db593f25SMarcelo Tosatti }
5207db593f25SMarcelo Tosatti 
5208db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
5209db593f25SMarcelo Tosatti {
5210db593f25SMarcelo Tosatti     return bs->in_use;
5211db593f25SMarcelo Tosatti }
5212db593f25SMarcelo Tosatti 
521328a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
521428a7282aSLuiz Capitulino {
5215d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
521658e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
521728a7282aSLuiz Capitulino }
521828a7282aSLuiz Capitulino 
521928a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
522028a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
522128a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
522228a7282aSLuiz Capitulino {
5223d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
522492aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
522592aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
522692aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
522728a7282aSLuiz Capitulino }
522828a7282aSLuiz Capitulino 
522928a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
523028a7282aSLuiz Capitulino {
5231d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
523228a7282aSLuiz Capitulino }
523328a7282aSLuiz Capitulino 
523428a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
523528a7282aSLuiz Capitulino {
523628a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
523758e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
52383bd293c3SPaolo Bonzini         if (bs->job) {
52393bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
52403bd293c3SPaolo Bonzini         }
524128a7282aSLuiz Capitulino     }
524228a7282aSLuiz Capitulino }
524328a7282aSLuiz Capitulino 
524428a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
524528a7282aSLuiz Capitulino {
52463e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
52473e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
524858e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
524958e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
525028a7282aSLuiz Capitulino     }
525128a7282aSLuiz Capitulino }
525228a7282aSLuiz Capitulino 
5253a597e79cSChristoph Hellwig void
5254a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
5255a597e79cSChristoph Hellwig         enum BlockAcctType type)
5256a597e79cSChristoph Hellwig {
5257a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
5258a597e79cSChristoph Hellwig 
5259a597e79cSChristoph Hellwig     cookie->bytes = bytes;
5260c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
5261a597e79cSChristoph Hellwig     cookie->type = type;
5262a597e79cSChristoph Hellwig }
5263a597e79cSChristoph Hellwig 
5264a597e79cSChristoph Hellwig void
5265a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
5266a597e79cSChristoph Hellwig {
5267a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
5268a597e79cSChristoph Hellwig 
5269a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
5270a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
5271c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
5272a597e79cSChristoph Hellwig }
5273a597e79cSChristoph Hellwig 
5274d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5275f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5276f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5277f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5278f88e1a42SJes Sorensen {
5279f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
5280d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
5281f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
528296df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5283cc84d90fSMax Reitz     Error *local_err = NULL;
5284f88e1a42SJes Sorensen     int ret = 0;
5285f88e1a42SJes Sorensen 
5286f88e1a42SJes Sorensen     /* Find driver and parse its options */
5287f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5288f88e1a42SJes Sorensen     if (!drv) {
528971c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5290d92ada22SLuiz Capitulino         return;
5291f88e1a42SJes Sorensen     }
5292f88e1a42SJes Sorensen 
529398289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5294f88e1a42SJes Sorensen     if (!proto_drv) {
529571c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5296d92ada22SLuiz Capitulino         return;
5297f88e1a42SJes Sorensen     }
5298f88e1a42SJes Sorensen 
5299f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5300f88e1a42SJes Sorensen                                               drv->create_options);
5301f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5302f88e1a42SJes Sorensen                                               proto_drv->create_options);
5303f88e1a42SJes Sorensen 
5304f88e1a42SJes Sorensen     /* Create parameter list with default values */
5305f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
5306f88e1a42SJes Sorensen 
5307f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
5308f88e1a42SJes Sorensen 
5309f88e1a42SJes Sorensen     /* Parse -o options */
5310f88e1a42SJes Sorensen     if (options) {
5311f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
5312f88e1a42SJes Sorensen         if (param == NULL) {
531371c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
5314f88e1a42SJes Sorensen             goto out;
5315f88e1a42SJes Sorensen         }
5316f88e1a42SJes Sorensen     }
5317f88e1a42SJes Sorensen 
5318f88e1a42SJes Sorensen     if (base_filename) {
5319f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
5320f88e1a42SJes Sorensen                                  base_filename)) {
532171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
532271c79813SLuiz Capitulino                        fmt);
5323f88e1a42SJes Sorensen             goto out;
5324f88e1a42SJes Sorensen         }
5325f88e1a42SJes Sorensen     }
5326f88e1a42SJes Sorensen 
5327f88e1a42SJes Sorensen     if (base_fmt) {
5328f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
532971c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
533071c79813SLuiz Capitulino                              "format '%s'", fmt);
5331f88e1a42SJes Sorensen             goto out;
5332f88e1a42SJes Sorensen         }
5333f88e1a42SJes Sorensen     }
5334f88e1a42SJes Sorensen 
5335792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
5336792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
5337792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
533871c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
533971c79813SLuiz Capitulino                              "same filename as the backing file");
5340792da93aSJes Sorensen             goto out;
5341792da93aSJes Sorensen         }
5342792da93aSJes Sorensen     }
5343792da93aSJes Sorensen 
5344f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
5345f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
534696df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
534796df67d1SStefan Hajnoczi         if (!backing_drv) {
534871c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
534971c79813SLuiz Capitulino                        backing_fmt->value.s);
5350f88e1a42SJes Sorensen             goto out;
5351f88e1a42SJes Sorensen         }
5352f88e1a42SJes Sorensen     }
5353f88e1a42SJes Sorensen 
5354f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5355f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
5356d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
5357d220894eSKevin Wolf     if (size && size->value.n == -1) {
5358f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
535966f6b814SMax Reitz             BlockDriverState *bs;
5360f88e1a42SJes Sorensen             uint64_t size;
5361f88e1a42SJes Sorensen             char buf[32];
536263090dacSPaolo Bonzini             int back_flags;
536363090dacSPaolo Bonzini 
536463090dacSPaolo Bonzini             /* backing files always opened read-only */
536563090dacSPaolo Bonzini             back_flags =
536663090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5367f88e1a42SJes Sorensen 
5368f67503e5SMax Reitz             bs = NULL;
5369ddf5636dSMax Reitz             ret = bdrv_open(&bs, backing_file->value.s, NULL, NULL, back_flags,
5370cc84d90fSMax Reitz                             backing_drv, &local_err);
5371f88e1a42SJes Sorensen             if (ret < 0) {
5372cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
5373cc84d90fSMax Reitz                                  backing_file->value.s,
5374cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5375cc84d90fSMax Reitz                 error_free(local_err);
5376cc84d90fSMax Reitz                 local_err = NULL;
5377f88e1a42SJes Sorensen                 goto out;
5378f88e1a42SJes Sorensen             }
5379f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
5380f88e1a42SJes Sorensen             size *= 512;
5381f88e1a42SJes Sorensen 
5382f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
5383f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
538466f6b814SMax Reitz 
538566f6b814SMax Reitz             bdrv_unref(bs);
5386f88e1a42SJes Sorensen         } else {
538771c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5388f88e1a42SJes Sorensen             goto out;
5389f88e1a42SJes Sorensen         }
5390f88e1a42SJes Sorensen     }
5391f88e1a42SJes Sorensen 
5392f382d43aSMiroslav Rezanina     if (!quiet) {
5393f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
5394f88e1a42SJes Sorensen         print_option_parameters(param);
5395f88e1a42SJes Sorensen         puts("");
5396f382d43aSMiroslav Rezanina     }
5397cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, param, &local_err);
5398cc84d90fSMax Reitz     if (ret == -EFBIG) {
5399cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5400cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5401cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5402f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
5403f3f4d2c0SKevin Wolf         if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
5404f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5405f3f4d2c0SKevin Wolf         }
5406cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5407cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5408cc84d90fSMax Reitz         error_free(local_err);
5409cc84d90fSMax Reitz         local_err = NULL;
5410f88e1a42SJes Sorensen     }
5411f88e1a42SJes Sorensen 
5412f88e1a42SJes Sorensen out:
5413f88e1a42SJes Sorensen     free_option_parameters(create_options);
5414f88e1a42SJes Sorensen     free_option_parameters(param);
5415f88e1a42SJes Sorensen 
541684d18f06SMarkus Armbruster     if (local_err) {
5417cc84d90fSMax Reitz         error_propagate(errp, local_err);
5418cc84d90fSMax Reitz     }
5419f88e1a42SJes Sorensen }
542085d126f3SStefan Hajnoczi 
542185d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
542285d126f3SStefan Hajnoczi {
542385d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
542485d126f3SStefan Hajnoczi     return qemu_get_aio_context();
542585d126f3SStefan Hajnoczi }
5426d616b224SStefan Hajnoczi 
5427d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5428d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5429d616b224SStefan Hajnoczi {
5430d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5431d616b224SStefan Hajnoczi }
54326f176b48SMax Reitz 
54336f176b48SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
54346f176b48SMax Reitz {
54356f176b48SMax Reitz     if (bs->drv->bdrv_amend_options == NULL) {
54366f176b48SMax Reitz         return -ENOTSUP;
54376f176b48SMax Reitz     }
54386f176b48SMax Reitz     return bs->drv->bdrv_amend_options(bs, options);
54396f176b48SMax Reitz }
5440f6186f49SBenoît Canet 
5441b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
5442b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
5443b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
5444b5042a36SBenoît Canet  * node graph.
5445212a5a8fSBenoît Canet  */
5446212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5447212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5448f6186f49SBenoît Canet {
5449b5042a36SBenoît Canet     /* return false if basic checks fails */
5450b5042a36SBenoît Canet     if (!bs || !bs->drv) {
5451b5042a36SBenoît Canet         return false;
5452b5042a36SBenoît Canet     }
5453b5042a36SBenoît Canet 
5454b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
5455b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
5456b5042a36SBenoît Canet      */
5457b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
5458b5042a36SBenoît Canet         return bs == candidate;
5459b5042a36SBenoît Canet     }
5460b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
5461b5042a36SBenoît Canet 
5462b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
5463b5042a36SBenoît Canet      * the node graph.
5464b5042a36SBenoît Canet      */
5465b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
5466212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5467212a5a8fSBenoît Canet     }
5468212a5a8fSBenoît Canet 
5469b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
5470b5042a36SBenoît Canet      */
5471b5042a36SBenoît Canet     return false;
5472212a5a8fSBenoît Canet }
5473212a5a8fSBenoît Canet 
5474212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5475212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5476212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5477212a5a8fSBenoît Canet  */
5478212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5479212a5a8fSBenoît Canet {
5480212a5a8fSBenoît Canet     BlockDriverState *bs;
5481212a5a8fSBenoît Canet 
5482212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5483212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5484212a5a8fSBenoît Canet         bool perm;
5485212a5a8fSBenoît Canet 
5486b5042a36SBenoît Canet         /* try to recurse in this top level bs */
5487e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
5488212a5a8fSBenoît Canet 
5489212a5a8fSBenoît Canet         /* candidate is the first non filter */
5490212a5a8fSBenoît Canet         if (perm) {
5491212a5a8fSBenoît Canet             return true;
5492212a5a8fSBenoît Canet         }
5493212a5a8fSBenoît Canet     }
5494212a5a8fSBenoît Canet 
5495212a5a8fSBenoît Canet     return false;
5496f6186f49SBenoît Canet }
5497