xref: /openbmc/qemu/block.c (revision 775aa8b6e0ea25f8cca74d0fcb1e30a764cf624f)
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);
73*775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
74*775aa8b6SKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
75470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
76*775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
77*775aa8b6SKevin 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,
195cc0681c4SBenoît Canet                                      int nb_sectors,
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 */
208cc0681c4SBenoît Canet     throttle_account(&bs->throttle_state,
209cc0681c4SBenoît Canet                      is_write,
210cc0681c4SBenoît Canet                      nb_sectors * BDRV_SECTOR_SIZE);
211cc0681c4SBenoît Canet 
212cc0681c4SBenoît Canet     /* if the next request must wait -> do nothing */
213cc0681c4SBenoît Canet     if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
214cc0681c4SBenoît Canet         return;
215cc0681c4SBenoît Canet     }
216cc0681c4SBenoît Canet 
217cc0681c4SBenoît Canet     /* else queue next request for execution */
218cc0681c4SBenoît Canet     qemu_co_queue_next(&bs->throttled_reqs[is_write]);
21998f90dbaSZhi Yong Wu }
22098f90dbaSZhi Yong Wu 
221339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
222339064d5SKevin Wolf {
223339064d5SKevin Wolf     if (!bs || !bs->drv) {
224339064d5SKevin Wolf         /* 4k should be on the safe side */
225339064d5SKevin Wolf         return 4096;
226339064d5SKevin Wolf     }
227339064d5SKevin Wolf 
228339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
229339064d5SKevin Wolf }
230339064d5SKevin Wolf 
2319e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
2329e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2339e0b22f4SStefan Hajnoczi {
234947995c0SPaolo Bonzini     const char *p;
235947995c0SPaolo Bonzini 
2369e0b22f4SStefan Hajnoczi #ifdef _WIN32
2379e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2389e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2399e0b22f4SStefan Hajnoczi         return 0;
2409e0b22f4SStefan Hajnoczi     }
241947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
242947995c0SPaolo Bonzini #else
243947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2449e0b22f4SStefan Hajnoczi #endif
2459e0b22f4SStefan Hajnoczi 
246947995c0SPaolo Bonzini     return *p == ':';
2479e0b22f4SStefan Hajnoczi }
2489e0b22f4SStefan Hajnoczi 
24983f64091Sbellard int path_is_absolute(const char *path)
25083f64091Sbellard {
25121664424Sbellard #ifdef _WIN32
25221664424Sbellard     /* specific case for names like: "\\.\d:" */
253f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
25421664424Sbellard         return 1;
255f53f4da9SPaolo Bonzini     }
256f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2573b9f94e1Sbellard #else
258f53f4da9SPaolo Bonzini     return (*path == '/');
2593b9f94e1Sbellard #endif
26083f64091Sbellard }
26183f64091Sbellard 
26283f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
26383f64091Sbellard    path to it by considering it is relative to base_path. URL are
26483f64091Sbellard    supported. */
26583f64091Sbellard void path_combine(char *dest, int dest_size,
26683f64091Sbellard                   const char *base_path,
26783f64091Sbellard                   const char *filename)
26883f64091Sbellard {
26983f64091Sbellard     const char *p, *p1;
27083f64091Sbellard     int len;
27183f64091Sbellard 
27283f64091Sbellard     if (dest_size <= 0)
27383f64091Sbellard         return;
27483f64091Sbellard     if (path_is_absolute(filename)) {
27583f64091Sbellard         pstrcpy(dest, dest_size, filename);
27683f64091Sbellard     } else {
27783f64091Sbellard         p = strchr(base_path, ':');
27883f64091Sbellard         if (p)
27983f64091Sbellard             p++;
28083f64091Sbellard         else
28183f64091Sbellard             p = base_path;
2823b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2833b9f94e1Sbellard #ifdef _WIN32
2843b9f94e1Sbellard         {
2853b9f94e1Sbellard             const char *p2;
2863b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2873b9f94e1Sbellard             if (!p1 || p2 > p1)
2883b9f94e1Sbellard                 p1 = p2;
2893b9f94e1Sbellard         }
2903b9f94e1Sbellard #endif
29183f64091Sbellard         if (p1)
29283f64091Sbellard             p1++;
29383f64091Sbellard         else
29483f64091Sbellard             p1 = base_path;
29583f64091Sbellard         if (p1 > p)
29683f64091Sbellard             p = p1;
29783f64091Sbellard         len = p - base_path;
29883f64091Sbellard         if (len > dest_size - 1)
29983f64091Sbellard             len = dest_size - 1;
30083f64091Sbellard         memcpy(dest, base_path, len);
30183f64091Sbellard         dest[len] = '\0';
30283f64091Sbellard         pstrcat(dest, dest_size, filename);
30383f64091Sbellard     }
30483f64091Sbellard }
30583f64091Sbellard 
306dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
307dc5a1371SPaolo Bonzini {
308dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
309dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
310dc5a1371SPaolo Bonzini     } else {
311dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
312dc5a1371SPaolo Bonzini     }
313dc5a1371SPaolo Bonzini }
314dc5a1371SPaolo Bonzini 
3155efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
316ea2384d3Sbellard {
3178c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
3188c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
319f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
320f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
321f9f05dc5SKevin Wolf 
322f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
323f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
324f8c35c1dSStefan Hajnoczi          */
325f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
32683f64091Sbellard             /* add AIO emulation layer */
327f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
328f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
32983f64091Sbellard         }
330f9f05dc5SKevin Wolf     }
331b2e12bc6SChristoph Hellwig 
3328a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
333ea2384d3Sbellard }
334b338082bSbellard 
335b338082bSbellard /* create a new block device (by default it is empty) */
336b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
337fc01f7e7Sbellard {
3381b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
339b338082bSbellard 
3407267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
341e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
342b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
343ea2384d3Sbellard     if (device_name[0] != '\0') {
344dc364f4cSBenoît Canet         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
345ea2384d3Sbellard     }
34628a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
347d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
348d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
349cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
350cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3519fcb0251SFam Zheng     bs->refcnt = 1;
352d7d512f6SPaolo Bonzini 
353b338082bSbellard     return bs;
354b338082bSbellard }
355b338082bSbellard 
356d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
357d7d512f6SPaolo Bonzini {
358d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
359d7d512f6SPaolo Bonzini }
360d7d512f6SPaolo Bonzini 
361ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
362ea2384d3Sbellard {
363ea2384d3Sbellard     BlockDriver *drv1;
3648a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3658a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
366ea2384d3Sbellard             return drv1;
367ea2384d3Sbellard         }
3688a22f02aSStefan Hajnoczi     }
369ea2384d3Sbellard     return NULL;
370ea2384d3Sbellard }
371ea2384d3Sbellard 
372b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
373eb852011SMarkus Armbruster {
374b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
375b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
376b64ec4e4SFam Zheng     };
377b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
378b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
379eb852011SMarkus Armbruster     };
380eb852011SMarkus Armbruster     const char **p;
381eb852011SMarkus Armbruster 
382b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
383eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
384b64ec4e4SFam Zheng     }
385eb852011SMarkus Armbruster 
386b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
387eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
388eb852011SMarkus Armbruster             return 1;
389eb852011SMarkus Armbruster         }
390eb852011SMarkus Armbruster     }
391b64ec4e4SFam Zheng     if (read_only) {
392b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
393b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
394b64ec4e4SFam Zheng                 return 1;
395b64ec4e4SFam Zheng             }
396b64ec4e4SFam Zheng         }
397b64ec4e4SFam Zheng     }
398eb852011SMarkus Armbruster     return 0;
399eb852011SMarkus Armbruster }
400eb852011SMarkus Armbruster 
401b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
402b64ec4e4SFam Zheng                                           bool read_only)
403eb852011SMarkus Armbruster {
404eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
405b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
406eb852011SMarkus Armbruster }
407eb852011SMarkus Armbruster 
4085b7e1542SZhi Yong Wu typedef struct CreateCo {
4095b7e1542SZhi Yong Wu     BlockDriver *drv;
4105b7e1542SZhi Yong Wu     char *filename;
4115b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
4125b7e1542SZhi Yong Wu     int ret;
413cc84d90fSMax Reitz     Error *err;
4145b7e1542SZhi Yong Wu } CreateCo;
4155b7e1542SZhi Yong Wu 
4165b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4175b7e1542SZhi Yong Wu {
418cc84d90fSMax Reitz     Error *local_err = NULL;
419cc84d90fSMax Reitz     int ret;
420cc84d90fSMax Reitz 
4215b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4225b7e1542SZhi Yong Wu     assert(cco->drv);
4235b7e1542SZhi Yong Wu 
424cc84d90fSMax Reitz     ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
425cc84d90fSMax Reitz     if (error_is_set(&local_err)) {
426cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
427cc84d90fSMax Reitz     }
428cc84d90fSMax Reitz     cco->ret = ret;
4295b7e1542SZhi Yong Wu }
4305b7e1542SZhi Yong Wu 
4310e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
432cc84d90fSMax Reitz     QEMUOptionParameter *options, Error **errp)
433ea2384d3Sbellard {
4345b7e1542SZhi Yong Wu     int ret;
4350e7e1989SKevin Wolf 
4365b7e1542SZhi Yong Wu     Coroutine *co;
4375b7e1542SZhi Yong Wu     CreateCo cco = {
4385b7e1542SZhi Yong Wu         .drv = drv,
4395b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
4405b7e1542SZhi Yong Wu         .options = options,
4415b7e1542SZhi Yong Wu         .ret = NOT_DONE,
442cc84d90fSMax Reitz         .err = NULL,
4435b7e1542SZhi Yong Wu     };
4445b7e1542SZhi Yong Wu 
4455b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
446cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
44780168bffSLuiz Capitulino         ret = -ENOTSUP;
44880168bffSLuiz Capitulino         goto out;
4495b7e1542SZhi Yong Wu     }
4505b7e1542SZhi Yong Wu 
4515b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4525b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4535b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4545b7e1542SZhi Yong Wu     } else {
4555b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4565b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4575b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4585b7e1542SZhi Yong Wu             qemu_aio_wait();
4595b7e1542SZhi Yong Wu         }
4605b7e1542SZhi Yong Wu     }
4615b7e1542SZhi Yong Wu 
4625b7e1542SZhi Yong Wu     ret = cco.ret;
463cc84d90fSMax Reitz     if (ret < 0) {
464cc84d90fSMax Reitz         if (error_is_set(&cco.err)) {
465cc84d90fSMax Reitz             error_propagate(errp, cco.err);
466cc84d90fSMax Reitz         } else {
467cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
468cc84d90fSMax Reitz         }
469cc84d90fSMax Reitz     }
4705b7e1542SZhi Yong Wu 
47180168bffSLuiz Capitulino out:
47280168bffSLuiz Capitulino     g_free(cco.filename);
4735b7e1542SZhi Yong Wu     return ret;
474ea2384d3Sbellard }
475ea2384d3Sbellard 
476cc84d90fSMax Reitz int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
477cc84d90fSMax Reitz                      Error **errp)
47884a12e66SChristoph Hellwig {
47984a12e66SChristoph Hellwig     BlockDriver *drv;
480cc84d90fSMax Reitz     Error *local_err = NULL;
481cc84d90fSMax Reitz     int ret;
48284a12e66SChristoph Hellwig 
48398289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
48484a12e66SChristoph Hellwig     if (drv == NULL) {
485cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
48616905d71SStefan Hajnoczi         return -ENOENT;
48784a12e66SChristoph Hellwig     }
48884a12e66SChristoph Hellwig 
489cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, options, &local_err);
490cc84d90fSMax Reitz     if (error_is_set(&local_err)) {
491cc84d90fSMax Reitz         error_propagate(errp, local_err);
492cc84d90fSMax Reitz     }
493cc84d90fSMax Reitz     return ret;
49484a12e66SChristoph Hellwig }
49584a12e66SChristoph Hellwig 
496355ef4acSKevin Wolf int bdrv_refresh_limits(BlockDriverState *bs)
497d34682cdSKevin Wolf {
498d34682cdSKevin Wolf     BlockDriver *drv = bs->drv;
499d34682cdSKevin Wolf 
500d34682cdSKevin Wolf     memset(&bs->bl, 0, sizeof(bs->bl));
501d34682cdSKevin Wolf 
502466ad822SKevin Wolf     if (!drv) {
503466ad822SKevin Wolf         return 0;
504466ad822SKevin Wolf     }
505466ad822SKevin Wolf 
506466ad822SKevin Wolf     /* Take some limits from the children as a default */
507466ad822SKevin Wolf     if (bs->file) {
508466ad822SKevin Wolf         bdrv_refresh_limits(bs->file);
509466ad822SKevin Wolf         bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
510339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
511339064d5SKevin Wolf     } else {
512339064d5SKevin Wolf         bs->bl.opt_mem_alignment = 512;
513466ad822SKevin Wolf     }
514466ad822SKevin Wolf 
515466ad822SKevin Wolf     if (bs->backing_hd) {
516466ad822SKevin Wolf         bdrv_refresh_limits(bs->backing_hd);
517466ad822SKevin Wolf         bs->bl.opt_transfer_length =
518466ad822SKevin Wolf             MAX(bs->bl.opt_transfer_length,
519466ad822SKevin Wolf                 bs->backing_hd->bl.opt_transfer_length);
520339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
521339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
522339064d5SKevin Wolf                 bs->backing_hd->bl.opt_mem_alignment);
523466ad822SKevin Wolf     }
524466ad822SKevin Wolf 
525466ad822SKevin Wolf     /* Then let the driver override it */
526466ad822SKevin Wolf     if (drv->bdrv_refresh_limits) {
527d34682cdSKevin Wolf         return drv->bdrv_refresh_limits(bs);
528d34682cdSKevin Wolf     }
529d34682cdSKevin Wolf 
530d34682cdSKevin Wolf     return 0;
531d34682cdSKevin Wolf }
532d34682cdSKevin Wolf 
533eba25057SJim Meyering /*
534eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
535eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
536eba25057SJim Meyering  */
537eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
538eba25057SJim Meyering {
539d5249393Sbellard #ifdef _WIN32
5403b9f94e1Sbellard     char temp_dir[MAX_PATH];
541eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
542eba25057SJim Meyering        have length MAX_PATH or greater.  */
543eba25057SJim Meyering     assert(size >= MAX_PATH);
544eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
545eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
546eba25057SJim Meyering             ? 0 : -GetLastError());
547d5249393Sbellard #else
548ea2384d3Sbellard     int fd;
5497ccfb2ebSblueswir1     const char *tmpdir;
5500badc1eeSaurel32     tmpdir = getenv("TMPDIR");
5510badc1eeSaurel32     if (!tmpdir)
5520badc1eeSaurel32         tmpdir = "/tmp";
553eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
554eba25057SJim Meyering         return -EOVERFLOW;
555ea2384d3Sbellard     }
556eba25057SJim Meyering     fd = mkstemp(filename);
557fe235a06SDunrong Huang     if (fd < 0) {
558fe235a06SDunrong Huang         return -errno;
559fe235a06SDunrong Huang     }
560fe235a06SDunrong Huang     if (close(fd) != 0) {
561fe235a06SDunrong Huang         unlink(filename);
562eba25057SJim Meyering         return -errno;
563eba25057SJim Meyering     }
564eba25057SJim Meyering     return 0;
565d5249393Sbellard #endif
566eba25057SJim Meyering }
567ea2384d3Sbellard 
568f3a5d3f8SChristoph Hellwig /*
569f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
570f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
571f3a5d3f8SChristoph Hellwig  */
572f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
573f3a5d3f8SChristoph Hellwig {
574508c7cb3SChristoph Hellwig     int score_max = 0, score;
575508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
576f3a5d3f8SChristoph Hellwig 
5778a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
578508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
579508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
580508c7cb3SChristoph Hellwig             if (score > score_max) {
581508c7cb3SChristoph Hellwig                 score_max = score;
582508c7cb3SChristoph Hellwig                 drv = d;
583f3a5d3f8SChristoph Hellwig             }
584508c7cb3SChristoph Hellwig         }
585f3a5d3f8SChristoph Hellwig     }
586f3a5d3f8SChristoph Hellwig 
587508c7cb3SChristoph Hellwig     return drv;
588f3a5d3f8SChristoph Hellwig }
589f3a5d3f8SChristoph Hellwig 
59098289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
59198289620SKevin Wolf                                 bool allow_protocol_prefix)
59284a12e66SChristoph Hellwig {
59384a12e66SChristoph Hellwig     BlockDriver *drv1;
59484a12e66SChristoph Hellwig     char protocol[128];
59584a12e66SChristoph Hellwig     int len;
59684a12e66SChristoph Hellwig     const char *p;
59784a12e66SChristoph Hellwig 
59866f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
59966f82ceeSKevin Wolf 
60039508e7aSChristoph Hellwig     /*
60139508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
60239508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
60339508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
60439508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
60539508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
60639508e7aSChristoph Hellwig      */
60784a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
60839508e7aSChristoph Hellwig     if (drv1) {
60984a12e66SChristoph Hellwig         return drv1;
61084a12e66SChristoph Hellwig     }
61139508e7aSChristoph Hellwig 
61298289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
61339508e7aSChristoph Hellwig         return bdrv_find_format("file");
61439508e7aSChristoph Hellwig     }
61598289620SKevin Wolf 
6169e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
6179e0b22f4SStefan Hajnoczi     assert(p != NULL);
61884a12e66SChristoph Hellwig     len = p - filename;
61984a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
62084a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
62184a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
62284a12e66SChristoph Hellwig     protocol[len] = '\0';
62384a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
62484a12e66SChristoph Hellwig         if (drv1->protocol_name &&
62584a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
62684a12e66SChristoph Hellwig             return drv1;
62784a12e66SChristoph Hellwig         }
62884a12e66SChristoph Hellwig     }
62984a12e66SChristoph Hellwig     return NULL;
63084a12e66SChristoph Hellwig }
63184a12e66SChristoph Hellwig 
632f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
63334b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
634ea2384d3Sbellard {
635f500a6d3SKevin Wolf     int score, score_max;
636ea2384d3Sbellard     BlockDriver *drv1, *drv;
63783f64091Sbellard     uint8_t buf[2048];
638f500a6d3SKevin Wolf     int ret = 0;
639f8ea0b00SNicholas Bellinger 
64008a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
6418e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
642c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
643c98ac35dSStefan Weil         if (!drv) {
64434b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
645c98ac35dSStefan Weil             ret = -ENOENT;
646c98ac35dSStefan Weil         }
647c98ac35dSStefan Weil         *pdrv = drv;
648c98ac35dSStefan Weil         return ret;
6491a396859SNicholas A. Bellinger     }
650f8ea0b00SNicholas Bellinger 
65183f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
652ea2384d3Sbellard     if (ret < 0) {
65334b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
65434b5d2c6SMax Reitz                          "format");
655c98ac35dSStefan Weil         *pdrv = NULL;
656c98ac35dSStefan Weil         return ret;
657ea2384d3Sbellard     }
658ea2384d3Sbellard 
659ea2384d3Sbellard     score_max = 0;
66084a12e66SChristoph Hellwig     drv = NULL;
6618a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
66283f64091Sbellard         if (drv1->bdrv_probe) {
663ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
664ea2384d3Sbellard             if (score > score_max) {
665ea2384d3Sbellard                 score_max = score;
666ea2384d3Sbellard                 drv = drv1;
667ea2384d3Sbellard             }
668ea2384d3Sbellard         }
66983f64091Sbellard     }
670c98ac35dSStefan Weil     if (!drv) {
67134b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
67234b5d2c6SMax Reitz                    "driver found");
673c98ac35dSStefan Weil         ret = -ENOENT;
674c98ac35dSStefan Weil     }
675c98ac35dSStefan Weil     *pdrv = drv;
676c98ac35dSStefan Weil     return ret;
677ea2384d3Sbellard }
678ea2384d3Sbellard 
67951762288SStefan Hajnoczi /**
68051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
68151762288SStefan Hajnoczi  */
68251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
68351762288SStefan Hajnoczi {
68451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
68551762288SStefan Hajnoczi 
686396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
687396759adSNicholas Bellinger     if (bs->sg)
688396759adSNicholas Bellinger         return 0;
689396759adSNicholas Bellinger 
69051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
69151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
69251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
69351762288SStefan Hajnoczi         if (length < 0) {
69451762288SStefan Hajnoczi             return length;
69551762288SStefan Hajnoczi         }
6967e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
69751762288SStefan Hajnoczi     }
69851762288SStefan Hajnoczi 
69951762288SStefan Hajnoczi     bs->total_sectors = hint;
70051762288SStefan Hajnoczi     return 0;
70151762288SStefan Hajnoczi }
70251762288SStefan Hajnoczi 
703c3993cdcSStefan Hajnoczi /**
7049e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
7059e8f1835SPaolo Bonzini  *
7069e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
7079e8f1835SPaolo Bonzini  */
7089e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
7099e8f1835SPaolo Bonzini {
7109e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
7119e8f1835SPaolo Bonzini 
7129e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
7139e8f1835SPaolo Bonzini         /* do nothing */
7149e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
7159e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
7169e8f1835SPaolo Bonzini     } else {
7179e8f1835SPaolo Bonzini         return -1;
7189e8f1835SPaolo Bonzini     }
7199e8f1835SPaolo Bonzini 
7209e8f1835SPaolo Bonzini     return 0;
7219e8f1835SPaolo Bonzini }
7229e8f1835SPaolo Bonzini 
7239e8f1835SPaolo Bonzini /**
724c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
725c3993cdcSStefan Hajnoczi  *
726c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
727c3993cdcSStefan Hajnoczi  */
728c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
729c3993cdcSStefan Hajnoczi {
730c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
731c3993cdcSStefan Hajnoczi 
732c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
733c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
73492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
73592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
736c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
737c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
738c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
739c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
740c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
741c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
742c3993cdcSStefan Hajnoczi         /* this is the default */
743c3993cdcSStefan Hajnoczi     } else {
744c3993cdcSStefan Hajnoczi         return -1;
745c3993cdcSStefan Hajnoczi     }
746c3993cdcSStefan Hajnoczi 
747c3993cdcSStefan Hajnoczi     return 0;
748c3993cdcSStefan Hajnoczi }
749c3993cdcSStefan Hajnoczi 
75053fec9d3SStefan Hajnoczi /**
75153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
75253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
75353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
75453fec9d3SStefan Hajnoczi  */
75553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
75653fec9d3SStefan Hajnoczi {
75753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
75853fec9d3SStefan Hajnoczi }
75953fec9d3SStefan Hajnoczi 
76053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
76153fec9d3SStefan Hajnoczi {
76253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
76353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
76453fec9d3SStefan Hajnoczi }
76553fec9d3SStefan Hajnoczi 
7667b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7677b272452SKevin Wolf {
7687b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7697b272452SKevin Wolf 
7707b272452SKevin Wolf     /*
7717b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7727b272452SKevin Wolf      * image.
7737b272452SKevin Wolf      */
7747b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7757b272452SKevin Wolf 
7767b272452SKevin Wolf     /*
7777b272452SKevin Wolf      * Snapshots should be writable.
7787b272452SKevin Wolf      */
7797b272452SKevin Wolf     if (bs->is_temporary) {
7807b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7817b272452SKevin Wolf     }
7827b272452SKevin Wolf 
7837b272452SKevin Wolf     return open_flags;
7847b272452SKevin Wolf }
7857b272452SKevin Wolf 
7866913c0c2SBenoît Canet static int bdrv_assign_node_name(BlockDriverState *bs,
7876913c0c2SBenoît Canet                                  const char *node_name,
7886913c0c2SBenoît Canet                                  Error **errp)
7896913c0c2SBenoît Canet {
7906913c0c2SBenoît Canet     if (!node_name) {
7916913c0c2SBenoît Canet         return 0;
7926913c0c2SBenoît Canet     }
7936913c0c2SBenoît Canet 
7946913c0c2SBenoît Canet     /* empty string node name is invalid */
7956913c0c2SBenoît Canet     if (node_name[0] == '\0') {
7966913c0c2SBenoît Canet         error_setg(errp, "Empty node name");
7976913c0c2SBenoît Canet         return -EINVAL;
7986913c0c2SBenoît Canet     }
7996913c0c2SBenoît Canet 
8006913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8016913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8026913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
8036913c0c2SBenoît Canet         return -EINVAL;
8046913c0c2SBenoît Canet     }
8056913c0c2SBenoît Canet 
8066913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8076913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8086913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
8096913c0c2SBenoît Canet 
8106913c0c2SBenoît Canet     return 0;
8116913c0c2SBenoît Canet }
8126913c0c2SBenoît Canet 
813b6ce07aaSKevin Wolf /*
81457915332SKevin Wolf  * Common part for opening disk images and files
815b6ad491aSKevin Wolf  *
816b6ad491aSKevin Wolf  * Removes all processed options from *options.
81757915332SKevin Wolf  */
818f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
81934b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
82057915332SKevin Wolf {
82157915332SKevin Wolf     int ret, open_flags;
822035fccdfSKevin Wolf     const char *filename;
8236913c0c2SBenoît Canet     const char *node_name = NULL;
82434b5d2c6SMax Reitz     Error *local_err = NULL;
82557915332SKevin Wolf 
82657915332SKevin Wolf     assert(drv != NULL);
8276405875cSPaolo Bonzini     assert(bs->file == NULL);
828707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
82957915332SKevin Wolf 
83045673671SKevin Wolf     if (file != NULL) {
83145673671SKevin Wolf         filename = file->filename;
83245673671SKevin Wolf     } else {
83345673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
83445673671SKevin Wolf     }
83545673671SKevin Wolf 
83645673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
83728dcee10SStefan Hajnoczi 
8386913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
8396913c0c2SBenoît Canet     ret = bdrv_assign_node_name(bs, node_name, errp);
8406913c0c2SBenoît Canet     if (ret < 0) {
8416913c0c2SBenoît Canet         return ret;
8426913c0c2SBenoît Canet     }
8436913c0c2SBenoît Canet     qdict_del(options, "node-name");
8446913c0c2SBenoît Canet 
8455d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
8465d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
8475d186eb0SKevin Wolf      * and return immediately. */
8485d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
8495d186eb0SKevin Wolf         bdrv_swap(file, bs);
8505d186eb0SKevin Wolf         return 0;
8515d186eb0SKevin Wolf     }
8525d186eb0SKevin Wolf 
85357915332SKevin Wolf     bs->open_flags = flags;
8541b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
855c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8560d51b4deSAsias He     bs->zero_beyond_eof = true;
857b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
858b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
859b64ec4e4SFam Zheng 
860b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8618f94a6e4SKevin Wolf         error_setg(errp,
8628f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8638f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8648f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8658f94a6e4SKevin Wolf                    drv->format_name);
866b64ec4e4SFam Zheng         return -ENOTSUP;
867b64ec4e4SFam Zheng     }
86857915332SKevin Wolf 
86953fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8700ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8710ebd24e0SKevin Wolf         if (!bs->read_only) {
87253fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8730ebd24e0SKevin Wolf         } else {
8740ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
8750ebd24e0SKevin Wolf             return -EINVAL;
8760ebd24e0SKevin Wolf         }
87753fec9d3SStefan Hajnoczi     }
87853fec9d3SStefan Hajnoczi 
879c2ad1b0cSKevin Wolf     if (filename != NULL) {
88057915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
881c2ad1b0cSKevin Wolf     } else {
882c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
883c2ad1b0cSKevin Wolf     }
88457915332SKevin Wolf 
88557915332SKevin Wolf     bs->drv = drv;
8867267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
88757915332SKevin Wolf 
88803f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
889e7c63796SStefan Hajnoczi 
89066f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
89166f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
8925d186eb0SKevin Wolf         assert(file == NULL);
893030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
89434b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
895f500a6d3SKevin Wolf     } else {
8962af5ef70SKevin Wolf         if (file == NULL) {
89734b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
89834b5d2c6SMax Reitz                        "protocol level", drv->format_name);
8992af5ef70SKevin Wolf             ret = -EINVAL;
9002af5ef70SKevin Wolf             goto free_and_fail;
9012af5ef70SKevin Wolf         }
902f500a6d3SKevin Wolf         bs->file = file;
90334b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
90466f82ceeSKevin Wolf     }
90566f82ceeSKevin Wolf 
90657915332SKevin Wolf     if (ret < 0) {
90734b5d2c6SMax Reitz         if (error_is_set(&local_err)) {
90834b5d2c6SMax Reitz             error_propagate(errp, local_err);
9092fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9102fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
91134b5d2c6SMax Reitz         } else {
91234b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
91334b5d2c6SMax Reitz         }
91457915332SKevin Wolf         goto free_and_fail;
91557915332SKevin Wolf     }
91657915332SKevin Wolf 
91751762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
91851762288SStefan Hajnoczi     if (ret < 0) {
91934b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
92051762288SStefan Hajnoczi         goto free_and_fail;
92157915332SKevin Wolf     }
92251762288SStefan Hajnoczi 
923d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
924c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
925c25f53b0SPaolo Bonzini     assert(bs->request_alignment != 0);
926d34682cdSKevin Wolf 
92757915332SKevin Wolf #ifndef _WIN32
92857915332SKevin Wolf     if (bs->is_temporary) {
929d4cea8dfSDunrong Huang         assert(bs->filename[0] != '\0');
930d4cea8dfSDunrong Huang         unlink(bs->filename);
93157915332SKevin Wolf     }
93257915332SKevin Wolf #endif
93357915332SKevin Wolf     return 0;
93457915332SKevin Wolf 
93557915332SKevin Wolf free_and_fail:
93666f82ceeSKevin Wolf     bs->file = NULL;
9377267c094SAnthony Liguori     g_free(bs->opaque);
93857915332SKevin Wolf     bs->opaque = NULL;
93957915332SKevin Wolf     bs->drv = NULL;
94057915332SKevin Wolf     return ret;
94157915332SKevin Wolf }
94257915332SKevin Wolf 
94357915332SKevin Wolf /*
944b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
945787e4a85SKevin Wolf  *
946787e4a85SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
947787e4a85SKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
948787e4a85SKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
949787e4a85SKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
950b6ce07aaSKevin Wolf  */
951787e4a85SKevin Wolf int bdrv_file_open(BlockDriverState **pbs, const char *filename,
95272daa72eSMax Reitz                    const char *reference, QDict *options, int flags,
95372daa72eSMax Reitz                    Error **errp)
954b338082bSbellard {
95572daa72eSMax Reitz     BlockDriverState *bs = NULL;
9566db95603SChristoph Hellwig     BlockDriver *drv;
957c2ad1b0cSKevin Wolf     const char *drvname;
95898289620SKevin Wolf     bool allow_protocol_prefix = false;
95934b5d2c6SMax Reitz     Error *local_err = NULL;
96083f64091Sbellard     int ret;
9613b0d4f61Sbellard 
962707ff828SKevin Wolf     /* NULL means an empty set of options */
963707ff828SKevin Wolf     if (options == NULL) {
964707ff828SKevin Wolf         options = qdict_new();
9653b0d4f61Sbellard     }
966707ff828SKevin Wolf 
96772daa72eSMax Reitz     if (reference) {
96872daa72eSMax Reitz         if (filename || qdict_size(options)) {
96972daa72eSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
97072daa72eSMax Reitz                        "additional options or a new filename");
97172daa72eSMax Reitz             return -EINVAL;
97272daa72eSMax Reitz         }
97372daa72eSMax Reitz         QDECREF(options);
97472daa72eSMax Reitz 
97572daa72eSMax Reitz         bs = bdrv_find(reference);
97672daa72eSMax Reitz         if (!bs) {
97772daa72eSMax Reitz             error_setg(errp, "Cannot find block device '%s'", reference);
97872daa72eSMax Reitz             return -ENODEV;
97972daa72eSMax Reitz         }
98072daa72eSMax Reitz         bdrv_ref(bs);
98172daa72eSMax Reitz         *pbs = bs;
98272daa72eSMax Reitz         return 0;
98372daa72eSMax Reitz     }
98472daa72eSMax Reitz 
985707ff828SKevin Wolf     bs = bdrv_new("");
986707ff828SKevin Wolf     bs->options = options;
987707ff828SKevin Wolf     options = qdict_clone_shallow(options);
988707ff828SKevin Wolf 
989035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
990035fccdfSKevin Wolf     if (!filename) {
991035fccdfSKevin Wolf         filename = qdict_get_try_str(options, "filename");
992035fccdfSKevin Wolf     } else if (filename && !qdict_haskey(options, "filename")) {
993035fccdfSKevin Wolf         qdict_put(options, "filename", qstring_from_str(filename));
99498289620SKevin Wolf         allow_protocol_prefix = true;
995035fccdfSKevin Wolf     } else {
99634b5d2c6SMax Reitz         error_setg(errp, "Can't specify 'file' and 'filename' options at the "
99734b5d2c6SMax Reitz                    "same time");
998035fccdfSKevin Wolf         ret = -EINVAL;
999035fccdfSKevin Wolf         goto fail;
1000035fccdfSKevin Wolf     }
1001035fccdfSKevin Wolf 
1002c2ad1b0cSKevin Wolf     /* Find the right block driver */
1003c2ad1b0cSKevin Wolf     drvname = qdict_get_try_str(options, "driver");
1004c2ad1b0cSKevin Wolf     if (drvname) {
10058f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
100634b5d2c6SMax Reitz         if (!drv) {
100734b5d2c6SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
100834b5d2c6SMax Reitz         }
1009c2ad1b0cSKevin Wolf         qdict_del(options, "driver");
1010c2ad1b0cSKevin Wolf     } else if (filename) {
101198289620SKevin Wolf         drv = bdrv_find_protocol(filename, allow_protocol_prefix);
101298289620SKevin Wolf         if (!drv) {
101334b5d2c6SMax Reitz             error_setg(errp, "Unknown protocol");
101498289620SKevin Wolf         }
1015c2ad1b0cSKevin Wolf     } else {
101634b5d2c6SMax Reitz         error_setg(errp, "Must specify either driver or file");
1017c2ad1b0cSKevin Wolf         drv = NULL;
1018c2ad1b0cSKevin Wolf     }
1019c2ad1b0cSKevin Wolf 
1020c2ad1b0cSKevin Wolf     if (!drv) {
102134b5d2c6SMax Reitz         /* errp has been set already */
1022c2ad1b0cSKevin Wolf         ret = -ENOENT;
1023c2ad1b0cSKevin Wolf         goto fail;
1024c2ad1b0cSKevin Wolf     }
1025c2ad1b0cSKevin Wolf 
1026c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
1027c2ad1b0cSKevin Wolf     if (drv->bdrv_parse_filename && filename) {
10286963a30dSKevin Wolf         drv->bdrv_parse_filename(filename, options, &local_err);
10296963a30dSKevin Wolf         if (error_is_set(&local_err)) {
103034b5d2c6SMax Reitz             error_propagate(errp, local_err);
10316963a30dSKevin Wolf             ret = -EINVAL;
10326963a30dSKevin Wolf             goto fail;
10336963a30dSKevin Wolf         }
103456d1b4d2SKevin Wolf         qdict_del(options, "filename");
1035030be321SBenoît Canet     } else if (drv->bdrv_needs_filename && !filename) {
103634b5d2c6SMax Reitz         error_setg(errp, "The '%s' block driver requires a file name",
1037c2ad1b0cSKevin Wolf                    drv->format_name);
1038c2ad1b0cSKevin Wolf         ret = -EINVAL;
1039c2ad1b0cSKevin Wolf         goto fail;
10406963a30dSKevin Wolf     }
10416963a30dSKevin Wolf 
1042505d7583SMax Reitz     if (!drv->bdrv_file_open) {
1043505d7583SMax Reitz         ret = bdrv_open(bs, filename, options, flags, drv, &local_err);
1044505d7583SMax Reitz         options = NULL;
1045505d7583SMax Reitz     } else {
104634b5d2c6SMax Reitz         ret = bdrv_open_common(bs, NULL, options, flags, drv, &local_err);
1047505d7583SMax Reitz     }
1048707ff828SKevin Wolf     if (ret < 0) {
104934b5d2c6SMax Reitz         error_propagate(errp, local_err);
1050707ff828SKevin Wolf         goto fail;
1051707ff828SKevin Wolf     }
1052707ff828SKevin Wolf 
1053707ff828SKevin Wolf     /* Check if any unknown options were used */
1054505d7583SMax Reitz     if (options && (qdict_size(options) != 0)) {
1055707ff828SKevin Wolf         const QDictEntry *entry = qdict_first(options);
105634b5d2c6SMax Reitz         error_setg(errp, "Block protocol '%s' doesn't support the option '%s'",
1057707ff828SKevin Wolf                    drv->format_name, entry->key);
1058707ff828SKevin Wolf         ret = -EINVAL;
1059707ff828SKevin Wolf         goto fail;
1060707ff828SKevin Wolf     }
1061707ff828SKevin Wolf     QDECREF(options);
1062707ff828SKevin Wolf 
106371d0770cSaliguori     bs->growable = 1;
106483f64091Sbellard     *pbs = bs;
106583f64091Sbellard     return 0;
1066707ff828SKevin Wolf 
1067707ff828SKevin Wolf fail:
1068707ff828SKevin Wolf     QDECREF(options);
1069707ff828SKevin Wolf     if (!bs->drv) {
1070707ff828SKevin Wolf         QDECREF(bs->options);
1071707ff828SKevin Wolf     }
10724f6fd349SFam Zheng     bdrv_unref(bs);
1073707ff828SKevin Wolf     return ret;
10743b0d4f61Sbellard }
10753b0d4f61Sbellard 
107631ca6d07SKevin Wolf /*
107731ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
107831ca6d07SKevin Wolf  *
107931ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
108031ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
108131ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
108231ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
108331ca6d07SKevin Wolf  */
108434b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
10859156df12SPaolo Bonzini {
10869156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
10879156df12SPaolo Bonzini     int back_flags, ret;
10889156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
108934b5d2c6SMax Reitz     Error *local_err = NULL;
10909156df12SPaolo Bonzini 
10919156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
109231ca6d07SKevin Wolf         QDECREF(options);
10939156df12SPaolo Bonzini         return 0;
10949156df12SPaolo Bonzini     }
10959156df12SPaolo Bonzini 
109631ca6d07SKevin Wolf     /* NULL means an empty set of options */
109731ca6d07SKevin Wolf     if (options == NULL) {
109831ca6d07SKevin Wolf         options = qdict_new();
109931ca6d07SKevin Wolf     }
110031ca6d07SKevin Wolf 
11019156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
11021cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
11031cb6f506SKevin Wolf         backing_filename[0] = '\0';
11041cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
110531ca6d07SKevin Wolf         QDECREF(options);
11069156df12SPaolo Bonzini         return 0;
1107dbecebddSFam Zheng     } else {
1108dbecebddSFam Zheng         bdrv_get_full_backing_filename(bs, backing_filename,
1109dbecebddSFam Zheng                                        sizeof(backing_filename));
11109156df12SPaolo Bonzini     }
11119156df12SPaolo Bonzini 
11129156df12SPaolo Bonzini     bs->backing_hd = bdrv_new("");
11139156df12SPaolo Bonzini 
11149156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
11159156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
11169156df12SPaolo Bonzini     }
11179156df12SPaolo Bonzini 
11189156df12SPaolo Bonzini     /* backing files always opened read-only */
111987a5debdSThibaut LAURENT     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
112087a5debdSThibaut LAURENT                                     BDRV_O_COPY_ON_READ);
11219156df12SPaolo Bonzini 
112231ca6d07SKevin Wolf     ret = bdrv_open(bs->backing_hd,
112331ca6d07SKevin Wolf                     *backing_filename ? backing_filename : NULL, options,
112434b5d2c6SMax Reitz                     back_flags, back_drv, &local_err);
11259156df12SPaolo Bonzini     if (ret < 0) {
11264f6fd349SFam Zheng         bdrv_unref(bs->backing_hd);
11279156df12SPaolo Bonzini         bs->backing_hd = NULL;
11289156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1129b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1130b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1131b04b6b6eSFam Zheng         error_free(local_err);
11329156df12SPaolo Bonzini         return ret;
11339156df12SPaolo Bonzini     }
1134d80ac658SPeter Feiner 
1135d80ac658SPeter Feiner     if (bs->backing_hd->file) {
113661ed2684SMax Reitz         pstrcpy(bs->backing_file, sizeof(bs->backing_file),
113761ed2684SMax Reitz                 bs->backing_hd->file->filename);
1138d80ac658SPeter Feiner     }
1139d80ac658SPeter Feiner 
1140d34682cdSKevin Wolf     /* Recalculate the BlockLimits with the backing file */
1141d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
1142d34682cdSKevin Wolf 
11439156df12SPaolo Bonzini     return 0;
11449156df12SPaolo Bonzini }
11459156df12SPaolo Bonzini 
1146b6ce07aaSKevin Wolf /*
1147da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1148da557aacSMax Reitz  * device's options.
1149da557aacSMax Reitz  *
1150da557aacSMax Reitz  * If force_raw is true, bdrv_file_open() will be used, thereby preventing any
1151da557aacSMax Reitz  * image format auto-detection. If it is false and a filename is given,
1152da557aacSMax Reitz  * bdrv_open() will be used for auto-detection.
1153da557aacSMax Reitz  *
1154da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1155da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1156da557aacSMax Reitz  *
1157da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1158da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1159da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1160da557aacSMax Reitz  * BlockdevRef.
1161da557aacSMax Reitz  *
1162da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1163da557aacSMax Reitz  */
1164da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1165da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1166da557aacSMax Reitz                     bool force_raw, bool allow_none, Error **errp)
1167da557aacSMax Reitz {
1168da557aacSMax Reitz     QDict *image_options;
1169da557aacSMax Reitz     int ret;
1170da557aacSMax Reitz     char *bdref_key_dot;
1171da557aacSMax Reitz     const char *reference;
1172da557aacSMax Reitz 
1173da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1174da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1175da557aacSMax Reitz     g_free(bdref_key_dot);
1176da557aacSMax Reitz 
1177da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1178da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1179da557aacSMax Reitz         if (allow_none) {
1180da557aacSMax Reitz             ret = 0;
1181da557aacSMax Reitz         } else {
1182da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1183da557aacSMax Reitz                        bdref_key);
1184da557aacSMax Reitz             ret = -EINVAL;
1185da557aacSMax Reitz         }
1186da557aacSMax Reitz         goto done;
1187da557aacSMax Reitz     }
1188da557aacSMax Reitz 
1189da557aacSMax Reitz     if (filename && !force_raw) {
1190da557aacSMax Reitz         /* If a filename is given and the block driver should be detected
1191da557aacSMax Reitz            automatically (instead of using none), use bdrv_open() in order to do
1192da557aacSMax Reitz            that auto-detection. */
1193da557aacSMax Reitz         BlockDriverState *bs;
1194da557aacSMax Reitz 
1195da557aacSMax Reitz         if (reference) {
1196da557aacSMax Reitz             error_setg(errp, "Cannot reference an existing block device while "
1197da557aacSMax Reitz                        "giving a filename");
1198da557aacSMax Reitz             ret = -EINVAL;
1199da557aacSMax Reitz             goto done;
1200da557aacSMax Reitz         }
1201da557aacSMax Reitz 
1202da557aacSMax Reitz         bs = bdrv_new("");
1203da557aacSMax Reitz         ret = bdrv_open(bs, filename, image_options, flags, NULL, errp);
1204da557aacSMax Reitz         if (ret < 0) {
1205da557aacSMax Reitz             bdrv_unref(bs);
1206da557aacSMax Reitz         } else {
1207da557aacSMax Reitz             *pbs = bs;
1208da557aacSMax Reitz         }
1209da557aacSMax Reitz     } else {
1210da557aacSMax Reitz         ret = bdrv_file_open(pbs, filename, reference, image_options, flags,
1211da557aacSMax Reitz                              errp);
1212da557aacSMax Reitz     }
1213da557aacSMax Reitz 
1214da557aacSMax Reitz done:
1215da557aacSMax Reitz     qdict_del(options, bdref_key);
1216da557aacSMax Reitz     return ret;
1217da557aacSMax Reitz }
1218da557aacSMax Reitz 
1219da557aacSMax Reitz /*
1220b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1221de9c0cecSKevin Wolf  *
1222de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1223de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1224de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1225de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1226b6ce07aaSKevin Wolf  */
1227de9c0cecSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
122834b5d2c6SMax Reitz               int flags, BlockDriver *drv, Error **errp)
1229ea2384d3Sbellard {
1230b6ce07aaSKevin Wolf     int ret;
123189c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
123289c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
1233f500a6d3SKevin Wolf     BlockDriverState *file = NULL;
123474fe54f2SKevin Wolf     const char *drvname;
123534b5d2c6SMax Reitz     Error *local_err = NULL;
123633e3963eSbellard 
1237de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1238de9c0cecSKevin Wolf     if (options == NULL) {
1239de9c0cecSKevin Wolf         options = qdict_new();
1240de9c0cecSKevin Wolf     }
1241de9c0cecSKevin Wolf 
1242de9c0cecSKevin Wolf     bs->options = options;
1243b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1244de9c0cecSKevin Wolf 
1245de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
124683f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
1247ea2384d3Sbellard         BlockDriverState *bs1;
1248ea2384d3Sbellard         int64_t total_size;
124991a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
125008b392e1SKevin Wolf         QEMUOptionParameter *create_options;
12519fd3171aSKevin Wolf         QDict *snapshot_options;
1252c2ad1b0cSKevin Wolf 
1253ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
1254ea2384d3Sbellard            instead of opening 'filename' directly */
1255ea2384d3Sbellard 
12569fd3171aSKevin Wolf         /* Get the required size from the image */
1257ea2384d3Sbellard         bs1 = bdrv_new("");
12589fd3171aSKevin Wolf         QINCREF(options);
1259c9fbb99dSKevin Wolf         ret = bdrv_open(bs1, filename, options, BDRV_O_NO_BACKING,
1260c9fbb99dSKevin Wolf                         drv, &local_err);
126151d7c00cSaliguori         if (ret < 0) {
12624f6fd349SFam Zheng             bdrv_unref(bs1);
1263de9c0cecSKevin Wolf             goto fail;
1264ea2384d3Sbellard         }
12653e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
12667c96d46eSaliguori 
12674f6fd349SFam Zheng         bdrv_unref(bs1);
1268ea2384d3Sbellard 
12699fd3171aSKevin Wolf         /* Create the temporary image */
1270eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1271eba25057SJim Meyering         if (ret < 0) {
127234b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not get temporary filename");
1273de9c0cecSKevin Wolf             goto fail;
1274eba25057SJim Meyering         }
12757c96d46eSaliguori 
127691a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
127708b392e1SKevin Wolf         create_options = parse_option_parameters("", bdrv_qcow2->create_options,
127808b392e1SKevin Wolf                                                  NULL);
127991a073a9SKevin Wolf 
128008b392e1SKevin Wolf         set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
128191a073a9SKevin Wolf 
1282cc84d90fSMax Reitz         ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
128308b392e1SKevin Wolf         free_option_parameters(create_options);
128451d7c00cSaliguori         if (ret < 0) {
128534b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not create temporary overlay "
1286cc84d90fSMax Reitz                              "'%s': %s", tmp_filename,
1287cc84d90fSMax Reitz                              error_get_pretty(local_err));
1288cc84d90fSMax Reitz             error_free(local_err);
1289cc84d90fSMax Reitz             local_err = NULL;
1290de9c0cecSKevin Wolf             goto fail;
1291ea2384d3Sbellard         }
129291a073a9SKevin Wolf 
12939fd3171aSKevin Wolf         /* Prepare a new options QDict for the temporary file, where user
12949fd3171aSKevin Wolf          * options refer to the backing file */
12959fd3171aSKevin Wolf         if (filename) {
12969fd3171aSKevin Wolf             qdict_put(options, "file.filename", qstring_from_str(filename));
12979fd3171aSKevin Wolf         }
12989fd3171aSKevin Wolf         if (drv) {
12999fd3171aSKevin Wolf             qdict_put(options, "driver", qstring_from_str(drv->format_name));
13009fd3171aSKevin Wolf         }
13019fd3171aSKevin Wolf 
13029fd3171aSKevin Wolf         snapshot_options = qdict_new();
13039fd3171aSKevin Wolf         qdict_put(snapshot_options, "backing", options);
13049fd3171aSKevin Wolf         qdict_flatten(snapshot_options);
13059fd3171aSKevin Wolf 
13069fd3171aSKevin Wolf         bs->options = snapshot_options;
13079fd3171aSKevin Wolf         options = qdict_clone_shallow(bs->options);
13089fd3171aSKevin Wolf 
1309ea2384d3Sbellard         filename = tmp_filename;
131091a073a9SKevin Wolf         drv = bdrv_qcow2;
1311ea2384d3Sbellard         bs->is_temporary = 1;
1312ea2384d3Sbellard     }
1313ea2384d3Sbellard 
1314f500a6d3SKevin Wolf     /* Open image file without format layer */
1315be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1316be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1317be028adcSJeff Cody     }
1318be028adcSJeff Cody 
1319054963f8SMax Reitz     ret = bdrv_open_image(&file, filename, options, "file",
1320054963f8SMax Reitz                           bdrv_open_flags(bs, flags | BDRV_O_UNMAP), true, true,
13212a05cbe4SMax Reitz                           &local_err);
1322f500a6d3SKevin Wolf     if (ret < 0) {
1323de9c0cecSKevin Wolf         goto fail;
1324f500a6d3SKevin Wolf     }
1325f500a6d3SKevin Wolf 
1326f500a6d3SKevin Wolf     /* Find the right image format driver */
132774fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
132874fe54f2SKevin Wolf     if (drvname) {
13298f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
133074fe54f2SKevin Wolf         qdict_del(options, "driver");
133106d22aa3SKevin Wolf         if (!drv) {
133206d22aa3SKevin Wolf             error_setg(errp, "Invalid driver: '%s'", drvname);
133306d22aa3SKevin Wolf             ret = -EINVAL;
133406d22aa3SKevin Wolf             goto unlink_and_fail;
133506d22aa3SKevin Wolf         }
133674fe54f2SKevin Wolf     }
133774fe54f2SKevin Wolf 
1338f500a6d3SKevin Wolf     if (!drv) {
13392a05cbe4SMax Reitz         if (file) {
134034b5d2c6SMax Reitz             ret = find_image_format(file, filename, &drv, &local_err);
13412a05cbe4SMax Reitz         } else {
13422a05cbe4SMax Reitz             error_setg(errp, "Must specify either driver or file");
13432a05cbe4SMax Reitz             ret = -EINVAL;
13442a05cbe4SMax Reitz             goto unlink_and_fail;
13452a05cbe4SMax Reitz         }
1346f500a6d3SKevin Wolf     }
1347f500a6d3SKevin Wolf 
1348f500a6d3SKevin Wolf     if (!drv) {
1349f500a6d3SKevin Wolf         goto unlink_and_fail;
1350f500a6d3SKevin Wolf     }
1351f500a6d3SKevin Wolf 
1352b6ce07aaSKevin Wolf     /* Open the image */
135334b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1354b6ce07aaSKevin Wolf     if (ret < 0) {
13556987307cSChristoph Hellwig         goto unlink_and_fail;
13566987307cSChristoph Hellwig     }
13576987307cSChristoph Hellwig 
13582a05cbe4SMax Reitz     if (file && (bs->file != file)) {
13594f6fd349SFam Zheng         bdrv_unref(file);
1360f500a6d3SKevin Wolf         file = NULL;
1361f500a6d3SKevin Wolf     }
1362f500a6d3SKevin Wolf 
1363b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
13649156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
136531ca6d07SKevin Wolf         QDict *backing_options;
136631ca6d07SKevin Wolf 
13675726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
136834b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1369b6ce07aaSKevin Wolf         if (ret < 0) {
1370b6ad491aSKevin Wolf             goto close_and_fail;
1371b6ce07aaSKevin Wolf         }
1372b6ce07aaSKevin Wolf     }
1373b6ce07aaSKevin Wolf 
1374b6ad491aSKevin Wolf     /* Check if any unknown options were used */
1375b6ad491aSKevin Wolf     if (qdict_size(options) != 0) {
1376b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
137734b5d2c6SMax Reitz         error_setg(errp, "Block format '%s' used by device '%s' doesn't "
137834b5d2c6SMax Reitz                    "support the option '%s'", drv->format_name, bs->device_name,
137934b5d2c6SMax Reitz                    entry->key);
1380b6ad491aSKevin Wolf 
1381b6ad491aSKevin Wolf         ret = -EINVAL;
1382b6ad491aSKevin Wolf         goto close_and_fail;
1383b6ad491aSKevin Wolf     }
1384b6ad491aSKevin Wolf     QDECREF(options);
1385b6ad491aSKevin Wolf 
1386b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
13877d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1388b6ce07aaSKevin Wolf     }
1389b6ce07aaSKevin Wolf 
1390b6ce07aaSKevin Wolf     return 0;
1391b6ce07aaSKevin Wolf 
1392b6ce07aaSKevin Wolf unlink_and_fail:
1393f500a6d3SKevin Wolf     if (file != NULL) {
13944f6fd349SFam Zheng         bdrv_unref(file);
1395f500a6d3SKevin Wolf     }
1396b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1397b6ce07aaSKevin Wolf         unlink(filename);
1398b6ce07aaSKevin Wolf     }
1399de9c0cecSKevin Wolf fail:
1400de9c0cecSKevin Wolf     QDECREF(bs->options);
1401b6ad491aSKevin Wolf     QDECREF(options);
1402de9c0cecSKevin Wolf     bs->options = NULL;
140334b5d2c6SMax Reitz     if (error_is_set(&local_err)) {
140434b5d2c6SMax Reitz         error_propagate(errp, local_err);
140534b5d2c6SMax Reitz     }
1406b6ad491aSKevin Wolf     return ret;
1407de9c0cecSKevin Wolf 
1408b6ad491aSKevin Wolf close_and_fail:
1409b6ad491aSKevin Wolf     bdrv_close(bs);
1410b6ad491aSKevin Wolf     QDECREF(options);
141134b5d2c6SMax Reitz     if (error_is_set(&local_err)) {
141234b5d2c6SMax Reitz         error_propagate(errp, local_err);
141334b5d2c6SMax Reitz     }
1414b6ce07aaSKevin Wolf     return ret;
1415b6ce07aaSKevin Wolf }
1416b6ce07aaSKevin Wolf 
1417e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1418e971aa12SJeff Cody      bool prepared;
1419e971aa12SJeff Cody      BDRVReopenState state;
1420e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1421e971aa12SJeff Cody } BlockReopenQueueEntry;
1422e971aa12SJeff Cody 
1423e971aa12SJeff Cody /*
1424e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1425e971aa12SJeff Cody  * reopen of multiple devices.
1426e971aa12SJeff Cody  *
1427e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1428e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1429e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1430e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1431e971aa12SJeff Cody  * atomic 'set'.
1432e971aa12SJeff Cody  *
1433e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1434e971aa12SJeff Cody  *
1435e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1436e971aa12SJeff Cody  *
1437e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1438e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1439e971aa12SJeff Cody  *
1440e971aa12SJeff Cody  */
1441e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1442e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1443e971aa12SJeff Cody {
1444e971aa12SJeff Cody     assert(bs != NULL);
1445e971aa12SJeff Cody 
1446e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1447e971aa12SJeff Cody     if (bs_queue == NULL) {
1448e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1449e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1450e971aa12SJeff Cody     }
1451e971aa12SJeff Cody 
1452e971aa12SJeff Cody     if (bs->file) {
1453e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1454e971aa12SJeff Cody     }
1455e971aa12SJeff Cody 
1456e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1457e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1458e971aa12SJeff Cody 
1459e971aa12SJeff Cody     bs_entry->state.bs = bs;
1460e971aa12SJeff Cody     bs_entry->state.flags = flags;
1461e971aa12SJeff Cody 
1462e971aa12SJeff Cody     return bs_queue;
1463e971aa12SJeff Cody }
1464e971aa12SJeff Cody 
1465e971aa12SJeff Cody /*
1466e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1467e971aa12SJeff Cody  *
1468e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1469e971aa12SJeff Cody  * via bdrv_reopen_queue().
1470e971aa12SJeff Cody  *
1471e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1472e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1473e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1474e971aa12SJeff Cody  * data cleaned up.
1475e971aa12SJeff Cody  *
1476e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1477e971aa12SJeff Cody  * to all devices.
1478e971aa12SJeff Cody  *
1479e971aa12SJeff Cody  */
1480e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1481e971aa12SJeff Cody {
1482e971aa12SJeff Cody     int ret = -1;
1483e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1484e971aa12SJeff Cody     Error *local_err = NULL;
1485e971aa12SJeff Cody 
1486e971aa12SJeff Cody     assert(bs_queue != NULL);
1487e971aa12SJeff Cody 
1488e971aa12SJeff Cody     bdrv_drain_all();
1489e971aa12SJeff Cody 
1490e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1491e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1492e971aa12SJeff Cody             error_propagate(errp, local_err);
1493e971aa12SJeff Cody             goto cleanup;
1494e971aa12SJeff Cody         }
1495e971aa12SJeff Cody         bs_entry->prepared = true;
1496e971aa12SJeff Cody     }
1497e971aa12SJeff Cody 
1498e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1499e971aa12SJeff Cody      * changes
1500e971aa12SJeff Cody      */
1501e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1502e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1503e971aa12SJeff Cody     }
1504e971aa12SJeff Cody 
1505e971aa12SJeff Cody     ret = 0;
1506e971aa12SJeff Cody 
1507e971aa12SJeff Cody cleanup:
1508e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1509e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1510e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1511e971aa12SJeff Cody         }
1512e971aa12SJeff Cody         g_free(bs_entry);
1513e971aa12SJeff Cody     }
1514e971aa12SJeff Cody     g_free(bs_queue);
1515e971aa12SJeff Cody     return ret;
1516e971aa12SJeff Cody }
1517e971aa12SJeff Cody 
1518e971aa12SJeff Cody 
1519e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1520e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1521e971aa12SJeff Cody {
1522e971aa12SJeff Cody     int ret = -1;
1523e971aa12SJeff Cody     Error *local_err = NULL;
1524e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1525e971aa12SJeff Cody 
1526e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1527e971aa12SJeff Cody     if (local_err != NULL) {
1528e971aa12SJeff Cody         error_propagate(errp, local_err);
1529e971aa12SJeff Cody     }
1530e971aa12SJeff Cody     return ret;
1531e971aa12SJeff Cody }
1532e971aa12SJeff Cody 
1533e971aa12SJeff Cody 
1534e971aa12SJeff Cody /*
1535e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1536e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1537e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1538e971aa12SJeff Cody  *
1539e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1540e971aa12SJeff Cody  * flags are the new open flags
1541e971aa12SJeff Cody  * queue is the reopen queue
1542e971aa12SJeff Cody  *
1543e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1544e971aa12SJeff Cody  * as well.
1545e971aa12SJeff Cody  *
1546e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1547e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1548e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1549e971aa12SJeff Cody  *
1550e971aa12SJeff Cody  */
1551e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1552e971aa12SJeff Cody                         Error **errp)
1553e971aa12SJeff Cody {
1554e971aa12SJeff Cody     int ret = -1;
1555e971aa12SJeff Cody     Error *local_err = NULL;
1556e971aa12SJeff Cody     BlockDriver *drv;
1557e971aa12SJeff Cody 
1558e971aa12SJeff Cody     assert(reopen_state != NULL);
1559e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1560e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1561e971aa12SJeff Cody 
1562e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1563e971aa12SJeff Cody      * to r/w */
1564e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1565e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1566e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1567e971aa12SJeff Cody                   reopen_state->bs->device_name);
1568e971aa12SJeff Cody         goto error;
1569e971aa12SJeff Cody     }
1570e971aa12SJeff Cody 
1571e971aa12SJeff Cody 
1572e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1573e971aa12SJeff Cody     if (ret) {
1574e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1575e971aa12SJeff Cody                   strerror(-ret));
1576e971aa12SJeff Cody         goto error;
1577e971aa12SJeff Cody     }
1578e971aa12SJeff Cody 
1579e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1580e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1581e971aa12SJeff Cody         if (ret) {
1582e971aa12SJeff Cody             if (local_err != NULL) {
1583e971aa12SJeff Cody                 error_propagate(errp, local_err);
1584e971aa12SJeff Cody             } else {
1585d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1586e971aa12SJeff Cody                            reopen_state->bs->filename);
1587e971aa12SJeff Cody             }
1588e971aa12SJeff Cody             goto error;
1589e971aa12SJeff Cody         }
1590e971aa12SJeff Cody     } else {
1591e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1592e971aa12SJeff Cody          * handler for each supported drv. */
1593e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1594e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1595e971aa12SJeff Cody                  "reopening of file");
1596e971aa12SJeff Cody         ret = -1;
1597e971aa12SJeff Cody         goto error;
1598e971aa12SJeff Cody     }
1599e971aa12SJeff Cody 
1600e971aa12SJeff Cody     ret = 0;
1601e971aa12SJeff Cody 
1602e971aa12SJeff Cody error:
1603e971aa12SJeff Cody     return ret;
1604e971aa12SJeff Cody }
1605e971aa12SJeff Cody 
1606e971aa12SJeff Cody /*
1607e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1608e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1609e971aa12SJeff Cody  * the active BlockDriverState contents.
1610e971aa12SJeff Cody  */
1611e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1612e971aa12SJeff Cody {
1613e971aa12SJeff Cody     BlockDriver *drv;
1614e971aa12SJeff Cody 
1615e971aa12SJeff Cody     assert(reopen_state != NULL);
1616e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1617e971aa12SJeff Cody     assert(drv != NULL);
1618e971aa12SJeff Cody 
1619e971aa12SJeff Cody     /* If there are any driver level actions to take */
1620e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1621e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1622e971aa12SJeff Cody     }
1623e971aa12SJeff Cody 
1624e971aa12SJeff Cody     /* set BDS specific flags now */
1625e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1626e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1627e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1628e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1629355ef4acSKevin Wolf 
1630355ef4acSKevin Wolf     bdrv_refresh_limits(reopen_state->bs);
1631e971aa12SJeff Cody }
1632e971aa12SJeff Cody 
1633e971aa12SJeff Cody /*
1634e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1635e971aa12SJeff Cody  * reopen_state
1636e971aa12SJeff Cody  */
1637e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1638e971aa12SJeff Cody {
1639e971aa12SJeff Cody     BlockDriver *drv;
1640e971aa12SJeff Cody 
1641e971aa12SJeff Cody     assert(reopen_state != NULL);
1642e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1643e971aa12SJeff Cody     assert(drv != NULL);
1644e971aa12SJeff Cody 
1645e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1646e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1647e971aa12SJeff Cody     }
1648e971aa12SJeff Cody }
1649e971aa12SJeff Cody 
1650e971aa12SJeff Cody 
1651fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1652fc01f7e7Sbellard {
16533e914655SPaolo Bonzini     if (bs->job) {
16543e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
16553e914655SPaolo Bonzini     }
165658fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
165758fda173SStefan Hajnoczi     bdrv_flush(bs);
165858fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1659d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
16607094f12fSKevin Wolf 
16613cbc002cSPaolo Bonzini     if (bs->drv) {
1662557df6acSStefan Hajnoczi         if (bs->backing_hd) {
16634f6fd349SFam Zheng             bdrv_unref(bs->backing_hd);
1664557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1665557df6acSStefan Hajnoczi         }
1666ea2384d3Sbellard         bs->drv->bdrv_close(bs);
16677267c094SAnthony Liguori         g_free(bs->opaque);
1668ea2384d3Sbellard #ifdef _WIN32
1669ea2384d3Sbellard         if (bs->is_temporary) {
1670ea2384d3Sbellard             unlink(bs->filename);
1671ea2384d3Sbellard         }
167267b915a5Sbellard #endif
1673ea2384d3Sbellard         bs->opaque = NULL;
1674ea2384d3Sbellard         bs->drv = NULL;
167553fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1676a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1677a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
16786405875cSPaolo Bonzini         bs->total_sectors = 0;
16796405875cSPaolo Bonzini         bs->encrypted = 0;
16806405875cSPaolo Bonzini         bs->valid_key = 0;
16816405875cSPaolo Bonzini         bs->sg = 0;
16826405875cSPaolo Bonzini         bs->growable = 0;
16830d51b4deSAsias He         bs->zero_beyond_eof = false;
1684de9c0cecSKevin Wolf         QDECREF(bs->options);
1685de9c0cecSKevin Wolf         bs->options = NULL;
1686b338082bSbellard 
168766f82ceeSKevin Wolf         if (bs->file != NULL) {
16884f6fd349SFam Zheng             bdrv_unref(bs->file);
16890ac9377dSPaolo Bonzini             bs->file = NULL;
169066f82ceeSKevin Wolf         }
16919ca11154SPavel Hrdina     }
169266f82ceeSKevin Wolf 
16937d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
169498f90dbaSZhi Yong Wu 
169598f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
169698f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
169798f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
169898f90dbaSZhi Yong Wu     }
1699b338082bSbellard }
1700b338082bSbellard 
17012bc93fedSMORITA Kazutaka void bdrv_close_all(void)
17022bc93fedSMORITA Kazutaka {
17032bc93fedSMORITA Kazutaka     BlockDriverState *bs;
17042bc93fedSMORITA Kazutaka 
1705dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17062bc93fedSMORITA Kazutaka         bdrv_close(bs);
17072bc93fedSMORITA Kazutaka     }
17082bc93fedSMORITA Kazutaka }
17092bc93fedSMORITA Kazutaka 
171088266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
171188266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
171288266f5aSStefan Hajnoczi {
171388266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
171488266f5aSStefan Hajnoczi         return true;
171588266f5aSStefan Hajnoczi     }
1716cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1717cc0681c4SBenoît Canet         return true;
1718cc0681c4SBenoît Canet     }
1719cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
172088266f5aSStefan Hajnoczi         return true;
172188266f5aSStefan Hajnoczi     }
172288266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
172388266f5aSStefan Hajnoczi         return true;
172488266f5aSStefan Hajnoczi     }
172588266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
172688266f5aSStefan Hajnoczi         return true;
172788266f5aSStefan Hajnoczi     }
172888266f5aSStefan Hajnoczi     return false;
172988266f5aSStefan Hajnoczi }
173088266f5aSStefan Hajnoczi 
173188266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
173288266f5aSStefan Hajnoczi {
173388266f5aSStefan Hajnoczi     BlockDriverState *bs;
1734dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
173588266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
173688266f5aSStefan Hajnoczi             return true;
173788266f5aSStefan Hajnoczi         }
173888266f5aSStefan Hajnoczi     }
173988266f5aSStefan Hajnoczi     return false;
174088266f5aSStefan Hajnoczi }
174188266f5aSStefan Hajnoczi 
1742922453bcSStefan Hajnoczi /*
1743922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1744922453bcSStefan Hajnoczi  *
1745922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1746922453bcSStefan Hajnoczi  * after calling this function.
17474c355d53SZhi Yong Wu  *
17484c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
17494c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
17504c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
17514c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
17524c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1753922453bcSStefan Hajnoczi  */
1754922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1755922453bcSStefan Hajnoczi {
175688266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
175788266f5aSStefan Hajnoczi     bool busy = true;
1758922453bcSStefan Hajnoczi     BlockDriverState *bs;
1759922453bcSStefan Hajnoczi 
176088266f5aSStefan Hajnoczi     while (busy) {
1761dc364f4cSBenoît Canet         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17620b06ef3bSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
17634c355d53SZhi Yong Wu         }
1764922453bcSStefan Hajnoczi 
176588266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
176688266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1767922453bcSStefan Hajnoczi     }
1768922453bcSStefan Hajnoczi }
1769922453bcSStefan Hajnoczi 
1770dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1771dc364f4cSBenoît Canet  * graph_bdrv_state list.
1772d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1773d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1774d22b2f41SRyan Harper {
1775d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1776dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1777d22b2f41SRyan Harper     }
1778d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1779dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1780dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1781dc364f4cSBenoît Canet     }
1782dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1783d22b2f41SRyan Harper }
1784d22b2f41SRyan Harper 
1785e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1786e023b2e2SPaolo Bonzini {
1787e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1788e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1789e023b2e2SPaolo Bonzini     }
1790e023b2e2SPaolo Bonzini }
1791e023b2e2SPaolo Bonzini 
17924ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
17934ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
17944ddc07caSPaolo Bonzini {
17954ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
17964ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
17974ddc07caSPaolo Bonzini 
17984ddc07caSPaolo Bonzini     /* dev info */
17994ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
18004ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
18014ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
18021b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
18034ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
18044ddc07caSPaolo Bonzini 
18054ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
18064ddc07caSPaolo Bonzini 
1807cc0681c4SBenoît Canet     /* i/o throttled req */
1808cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1809cc0681c4SBenoît Canet            &bs_src->throttle_state,
1810cc0681c4SBenoît Canet            sizeof(ThrottleState));
1811cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1812cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
18134ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
18144ddc07caSPaolo Bonzini 
18154ddc07caSPaolo Bonzini     /* r/w error */
18164ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
18174ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
18184ddc07caSPaolo Bonzini 
18194ddc07caSPaolo Bonzini     /* i/o status */
18204ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
18214ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
18224ddc07caSPaolo Bonzini 
18234ddc07caSPaolo Bonzini     /* dirty bitmap */
1824e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
18254ddc07caSPaolo Bonzini 
18269fcb0251SFam Zheng     /* reference count */
18279fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
18289fcb0251SFam Zheng 
18294ddc07caSPaolo Bonzini     /* job */
18304ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
18314ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
18324ddc07caSPaolo Bonzini 
18334ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
18344ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
18354ddc07caSPaolo Bonzini             bs_src->device_name);
1836dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
1837dc364f4cSBenoît Canet 
1838dc364f4cSBenoît Canet     /* keep the same entry in graph_bdrv_states
1839dc364f4cSBenoît Canet      * We do want to swap name but don't want to swap linked list entries
1840dc364f4cSBenoît Canet      */
1841dc364f4cSBenoît Canet     bs_dest->node_list   = bs_src->node_list;
18424ddc07caSPaolo Bonzini }
18434ddc07caSPaolo Bonzini 
18444ddc07caSPaolo Bonzini /*
18454ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
18464ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
18474ddc07caSPaolo Bonzini  * actually attached to a device.
18484ddc07caSPaolo Bonzini  *
18494ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
18504ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
18514ddc07caSPaolo Bonzini  *
18524ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
18534ddc07caSPaolo Bonzini  *
18544ddc07caSPaolo Bonzini  * This function does not create any image files.
18554ddc07caSPaolo Bonzini  */
18564ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
18574ddc07caSPaolo Bonzini {
18584ddc07caSPaolo Bonzini     BlockDriverState tmp;
18594ddc07caSPaolo Bonzini 
18604ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
18614ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
1862e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
18634ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
18644ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
18654ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
18664ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1867cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
18684ddc07caSPaolo Bonzini 
18694ddc07caSPaolo Bonzini     tmp = *bs_new;
18704ddc07caSPaolo Bonzini     *bs_new = *bs_old;
18714ddc07caSPaolo Bonzini     *bs_old = tmp;
18724ddc07caSPaolo Bonzini 
18734ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
18744ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
18754ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
18764ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
18774ddc07caSPaolo Bonzini 
18784ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
18794ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
18804ddc07caSPaolo Bonzini 
18814ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
18824ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
18834ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
18844ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
18854ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1886cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
18874ddc07caSPaolo Bonzini 
18884ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
18894ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
18904ddc07caSPaolo Bonzini }
18914ddc07caSPaolo Bonzini 
18928802d1fdSJeff Cody /*
18938802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
18948802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
18958802d1fdSJeff Cody  *
18968802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
18978802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
18988802d1fdSJeff Cody  *
1899f6801b83SJeff Cody  * bs_new is required to be anonymous.
1900f6801b83SJeff Cody  *
19018802d1fdSJeff Cody  * This function does not create any image files.
19028802d1fdSJeff Cody  */
19038802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
19048802d1fdSJeff Cody {
19054ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
19068802d1fdSJeff Cody 
19078802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
19088802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
19094ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
19104ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
19114ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
19124ddc07caSPaolo Bonzini             bs_new->filename);
19134ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
19144ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
19158802d1fdSJeff Cody }
19168802d1fdSJeff Cody 
19174f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
1918b338082bSbellard {
1919fa879d62SMarkus Armbruster     assert(!bs->dev);
19203e914655SPaolo Bonzini     assert(!bs->job);
19213e914655SPaolo Bonzini     assert(!bs->in_use);
19224f6fd349SFam Zheng     assert(!bs->refcnt);
1923e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
192418846deeSMarkus Armbruster 
1925e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1926e1b5c52eSStefan Hajnoczi 
19271b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1928d22b2f41SRyan Harper     bdrv_make_anon(bs);
192934c6f050Saurel32 
19307267c094SAnthony Liguori     g_free(bs);
1931fc01f7e7Sbellard }
1932fc01f7e7Sbellard 
1933fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1934fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
193518846deeSMarkus Armbruster {
1936fa879d62SMarkus Armbruster     if (bs->dev) {
193718846deeSMarkus Armbruster         return -EBUSY;
193818846deeSMarkus Armbruster     }
1939fa879d62SMarkus Armbruster     bs->dev = dev;
194028a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
194118846deeSMarkus Armbruster     return 0;
194218846deeSMarkus Armbruster }
194318846deeSMarkus Armbruster 
1944fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1945fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
194618846deeSMarkus Armbruster {
1947fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1948fa879d62SMarkus Armbruster         abort();
1949fa879d62SMarkus Armbruster     }
1950fa879d62SMarkus Armbruster }
1951fa879d62SMarkus Armbruster 
1952fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1953fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1954fa879d62SMarkus Armbruster {
1955fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1956fa879d62SMarkus Armbruster     bs->dev = NULL;
19570e49de52SMarkus Armbruster     bs->dev_ops = NULL;
19580e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
19591b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
196018846deeSMarkus Armbruster }
196118846deeSMarkus Armbruster 
1962fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1963fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
196418846deeSMarkus Armbruster {
1965fa879d62SMarkus Armbruster     return bs->dev;
196618846deeSMarkus Armbruster }
196718846deeSMarkus Armbruster 
19680e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
19690e49de52SMarkus Armbruster                       void *opaque)
19700e49de52SMarkus Armbruster {
19710e49de52SMarkus Armbruster     bs->dev_ops = ops;
19720e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
19730e49de52SMarkus Armbruster }
19740e49de52SMarkus Armbruster 
197532c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
197632c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
19771ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1978329c0a48SLuiz Capitulino {
1979329c0a48SLuiz Capitulino     QObject *data;
1980329c0a48SLuiz Capitulino     const char *action_str;
1981329c0a48SLuiz Capitulino 
1982329c0a48SLuiz Capitulino     switch (action) {
1983329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1984329c0a48SLuiz Capitulino         action_str = "report";
1985329c0a48SLuiz Capitulino         break;
1986329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1987329c0a48SLuiz Capitulino         action_str = "ignore";
1988329c0a48SLuiz Capitulino         break;
1989329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1990329c0a48SLuiz Capitulino         action_str = "stop";
1991329c0a48SLuiz Capitulino         break;
1992329c0a48SLuiz Capitulino     default:
1993329c0a48SLuiz Capitulino         abort();
1994329c0a48SLuiz Capitulino     }
1995329c0a48SLuiz Capitulino 
1996329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1997329c0a48SLuiz Capitulino                               bdrv->device_name,
1998329c0a48SLuiz Capitulino                               action_str,
1999329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
200032c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
2001329c0a48SLuiz Capitulino 
2002329c0a48SLuiz Capitulino     qobject_decref(data);
2003329c0a48SLuiz Capitulino }
2004329c0a48SLuiz Capitulino 
20056f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
20066f382ed2SLuiz Capitulino {
20076f382ed2SLuiz Capitulino     QObject *data;
20086f382ed2SLuiz Capitulino 
20096f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
20106f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
20116f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
20126f382ed2SLuiz Capitulino 
20136f382ed2SLuiz Capitulino     qobject_decref(data);
20146f382ed2SLuiz Capitulino }
20156f382ed2SLuiz Capitulino 
20167d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
20170e49de52SMarkus Armbruster {
2018145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
20196f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
20207d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
20216f382ed2SLuiz Capitulino         if (tray_was_closed) {
20226f382ed2SLuiz Capitulino             /* tray open */
20236f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
20246f382ed2SLuiz Capitulino         }
20256f382ed2SLuiz Capitulino         if (load) {
20266f382ed2SLuiz Capitulino             /* tray close */
20276f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
20286f382ed2SLuiz Capitulino         }
2029145feb17SMarkus Armbruster     }
2030145feb17SMarkus Armbruster }
2031145feb17SMarkus Armbruster 
20322c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
20332c6942faSMarkus Armbruster {
20342c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
20352c6942faSMarkus Armbruster }
20362c6942faSMarkus Armbruster 
2037025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2038025ccaa7SPaolo Bonzini {
2039025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2040025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2041025ccaa7SPaolo Bonzini     }
2042025ccaa7SPaolo Bonzini }
2043025ccaa7SPaolo Bonzini 
2044e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2045e4def80bSMarkus Armbruster {
2046e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2047e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
2048e4def80bSMarkus Armbruster     }
2049e4def80bSMarkus Armbruster     return false;
2050e4def80bSMarkus Armbruster }
2051e4def80bSMarkus Armbruster 
2052145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
2053145feb17SMarkus Armbruster {
2054145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
2055145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
20560e49de52SMarkus Armbruster     }
20570e49de52SMarkus Armbruster }
20580e49de52SMarkus Armbruster 
2059f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2060f107639aSMarkus Armbruster {
2061f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2062f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2063f107639aSMarkus Armbruster     }
2064f107639aSMarkus Armbruster     return false;
2065f107639aSMarkus Armbruster }
2066f107639aSMarkus Armbruster 
2067e97fc193Saliguori /*
2068e97fc193Saliguori  * Run consistency checks on an image
2069e97fc193Saliguori  *
2070e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2071a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2072e076f338SKevin Wolf  * check are stored in res.
2073e97fc193Saliguori  */
20744534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2075e97fc193Saliguori {
2076e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2077e97fc193Saliguori         return -ENOTSUP;
2078e97fc193Saliguori     }
2079e97fc193Saliguori 
2080e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
20814534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2082e97fc193Saliguori }
2083e97fc193Saliguori 
20848a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
20858a426614SKevin Wolf 
208633e3963eSbellard /* commit COW file into the raw image */
208733e3963eSbellard int bdrv_commit(BlockDriverState *bs)
208833e3963eSbellard {
208919cb3738Sbellard     BlockDriver *drv = bs->drv;
209072706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
20918a426614SKevin Wolf     int n, ro, open_flags;
20920bce597dSJeff Cody     int ret = 0;
209372706ea4SJeff Cody     uint8_t *buf = NULL;
2094c2cba3d9SJim Meyering     char filename[PATH_MAX];
209533e3963eSbellard 
209619cb3738Sbellard     if (!drv)
209719cb3738Sbellard         return -ENOMEDIUM;
209833e3963eSbellard 
20994dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
21004dca4b63SNaphtali Sprei         return -ENOTSUP;
21014dca4b63SNaphtali Sprei     }
21024dca4b63SNaphtali Sprei 
21032d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
21042d3735d3SStefan Hajnoczi         return -EBUSY;
21052d3735d3SStefan Hajnoczi     }
21062d3735d3SStefan Hajnoczi 
21074dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2108c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2109c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
21104dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
21114dca4b63SNaphtali Sprei 
21124dca4b63SNaphtali Sprei     if (ro) {
21130bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
21140bce597dSJeff Cody             return -EACCES;
21154dca4b63SNaphtali Sprei         }
2116ea2384d3Sbellard     }
2117ea2384d3Sbellard 
211872706ea4SJeff Cody     length = bdrv_getlength(bs);
211972706ea4SJeff Cody     if (length < 0) {
212072706ea4SJeff Cody         ret = length;
212172706ea4SJeff Cody         goto ro_cleanup;
212272706ea4SJeff Cody     }
212372706ea4SJeff Cody 
212472706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
212572706ea4SJeff Cody     if (backing_length < 0) {
212672706ea4SJeff Cody         ret = backing_length;
212772706ea4SJeff Cody         goto ro_cleanup;
212872706ea4SJeff Cody     }
212972706ea4SJeff Cody 
213072706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
213172706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
213272706ea4SJeff Cody      * we must return an error */
213372706ea4SJeff Cody     if (length > backing_length) {
213472706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
213572706ea4SJeff Cody         if (ret < 0) {
213672706ea4SJeff Cody             goto ro_cleanup;
213772706ea4SJeff Cody         }
213872706ea4SJeff Cody     }
213972706ea4SJeff Cody 
214072706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
21417267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
21428a426614SKevin Wolf 
21438a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2144d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2145d663640cSPaolo Bonzini         if (ret < 0) {
2146d663640cSPaolo Bonzini             goto ro_cleanup;
2147d663640cSPaolo Bonzini         }
2148d663640cSPaolo Bonzini         if (ret) {
2149dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2150dabfa6ccSKevin Wolf             if (ret < 0) {
21514dca4b63SNaphtali Sprei                 goto ro_cleanup;
215233e3963eSbellard             }
215333e3963eSbellard 
2154dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2155dabfa6ccSKevin Wolf             if (ret < 0) {
21564dca4b63SNaphtali Sprei                 goto ro_cleanup;
215733e3963eSbellard             }
215833e3963eSbellard         }
215933e3963eSbellard     }
216095389c86Sbellard 
21611d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
21621d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2163dabfa6ccSKevin Wolf         if (ret < 0) {
2164dabfa6ccSKevin Wolf             goto ro_cleanup;
2165dabfa6ccSKevin Wolf         }
21661d44952fSChristoph Hellwig         bdrv_flush(bs);
21671d44952fSChristoph Hellwig     }
216895389c86Sbellard 
21693f5075aeSChristoph Hellwig     /*
21703f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
21713f5075aeSChristoph Hellwig      * stable on disk.
21723f5075aeSChristoph Hellwig      */
2173dabfa6ccSKevin Wolf     if (bs->backing_hd) {
21743f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2175dabfa6ccSKevin Wolf     }
21764dca4b63SNaphtali Sprei 
2177dabfa6ccSKevin Wolf     ret = 0;
21784dca4b63SNaphtali Sprei ro_cleanup:
21797267c094SAnthony Liguori     g_free(buf);
21804dca4b63SNaphtali Sprei 
21814dca4b63SNaphtali Sprei     if (ro) {
21820bce597dSJeff Cody         /* ignoring error return here */
21830bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
21844dca4b63SNaphtali Sprei     }
21854dca4b63SNaphtali Sprei 
21861d44952fSChristoph Hellwig     return ret;
218733e3963eSbellard }
218833e3963eSbellard 
2189e8877497SStefan Hajnoczi int bdrv_commit_all(void)
21906ab4b5abSMarkus Armbruster {
21916ab4b5abSMarkus Armbruster     BlockDriverState *bs;
21926ab4b5abSMarkus Armbruster 
2193dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2194272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2195e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2196e8877497SStefan Hajnoczi             if (ret < 0) {
2197e8877497SStefan Hajnoczi                 return ret;
21986ab4b5abSMarkus Armbruster             }
21996ab4b5abSMarkus Armbruster         }
2200272d2d8eSJeff Cody     }
2201e8877497SStefan Hajnoczi     return 0;
2202e8877497SStefan Hajnoczi }
22036ab4b5abSMarkus Armbruster 
2204dbffbdcfSStefan Hajnoczi /**
2205dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2206dbffbdcfSStefan Hajnoczi  *
2207dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2208dbffbdcfSStefan Hajnoczi  */
2209dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2210dbffbdcfSStefan Hajnoczi {
22112dbafdc0SKevin Wolf     if (req->serialising) {
22122dbafdc0SKevin Wolf         req->bs->serialising_in_flight--;
22132dbafdc0SKevin Wolf     }
22142dbafdc0SKevin Wolf 
2215dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2216f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2217dbffbdcfSStefan Hajnoczi }
2218dbffbdcfSStefan Hajnoczi 
2219dbffbdcfSStefan Hajnoczi /**
2220dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2221dbffbdcfSStefan Hajnoczi  */
2222dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2223dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2224793ed47aSKevin Wolf                                   int64_t offset,
2225793ed47aSKevin Wolf                                   unsigned int bytes, bool is_write)
2226dbffbdcfSStefan Hajnoczi {
2227dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2228dbffbdcfSStefan Hajnoczi         .bs = bs,
2229793ed47aSKevin Wolf         .offset         = offset,
2230793ed47aSKevin Wolf         .bytes          = bytes,
2231dbffbdcfSStefan Hajnoczi         .is_write       = is_write,
22325f8b6491SStefan Hajnoczi         .co             = qemu_coroutine_self(),
22332dbafdc0SKevin Wolf         .serialising    = false,
22347327145fSKevin Wolf         .overlap_offset = offset,
22357327145fSKevin Wolf         .overlap_bytes  = bytes,
2236dbffbdcfSStefan Hajnoczi     };
2237dbffbdcfSStefan Hajnoczi 
2238f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2239f4658285SStefan Hajnoczi 
2240dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2241dbffbdcfSStefan Hajnoczi }
2242dbffbdcfSStefan Hajnoczi 
22437327145fSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, size_t align)
22442dbafdc0SKevin Wolf {
22457327145fSKevin Wolf     int64_t overlap_offset = req->offset & ~(align - 1);
22467327145fSKevin Wolf     int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
22477327145fSKevin Wolf                       - overlap_offset;
22487327145fSKevin Wolf 
22492dbafdc0SKevin Wolf     if (!req->serialising) {
22502dbafdc0SKevin Wolf         req->bs->serialising_in_flight++;
22512dbafdc0SKevin Wolf         req->serialising = true;
22522dbafdc0SKevin Wolf     }
22537327145fSKevin Wolf 
22547327145fSKevin Wolf     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
22557327145fSKevin Wolf     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
22562dbafdc0SKevin Wolf }
22572dbafdc0SKevin Wolf 
2258d83947acSStefan Hajnoczi /**
2259d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2260d83947acSStefan Hajnoczi  */
2261343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2262d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2263d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2264d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2265d83947acSStefan Hajnoczi {
2266d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2267d83947acSStefan Hajnoczi 
2268d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2269d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2270d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2271d83947acSStefan Hajnoczi     } else {
2272d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2273d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2274d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2275d83947acSStefan Hajnoczi                                             nb_sectors, c);
2276d83947acSStefan Hajnoczi     }
2277d83947acSStefan Hajnoczi }
2278d83947acSStefan Hajnoczi 
22797327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs)
2280793ed47aSKevin Wolf {
2281793ed47aSKevin Wolf     BlockDriverInfo bdi;
22827327145fSKevin Wolf     int ret;
2283793ed47aSKevin Wolf 
22847327145fSKevin Wolf     ret = bdrv_get_info(bs, &bdi);
22857327145fSKevin Wolf     if (ret < 0 || bdi.cluster_size == 0) {
22867327145fSKevin Wolf         return bs->request_alignment;
2287793ed47aSKevin Wolf     } else {
22887327145fSKevin Wolf         return bdi.cluster_size;
2289793ed47aSKevin Wolf     }
2290793ed47aSKevin Wolf }
2291793ed47aSKevin Wolf 
2292f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2293793ed47aSKevin Wolf                                      int64_t offset, unsigned int bytes)
2294793ed47aSKevin Wolf {
2295d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
22967327145fSKevin Wolf     if (offset >= req->overlap_offset + req->overlap_bytes) {
2297d83947acSStefan Hajnoczi         return false;
2298d83947acSStefan Hajnoczi     }
2299d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
23007327145fSKevin Wolf     if (req->overlap_offset >= offset + bytes) {
2301d83947acSStefan Hajnoczi         return false;
2302d83947acSStefan Hajnoczi     }
2303d83947acSStefan Hajnoczi     return true;
2304f4658285SStefan Hajnoczi }
2305f4658285SStefan Hajnoczi 
230628de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
2307f4658285SStefan Hajnoczi {
23082dbafdc0SKevin Wolf     BlockDriverState *bs = self->bs;
2309f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2310f4658285SStefan Hajnoczi     bool retry;
231128de2dcdSKevin Wolf     bool waited = false;
2312f4658285SStefan Hajnoczi 
23132dbafdc0SKevin Wolf     if (!bs->serialising_in_flight) {
231428de2dcdSKevin Wolf         return false;
23152dbafdc0SKevin Wolf     }
23162dbafdc0SKevin Wolf 
2317f4658285SStefan Hajnoczi     do {
2318f4658285SStefan Hajnoczi         retry = false;
2319f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
23202dbafdc0SKevin Wolf             if (req == self || (!req->serialising && !self->serialising)) {
232165afd211SKevin Wolf                 continue;
232265afd211SKevin Wolf             }
23237327145fSKevin Wolf             if (tracked_request_overlaps(req, self->overlap_offset,
23247327145fSKevin Wolf                                          self->overlap_bytes))
23257327145fSKevin Wolf             {
23265f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
23275f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
23285f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
23295f8b6491SStefan Hajnoczi                  */
23305f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
23315f8b6491SStefan Hajnoczi 
23326460440fSKevin Wolf                 /* If the request is already (indirectly) waiting for us, or
23336460440fSKevin Wolf                  * will wait for us as soon as it wakes up, then just go on
23346460440fSKevin Wolf                  * (instead of producing a deadlock in the former case). */
23356460440fSKevin Wolf                 if (!req->waiting_for) {
23366460440fSKevin Wolf                     self->waiting_for = req;
2337f4658285SStefan Hajnoczi                     qemu_co_queue_wait(&req->wait_queue);
23386460440fSKevin Wolf                     self->waiting_for = NULL;
2339f4658285SStefan Hajnoczi                     retry = true;
234028de2dcdSKevin Wolf                     waited = true;
2341f4658285SStefan Hajnoczi                     break;
2342f4658285SStefan Hajnoczi                 }
2343f4658285SStefan Hajnoczi             }
23446460440fSKevin Wolf         }
2345f4658285SStefan Hajnoczi     } while (retry);
234628de2dcdSKevin Wolf 
234728de2dcdSKevin Wolf     return waited;
2348f4658285SStefan Hajnoczi }
2349f4658285SStefan Hajnoczi 
2350756e6736SKevin Wolf /*
2351756e6736SKevin Wolf  * Return values:
2352756e6736SKevin Wolf  * 0        - success
2353756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2354756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2355756e6736SKevin Wolf  *            image file header
2356756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2357756e6736SKevin Wolf  */
2358756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2359756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2360756e6736SKevin Wolf {
2361756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2362469ef350SPaolo Bonzini     int ret;
2363756e6736SKevin Wolf 
23645f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23655f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23665f377794SPaolo Bonzini         return -EINVAL;
23675f377794SPaolo Bonzini     }
23685f377794SPaolo Bonzini 
2369756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2370469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2371756e6736SKevin Wolf     } else {
2372469ef350SPaolo Bonzini         ret = -ENOTSUP;
2373756e6736SKevin Wolf     }
2374469ef350SPaolo Bonzini 
2375469ef350SPaolo Bonzini     if (ret == 0) {
2376469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2377469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2378469ef350SPaolo Bonzini     }
2379469ef350SPaolo Bonzini     return ret;
2380756e6736SKevin Wolf }
2381756e6736SKevin Wolf 
23826ebdcee2SJeff Cody /*
23836ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23846ebdcee2SJeff Cody  *
23856ebdcee2SJeff Cody  * active is the current topmost image.
23866ebdcee2SJeff Cody  *
23876ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
23886ebdcee2SJeff Cody  * or if active == bs.
23896ebdcee2SJeff Cody  */
23906ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
23916ebdcee2SJeff Cody                                     BlockDriverState *bs)
23926ebdcee2SJeff Cody {
23936ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
23946ebdcee2SJeff Cody     BlockDriverState *intermediate;
23956ebdcee2SJeff Cody 
23966ebdcee2SJeff Cody     assert(active != NULL);
23976ebdcee2SJeff Cody     assert(bs != NULL);
23986ebdcee2SJeff Cody 
23996ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
24006ebdcee2SJeff Cody      */
24016ebdcee2SJeff Cody     if (active == bs) {
24026ebdcee2SJeff Cody         return NULL;
24036ebdcee2SJeff Cody     }
24046ebdcee2SJeff Cody 
24056ebdcee2SJeff Cody     intermediate = active;
24066ebdcee2SJeff Cody     while (intermediate->backing_hd) {
24076ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
24086ebdcee2SJeff Cody             overlay = intermediate;
24096ebdcee2SJeff Cody             break;
24106ebdcee2SJeff Cody         }
24116ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
24126ebdcee2SJeff Cody     }
24136ebdcee2SJeff Cody 
24146ebdcee2SJeff Cody     return overlay;
24156ebdcee2SJeff Cody }
24166ebdcee2SJeff Cody 
24176ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
24186ebdcee2SJeff Cody     BlockDriverState *bs;
24196ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
24206ebdcee2SJeff Cody } BlkIntermediateStates;
24216ebdcee2SJeff Cody 
24226ebdcee2SJeff Cody 
24236ebdcee2SJeff Cody /*
24246ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
24256ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
24266ebdcee2SJeff Cody  *
24276ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
24286ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
24296ebdcee2SJeff Cody  *
24306ebdcee2SJeff Cody  * E.g., this will convert the following chain:
24316ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
24326ebdcee2SJeff Cody  *
24336ebdcee2SJeff Cody  * to
24346ebdcee2SJeff Cody  *
24356ebdcee2SJeff Cody  * bottom <- base <- active
24366ebdcee2SJeff Cody  *
24376ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
24386ebdcee2SJeff Cody  *
24396ebdcee2SJeff Cody  * base <- intermediate <- top <- active
24406ebdcee2SJeff Cody  *
24416ebdcee2SJeff Cody  * to
24426ebdcee2SJeff Cody  *
24436ebdcee2SJeff Cody  * base <- active
24446ebdcee2SJeff Cody  *
24456ebdcee2SJeff Cody  * Error conditions:
24466ebdcee2SJeff Cody  *  if active == top, that is considered an error
24476ebdcee2SJeff Cody  *
24486ebdcee2SJeff Cody  */
24496ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
24506ebdcee2SJeff Cody                            BlockDriverState *base)
24516ebdcee2SJeff Cody {
24526ebdcee2SJeff Cody     BlockDriverState *intermediate;
24536ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
24546ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
24556ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
24566ebdcee2SJeff Cody     int ret = -EIO;
24576ebdcee2SJeff Cody 
24586ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
24596ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
24606ebdcee2SJeff Cody 
24616ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
24626ebdcee2SJeff Cody         goto exit;
24636ebdcee2SJeff Cody     }
24646ebdcee2SJeff Cody 
24656ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
24666ebdcee2SJeff Cody 
24676ebdcee2SJeff Cody     if (new_top_bs == NULL) {
24686ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
24696ebdcee2SJeff Cody         goto exit;
24706ebdcee2SJeff Cody     }
24716ebdcee2SJeff Cody 
24726ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
24736ebdcee2SJeff Cody      * to do, no intermediate images */
24746ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
24756ebdcee2SJeff Cody         ret = 0;
24766ebdcee2SJeff Cody         goto exit;
24776ebdcee2SJeff Cody     }
24786ebdcee2SJeff Cody 
24796ebdcee2SJeff Cody     intermediate = top;
24806ebdcee2SJeff Cody 
24816ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
24826ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
24836ebdcee2SJeff Cody      */
24846ebdcee2SJeff Cody     while (intermediate) {
24856ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
24866ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
24876ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
24886ebdcee2SJeff Cody 
24896ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
24906ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
24916ebdcee2SJeff Cody             break;
24926ebdcee2SJeff Cody         }
24936ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
24946ebdcee2SJeff Cody     }
24956ebdcee2SJeff Cody     if (base_bs == NULL) {
24966ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
24976ebdcee2SJeff Cody          * unravel everything, and exit with error */
24986ebdcee2SJeff Cody         goto exit;
24996ebdcee2SJeff Cody     }
25006ebdcee2SJeff Cody 
25016ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
25026ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
25036ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
25046ebdcee2SJeff Cody     if (ret) {
25056ebdcee2SJeff Cody         goto exit;
25066ebdcee2SJeff Cody     }
25076ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
25086ebdcee2SJeff Cody 
2509355ef4acSKevin Wolf     bdrv_refresh_limits(new_top_bs);
25106ebdcee2SJeff Cody 
25116ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25126ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
25136ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
25144f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
25156ebdcee2SJeff Cody     }
25166ebdcee2SJeff Cody     ret = 0;
25176ebdcee2SJeff Cody 
25186ebdcee2SJeff Cody exit:
25196ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
25206ebdcee2SJeff Cody         g_free(intermediate_state);
25216ebdcee2SJeff Cody     }
25226ebdcee2SJeff Cody     return ret;
25236ebdcee2SJeff Cody }
25246ebdcee2SJeff Cody 
25256ebdcee2SJeff Cody 
252671d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
252771d0770cSaliguori                                    size_t size)
252871d0770cSaliguori {
252971d0770cSaliguori     int64_t len;
253071d0770cSaliguori 
253171d0770cSaliguori     if (!bdrv_is_inserted(bs))
253271d0770cSaliguori         return -ENOMEDIUM;
253371d0770cSaliguori 
253471d0770cSaliguori     if (bs->growable)
253571d0770cSaliguori         return 0;
253671d0770cSaliguori 
253771d0770cSaliguori     len = bdrv_getlength(bs);
253871d0770cSaliguori 
2539fbb7b4e0SKevin Wolf     if (offset < 0)
2540fbb7b4e0SKevin Wolf         return -EIO;
2541fbb7b4e0SKevin Wolf 
2542fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
254371d0770cSaliguori         return -EIO;
254471d0770cSaliguori 
254571d0770cSaliguori     return 0;
254671d0770cSaliguori }
254771d0770cSaliguori 
254871d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
254971d0770cSaliguori                               int nb_sectors)
255071d0770cSaliguori {
2551eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2552eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
255371d0770cSaliguori }
255471d0770cSaliguori 
25551c9805a3SStefan Hajnoczi typedef struct RwCo {
25561c9805a3SStefan Hajnoczi     BlockDriverState *bs;
2557*775aa8b6SKevin Wolf     int64_t offset;
25581c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
25591c9805a3SStefan Hajnoczi     bool is_write;
25601c9805a3SStefan Hajnoczi     int ret;
25614105eaaaSPeter Lieven     BdrvRequestFlags flags;
25621c9805a3SStefan Hajnoczi } RwCo;
25631c9805a3SStefan Hajnoczi 
25641c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2565fc01f7e7Sbellard {
25661c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2567fc01f7e7Sbellard 
25681c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
2569*775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2570*775aa8b6SKevin Wolf                                       rwco->qiov->size, rwco->qiov,
25714105eaaaSPeter Lieven                                       rwco->flags);
25721c9805a3SStefan Hajnoczi     } else {
2573*775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2574*775aa8b6SKevin Wolf                                        rwco->qiov->size, rwco->qiov,
25754105eaaaSPeter Lieven                                        rwco->flags);
25761c9805a3SStefan Hajnoczi     }
25771c9805a3SStefan Hajnoczi }
2578e7a8a783SKevin Wolf 
25791c9805a3SStefan Hajnoczi /*
25808d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
25811c9805a3SStefan Hajnoczi  */
2582*775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
25834105eaaaSPeter Lieven                         QEMUIOVector *qiov, bool is_write,
25844105eaaaSPeter Lieven                         BdrvRequestFlags flags)
25851c9805a3SStefan Hajnoczi {
25861c9805a3SStefan Hajnoczi     Coroutine *co;
25871c9805a3SStefan Hajnoczi     RwCo rwco = {
25881c9805a3SStefan Hajnoczi         .bs = bs,
2589*775aa8b6SKevin Wolf         .offset = offset,
25908d3b1a2dSKevin Wolf         .qiov = qiov,
25911c9805a3SStefan Hajnoczi         .is_write = is_write,
25921c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
25934105eaaaSPeter Lieven         .flags = flags,
25941c9805a3SStefan Hajnoczi     };
25951c9805a3SStefan Hajnoczi 
2596498e386cSZhi Yong Wu     /**
2597498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2598498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2599498e386cSZhi Yong Wu      * if it has been enabled.
2600498e386cSZhi Yong Wu      */
2601498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2602498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2603498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2604498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2605498e386cSZhi Yong Wu     }
2606498e386cSZhi Yong Wu 
26071c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
26081c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
26091c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
26101c9805a3SStefan Hajnoczi     } else {
26111c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
26121c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
26131c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
26141c9805a3SStefan Hajnoczi             qemu_aio_wait();
26151c9805a3SStefan Hajnoczi         }
26161c9805a3SStefan Hajnoczi     }
26171c9805a3SStefan Hajnoczi     return rwco.ret;
2618e7a8a783SKevin Wolf }
2619e7a8a783SKevin Wolf 
26208d3b1a2dSKevin Wolf /*
26218d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
26228d3b1a2dSKevin Wolf  */
26238d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
26244105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
26258d3b1a2dSKevin Wolf {
26268d3b1a2dSKevin Wolf     QEMUIOVector qiov;
26278d3b1a2dSKevin Wolf     struct iovec iov = {
26288d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
26298d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
26308d3b1a2dSKevin Wolf     };
26318d3b1a2dSKevin Wolf 
26328d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2633*775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2634*775aa8b6SKevin Wolf                         &qiov, is_write, flags);
26358d3b1a2dSKevin Wolf }
26368d3b1a2dSKevin Wolf 
26371c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
26381c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
26391c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
26401c9805a3SStefan Hajnoczi {
26414105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
264283f64091Sbellard }
2643fc01f7e7Sbellard 
264407d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
264507d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
264607d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
264707d27a44SMarkus Armbruster {
264807d27a44SMarkus Armbruster     bool enabled;
264907d27a44SMarkus Armbruster     int ret;
265007d27a44SMarkus Armbruster 
265107d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
265207d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
26534e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
265407d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
265507d27a44SMarkus Armbruster     return ret;
265607d27a44SMarkus Armbruster }
265707d27a44SMarkus Armbruster 
265819cb3738Sbellard /* Return < 0 if error. Important errors are:
265919cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
266019cb3738Sbellard   -ENOMEDIUM   No media inserted.
266119cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
266219cb3738Sbellard   -EACCES      Trying to write a read-only device
266319cb3738Sbellard */
2664fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2665fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2666fc01f7e7Sbellard {
26674105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
266883f64091Sbellard }
266983f64091Sbellard 
26708d3b1a2dSKevin Wolf int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
26718d3b1a2dSKevin Wolf {
2672*775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS, qiov, true, 0);
26734105eaaaSPeter Lieven }
26744105eaaaSPeter Lieven 
2675aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2676aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
26774105eaaaSPeter Lieven {
26784105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2679aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
26808d3b1a2dSKevin Wolf }
26818d3b1a2dSKevin Wolf 
2682d75cbb5eSPeter Lieven /*
2683d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2684d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2685d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2686d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2687d75cbb5eSPeter Lieven  *
2688d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2689d75cbb5eSPeter Lieven  */
2690d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2691d75cbb5eSPeter Lieven {
2692d75cbb5eSPeter Lieven     int64_t target_size = bdrv_getlength(bs) / BDRV_SECTOR_SIZE;
2693d75cbb5eSPeter Lieven     int64_t ret, nb_sectors, sector_num = 0;
2694d75cbb5eSPeter Lieven     int n;
2695d75cbb5eSPeter Lieven 
2696d75cbb5eSPeter Lieven     for (;;) {
2697d75cbb5eSPeter Lieven         nb_sectors = target_size - sector_num;
2698d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2699d75cbb5eSPeter Lieven             return 0;
2700d75cbb5eSPeter Lieven         }
2701d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2702d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2703d75cbb5eSPeter Lieven         }
2704d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
27053d94ce60SPeter Lieven         if (ret < 0) {
27063d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
27073d94ce60SPeter Lieven                          sector_num, strerror(-ret));
27083d94ce60SPeter Lieven             return ret;
27093d94ce60SPeter Lieven         }
2710d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2711d75cbb5eSPeter Lieven             sector_num += n;
2712d75cbb5eSPeter Lieven             continue;
2713d75cbb5eSPeter Lieven         }
2714d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2715d75cbb5eSPeter Lieven         if (ret < 0) {
2716d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2717d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2718d75cbb5eSPeter Lieven             return ret;
2719d75cbb5eSPeter Lieven         }
2720d75cbb5eSPeter Lieven         sector_num += n;
2721d75cbb5eSPeter Lieven     }
2722d75cbb5eSPeter Lieven }
2723d75cbb5eSPeter Lieven 
2724eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2725eda578e5Saliguori                void *buf, int count1)
272683f64091Sbellard {
27276ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
272883f64091Sbellard     int len, nb_sectors, count;
272983f64091Sbellard     int64_t sector_num;
27309a8c4cceSKevin Wolf     int ret;
273183f64091Sbellard 
273283f64091Sbellard     count = count1;
273383f64091Sbellard     /* first read to align to sector start */
27346ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
273583f64091Sbellard     if (len > count)
273683f64091Sbellard         len = count;
27376ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
273883f64091Sbellard     if (len > 0) {
27399a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
27409a8c4cceSKevin Wolf             return ret;
27416ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
274283f64091Sbellard         count -= len;
274383f64091Sbellard         if (count == 0)
274483f64091Sbellard             return count1;
274583f64091Sbellard         sector_num++;
274683f64091Sbellard         buf += len;
274783f64091Sbellard     }
274883f64091Sbellard 
274983f64091Sbellard     /* read the sectors "in place" */
27506ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
275183f64091Sbellard     if (nb_sectors > 0) {
27529a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
27539a8c4cceSKevin Wolf             return ret;
275483f64091Sbellard         sector_num += nb_sectors;
27556ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
275683f64091Sbellard         buf += len;
275783f64091Sbellard         count -= len;
275883f64091Sbellard     }
275983f64091Sbellard 
276083f64091Sbellard     /* add data from the last sector */
276183f64091Sbellard     if (count > 0) {
27629a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
27639a8c4cceSKevin Wolf             return ret;
276483f64091Sbellard         memcpy(buf, tmp_buf, count);
276583f64091Sbellard     }
276683f64091Sbellard     return count1;
276783f64091Sbellard }
276883f64091Sbellard 
27698d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
277083f64091Sbellard {
27716ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
277283f64091Sbellard     int len, nb_sectors, count;
277383f64091Sbellard     int64_t sector_num;
27749a8c4cceSKevin Wolf     int ret;
277583f64091Sbellard 
27768d3b1a2dSKevin Wolf     count = qiov->size;
27778d3b1a2dSKevin Wolf 
277883f64091Sbellard     /* first write to align to sector start */
27796ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
278083f64091Sbellard     if (len > count)
278183f64091Sbellard         len = count;
27826ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
278383f64091Sbellard     if (len > 0) {
27849a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
27859a8c4cceSKevin Wolf             return ret;
27868d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
27878d3b1a2dSKevin Wolf                           len);
27889a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
27899a8c4cceSKevin Wolf             return ret;
279083f64091Sbellard         count -= len;
279183f64091Sbellard         if (count == 0)
27928d3b1a2dSKevin Wolf             return qiov->size;
279383f64091Sbellard         sector_num++;
279483f64091Sbellard     }
279583f64091Sbellard 
279683f64091Sbellard     /* write the sectors "in place" */
27976ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
279883f64091Sbellard     if (nb_sectors > 0) {
27998d3b1a2dSKevin Wolf         QEMUIOVector qiov_inplace;
28008d3b1a2dSKevin Wolf 
28018d3b1a2dSKevin Wolf         qemu_iovec_init(&qiov_inplace, qiov->niov);
28028d3b1a2dSKevin Wolf         qemu_iovec_concat(&qiov_inplace, qiov, len,
28038d3b1a2dSKevin Wolf                           nb_sectors << BDRV_SECTOR_BITS);
28048d3b1a2dSKevin Wolf         ret = bdrv_writev(bs, sector_num, &qiov_inplace);
28058d3b1a2dSKevin Wolf         qemu_iovec_destroy(&qiov_inplace);
28068d3b1a2dSKevin Wolf         if (ret < 0) {
28079a8c4cceSKevin Wolf             return ret;
28088d3b1a2dSKevin Wolf         }
28098d3b1a2dSKevin Wolf 
281083f64091Sbellard         sector_num += nb_sectors;
28116ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
281283f64091Sbellard         count -= len;
281383f64091Sbellard     }
281483f64091Sbellard 
281583f64091Sbellard     /* add data from the last sector */
281683f64091Sbellard     if (count > 0) {
28179a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
28189a8c4cceSKevin Wolf             return ret;
28198d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
28209a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
28219a8c4cceSKevin Wolf             return ret;
282283f64091Sbellard     }
28238d3b1a2dSKevin Wolf     return qiov->size;
28248d3b1a2dSKevin Wolf }
28258d3b1a2dSKevin Wolf 
28268d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
28278d3b1a2dSKevin Wolf                 const void *buf, int count1)
28288d3b1a2dSKevin Wolf {
28298d3b1a2dSKevin Wolf     QEMUIOVector qiov;
28308d3b1a2dSKevin Wolf     struct iovec iov = {
28318d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
28328d3b1a2dSKevin Wolf         .iov_len    = count1,
28338d3b1a2dSKevin Wolf     };
28348d3b1a2dSKevin Wolf 
28358d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
28368d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
283783f64091Sbellard }
283883f64091Sbellard 
2839f08145feSKevin Wolf /*
2840f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2841f08145feSKevin Wolf  * request (acts as a barrier)
2842f08145feSKevin Wolf  *
2843f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2844f08145feSKevin Wolf  */
2845f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2846f08145feSKevin Wolf     const void *buf, int count)
2847f08145feSKevin Wolf {
2848f08145feSKevin Wolf     int ret;
2849f08145feSKevin Wolf 
2850f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2851f08145feSKevin Wolf     if (ret < 0) {
2852f08145feSKevin Wolf         return ret;
2853f08145feSKevin Wolf     }
2854f08145feSKevin Wolf 
2855f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2856f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2857f08145feSKevin Wolf         bdrv_flush(bs);
2858f08145feSKevin Wolf     }
2859f08145feSKevin Wolf 
2860f08145feSKevin Wolf     return 0;
2861f08145feSKevin Wolf }
2862f08145feSKevin Wolf 
2863470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2864ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2865ab185921SStefan Hajnoczi {
2866ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2867ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2868ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2869ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2870ab185921SStefan Hajnoczi      */
2871ab185921SStefan Hajnoczi     void *bounce_buffer;
2872ab185921SStefan Hajnoczi 
287379c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2874ab185921SStefan Hajnoczi     struct iovec iov;
2875ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2876ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2877ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2878ab185921SStefan Hajnoczi     size_t skip_bytes;
2879ab185921SStefan Hajnoczi     int ret;
2880ab185921SStefan Hajnoczi 
2881ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2882ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2883ab185921SStefan Hajnoczi      */
2884343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2885ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2886ab185921SStefan Hajnoczi 
2887470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2888ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2889ab185921SStefan Hajnoczi 
2890ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2891ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2892ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2893ab185921SStefan Hajnoczi 
289479c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2895ab185921SStefan Hajnoczi                              &bounce_qiov);
2896ab185921SStefan Hajnoczi     if (ret < 0) {
2897ab185921SStefan Hajnoczi         goto err;
2898ab185921SStefan Hajnoczi     }
2899ab185921SStefan Hajnoczi 
290079c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
290179c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2902621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2903aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
290479c053bdSStefan Hajnoczi     } else {
2905f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2906f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2907f05fa4adSPaolo Bonzini          */
290879c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2909ab185921SStefan Hajnoczi                                   &bounce_qiov);
291079c053bdSStefan Hajnoczi     }
291179c053bdSStefan Hajnoczi 
2912ab185921SStefan Hajnoczi     if (ret < 0) {
2913ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2914ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2915ab185921SStefan Hajnoczi          * Simply report it in all cases.
2916ab185921SStefan Hajnoczi          */
2917ab185921SStefan Hajnoczi         goto err;
2918ab185921SStefan Hajnoczi     }
2919ab185921SStefan Hajnoczi 
2920ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
292103396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2922ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2923ab185921SStefan Hajnoczi 
2924ab185921SStefan Hajnoczi err:
2925ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2926ab185921SStefan Hajnoczi     return ret;
2927ab185921SStefan Hajnoczi }
2928ab185921SStefan Hajnoczi 
2929c5fbe571SStefan Hajnoczi /*
2930d0c7f642SKevin Wolf  * Forwards an already correctly aligned request to the BlockDriver. This
2931d0c7f642SKevin Wolf  * handles copy on read and zeroing after EOF; any other features must be
2932d0c7f642SKevin Wolf  * implemented by the caller.
2933c5fbe571SStefan Hajnoczi  */
2934d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
293565afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
2936ec746e10SKevin Wolf     int64_t align, QEMUIOVector *qiov, int flags)
2937da1fa91dSKevin Wolf {
2938da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2939dbffbdcfSStefan Hajnoczi     int ret;
2940da1fa91dSKevin Wolf 
2941d0c7f642SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
2942d0c7f642SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
2943da1fa91dSKevin Wolf 
2944d0c7f642SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2945d0c7f642SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
2946d0c7f642SKevin Wolf 
2947d0c7f642SKevin Wolf     /* Handle Copy on Read and associated serialisation */
2948470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
29497327145fSKevin Wolf         /* If we touch the same cluster it counts as an overlap.  This
29507327145fSKevin Wolf          * guarantees that allocating writes will be serialized and not race
29517327145fSKevin Wolf          * with each other for the same cluster.  For example, in copy-on-read
29527327145fSKevin Wolf          * it ensures that the CoR read and write operations are atomic and
29537327145fSKevin Wolf          * guest writes cannot interleave between them. */
29547327145fSKevin Wolf         mark_request_serialising(req, bdrv_get_cluster_size(bs));
2955470c0504SStefan Hajnoczi     }
2956470c0504SStefan Hajnoczi 
29572dbafdc0SKevin Wolf     wait_serialising_requests(req);
2958f4658285SStefan Hajnoczi 
2959470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2960ab185921SStefan Hajnoczi         int pnum;
2961ab185921SStefan Hajnoczi 
2962bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2963ab185921SStefan Hajnoczi         if (ret < 0) {
2964ab185921SStefan Hajnoczi             goto out;
2965ab185921SStefan Hajnoczi         }
2966ab185921SStefan Hajnoczi 
2967ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2968470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2969ab185921SStefan Hajnoczi             goto out;
2970ab185921SStefan Hajnoczi         }
2971ab185921SStefan Hajnoczi     }
2972ab185921SStefan Hajnoczi 
2973d0c7f642SKevin Wolf     /* Forward the request to the BlockDriver */
2974893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2975dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2976893a8f62SMORITA Kazutaka     } else {
2977893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2978893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2979893a8f62SMORITA Kazutaka 
2980893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2981893a8f62SMORITA Kazutaka         if (len < 0) {
2982893a8f62SMORITA Kazutaka             ret = len;
2983893a8f62SMORITA Kazutaka             goto out;
2984893a8f62SMORITA Kazutaka         }
2985893a8f62SMORITA Kazutaka 
2986d055a1feSFam Zheng         total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
2987ec746e10SKevin Wolf         max_nb_sectors = MAX(0, ROUND_UP(total_sectors - sector_num,
2988ec746e10SKevin Wolf                                          align >> BDRV_SECTOR_BITS));
2989893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
2990893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
2991893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
2992893a8f62SMORITA Kazutaka         } else {
2993893a8f62SMORITA Kazutaka             ret = 0;
2994893a8f62SMORITA Kazutaka         }
2995893a8f62SMORITA Kazutaka 
2996893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
2997893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2998893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
2999893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
3000893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
3001893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
3002893a8f62SMORITA Kazutaka         }
3003893a8f62SMORITA Kazutaka     }
3004ab185921SStefan Hajnoczi 
3005ab185921SStefan Hajnoczi out:
3006dbffbdcfSStefan Hajnoczi     return ret;
3007da1fa91dSKevin Wolf }
3008da1fa91dSKevin Wolf 
3009d0c7f642SKevin Wolf /*
3010d0c7f642SKevin Wolf  * Handle a read request in coroutine context
3011d0c7f642SKevin Wolf  */
30121b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
30131b0288aeSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3014d0c7f642SKevin Wolf     BdrvRequestFlags flags)
3015d0c7f642SKevin Wolf {
3016d0c7f642SKevin Wolf     BlockDriver *drv = bs->drv;
301765afd211SKevin Wolf     BdrvTrackedRequest req;
301865afd211SKevin Wolf 
30191b0288aeSKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
30201b0288aeSKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
30211b0288aeSKevin Wolf     uint8_t *head_buf = NULL;
30221b0288aeSKevin Wolf     uint8_t *tail_buf = NULL;
30231b0288aeSKevin Wolf     QEMUIOVector local_qiov;
30241b0288aeSKevin Wolf     bool use_local_qiov = false;
3025d0c7f642SKevin Wolf     int ret;
3026d0c7f642SKevin Wolf 
3027d0c7f642SKevin Wolf     if (!drv) {
3028d0c7f642SKevin Wolf         return -ENOMEDIUM;
3029d0c7f642SKevin Wolf     }
30301b0288aeSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3031d0c7f642SKevin Wolf         return -EIO;
3032d0c7f642SKevin Wolf     }
3033d0c7f642SKevin Wolf 
3034d0c7f642SKevin Wolf     if (bs->copy_on_read) {
3035d0c7f642SKevin Wolf         flags |= BDRV_REQ_COPY_ON_READ;
3036d0c7f642SKevin Wolf     }
3037d0c7f642SKevin Wolf 
3038d0c7f642SKevin Wolf     /* throttling disk I/O */
3039d0c7f642SKevin Wolf     if (bs->io_limits_enabled) {
30401b0288aeSKevin Wolf         /* TODO Switch to byte granularity */
30411b0288aeSKevin Wolf         bdrv_io_limits_intercept(bs, bytes >> BDRV_SECTOR_BITS, false);
3042d0c7f642SKevin Wolf     }
3043d0c7f642SKevin Wolf 
30441b0288aeSKevin Wolf     /* Align read if necessary by padding qiov */
30451b0288aeSKevin Wolf     if (offset & (align - 1)) {
30461b0288aeSKevin Wolf         head_buf = qemu_blockalign(bs, align);
30471b0288aeSKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
30481b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
30491b0288aeSKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30501b0288aeSKevin Wolf         use_local_qiov = true;
30511b0288aeSKevin Wolf 
30521b0288aeSKevin Wolf         bytes += offset & (align - 1);
30531b0288aeSKevin Wolf         offset = offset & ~(align - 1);
30541b0288aeSKevin Wolf     }
30551b0288aeSKevin Wolf 
30561b0288aeSKevin Wolf     if ((offset + bytes) & (align - 1)) {
30571b0288aeSKevin Wolf         if (!use_local_qiov) {
30581b0288aeSKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
30591b0288aeSKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
30601b0288aeSKevin Wolf             use_local_qiov = true;
30611b0288aeSKevin Wolf         }
30621b0288aeSKevin Wolf         tail_buf = qemu_blockalign(bs, align);
30631b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf,
30641b0288aeSKevin Wolf                        align - ((offset + bytes) & (align - 1)));
30651b0288aeSKevin Wolf 
30661b0288aeSKevin Wolf         bytes = ROUND_UP(bytes, align);
30671b0288aeSKevin Wolf     }
30681b0288aeSKevin Wolf 
306965afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, false);
3070ec746e10SKevin Wolf     ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
30711b0288aeSKevin Wolf                               use_local_qiov ? &local_qiov : qiov,
30721b0288aeSKevin Wolf                               flags);
307365afd211SKevin Wolf     tracked_request_end(&req);
30741b0288aeSKevin Wolf 
30751b0288aeSKevin Wolf     if (use_local_qiov) {
30761b0288aeSKevin Wolf         qemu_iovec_destroy(&local_qiov);
30771b0288aeSKevin Wolf         qemu_vfree(head_buf);
30781b0288aeSKevin Wolf         qemu_vfree(tail_buf);
30791b0288aeSKevin Wolf     }
30801b0288aeSKevin Wolf 
3081d0c7f642SKevin Wolf     return ret;
3082d0c7f642SKevin Wolf }
3083d0c7f642SKevin Wolf 
30841b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
30851b0288aeSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
30861b0288aeSKevin Wolf     BdrvRequestFlags flags)
30871b0288aeSKevin Wolf {
30881b0288aeSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
30891b0288aeSKevin Wolf         return -EINVAL;
30901b0288aeSKevin Wolf     }
30911b0288aeSKevin Wolf 
30921b0288aeSKevin Wolf     return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
30931b0288aeSKevin Wolf                              nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
30941b0288aeSKevin Wolf }
30951b0288aeSKevin Wolf 
3096c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
3097da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
3098da1fa91dSKevin Wolf {
3099c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
3100da1fa91dSKevin Wolf 
3101470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3102470c0504SStefan Hajnoczi }
3103470c0504SStefan Hajnoczi 
3104470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3105470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3106470c0504SStefan Hajnoczi {
3107470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3108470c0504SStefan Hajnoczi 
3109470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3110470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
3111c5fbe571SStefan Hajnoczi }
3112c5fbe571SStefan Hajnoczi 
3113c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
3114c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
3115c31cb707SPeter Lieven  */
3116c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
3117c31cb707SPeter Lieven 
3118f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
3119aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
3120f08f2ddaSStefan Hajnoczi {
3121f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3122f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3123c31cb707SPeter Lieven     struct iovec iov = {0};
3124c31cb707SPeter Lieven     int ret = 0;
3125f08f2ddaSStefan Hajnoczi 
3126c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3127c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3128621f0589SKevin Wolf 
3129c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3130c31cb707SPeter Lieven         int num = nb_sectors;
3131c31cb707SPeter Lieven 
3132b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3133b8d71c09SPaolo Bonzini          * to be aligned.
3134b8d71c09SPaolo Bonzini          */
3135b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3136b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3137b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3138b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3139c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3140c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3141b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3142b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3143b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3144b8d71c09SPaolo Bonzini                  */
3145b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3146b8d71c09SPaolo Bonzini             }
3147c31cb707SPeter Lieven         }
3148c31cb707SPeter Lieven 
3149c31cb707SPeter Lieven         /* limit request size */
3150c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3151c31cb707SPeter Lieven             num = max_write_zeroes;
3152c31cb707SPeter Lieven         }
3153c31cb707SPeter Lieven 
3154c31cb707SPeter Lieven         ret = -ENOTSUP;
3155f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3156f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3157c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3158f08f2ddaSStefan Hajnoczi         }
3159f08f2ddaSStefan Hajnoczi 
3160c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3161f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3162c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3163c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3164b8d71c09SPaolo Bonzini                 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
3165b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3166c31cb707SPeter Lieven             }
3167f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3168f08f2ddaSStefan Hajnoczi 
3169c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3170b8d71c09SPaolo Bonzini 
3171b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3172b8d71c09SPaolo Bonzini              * all future requests.
3173b8d71c09SPaolo Bonzini              */
3174b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3175b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3176b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3177b8d71c09SPaolo Bonzini             }
3178c31cb707SPeter Lieven         }
3179c31cb707SPeter Lieven 
3180c31cb707SPeter Lieven         sector_num += num;
3181c31cb707SPeter Lieven         nb_sectors -= num;
3182c31cb707SPeter Lieven     }
3183f08f2ddaSStefan Hajnoczi 
3184f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3185f08f2ddaSStefan Hajnoczi     return ret;
3186f08f2ddaSStefan Hajnoczi }
3187f08f2ddaSStefan Hajnoczi 
3188c5fbe571SStefan Hajnoczi /*
3189b404f720SKevin Wolf  * Forwards an already correctly aligned write request to the BlockDriver.
3190c5fbe571SStefan Hajnoczi  */
3191b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
319265afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
319365afd211SKevin Wolf     QEMUIOVector *qiov, int flags)
3194c5fbe571SStefan Hajnoczi {
3195c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
319628de2dcdSKevin Wolf     bool waited;
31976b7cb247SStefan Hajnoczi     int ret;
3198da1fa91dSKevin Wolf 
3199b404f720SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3200b404f720SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3201da1fa91dSKevin Wolf 
3202b404f720SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3203b404f720SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3204cc0681c4SBenoît Canet 
320528de2dcdSKevin Wolf     waited = wait_serialising_requests(req);
320628de2dcdSKevin Wolf     assert(!waited || !req->serialising);
3207244eadefSKevin Wolf 
320865afd211SKevin Wolf     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
3209d616b224SStefan Hajnoczi 
3210d616b224SStefan Hajnoczi     if (ret < 0) {
3211d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3212d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
3213aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3214f08f2ddaSStefan Hajnoczi     } else {
32156b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3216f08f2ddaSStefan Hajnoczi     }
32176b7cb247SStefan Hajnoczi 
3218f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3219f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3220f05fa4adSPaolo Bonzini     }
3221f05fa4adSPaolo Bonzini 
32221755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3223da1fa91dSKevin Wolf 
3224da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
3225da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
3226da1fa91dSKevin Wolf     }
3227df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3228df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3229df2a6f29SPaolo Bonzini     }
3230da1fa91dSKevin Wolf 
32316b7cb247SStefan Hajnoczi     return ret;
3232da1fa91dSKevin Wolf }
3233da1fa91dSKevin Wolf 
3234b404f720SKevin Wolf /*
3235b404f720SKevin Wolf  * Handle a write request in coroutine context
3236b404f720SKevin Wolf  */
32376601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
32386601553eSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3239b404f720SKevin Wolf     BdrvRequestFlags flags)
3240b404f720SKevin Wolf {
324165afd211SKevin Wolf     BdrvTrackedRequest req;
32423b8242e0SKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
32433b8242e0SKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
32443b8242e0SKevin Wolf     uint8_t *head_buf = NULL;
32453b8242e0SKevin Wolf     uint8_t *tail_buf = NULL;
32463b8242e0SKevin Wolf     QEMUIOVector local_qiov;
32473b8242e0SKevin Wolf     bool use_local_qiov = false;
3248b404f720SKevin Wolf     int ret;
3249b404f720SKevin Wolf 
3250b404f720SKevin Wolf     if (!bs->drv) {
3251b404f720SKevin Wolf         return -ENOMEDIUM;
3252b404f720SKevin Wolf     }
3253b404f720SKevin Wolf     if (bs->read_only) {
3254b404f720SKevin Wolf         return -EACCES;
3255b404f720SKevin Wolf     }
32566601553eSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3257b404f720SKevin Wolf         return -EIO;
3258b404f720SKevin Wolf     }
3259b404f720SKevin Wolf 
3260b404f720SKevin Wolf     /* throttling disk I/O */
3261b404f720SKevin Wolf     if (bs->io_limits_enabled) {
32626601553eSKevin Wolf         /* TODO Switch to byte granularity */
32636601553eSKevin Wolf         bdrv_io_limits_intercept(bs, bytes >> BDRV_SECTOR_BITS, true);
3264b404f720SKevin Wolf     }
3265b404f720SKevin Wolf 
32663b8242e0SKevin Wolf     /*
32673b8242e0SKevin Wolf      * Align write if necessary by performing a read-modify-write cycle.
32683b8242e0SKevin Wolf      * Pad qiov with the read parts and be sure to have a tracked request not
32693b8242e0SKevin Wolf      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
32703b8242e0SKevin Wolf      */
327165afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, true);
32723b8242e0SKevin Wolf 
32733b8242e0SKevin Wolf     if (offset & (align - 1)) {
32743b8242e0SKevin Wolf         QEMUIOVector head_qiov;
32753b8242e0SKevin Wolf         struct iovec head_iov;
32763b8242e0SKevin Wolf 
32773b8242e0SKevin Wolf         mark_request_serialising(&req, align);
32783b8242e0SKevin Wolf         wait_serialising_requests(&req);
32793b8242e0SKevin Wolf 
32803b8242e0SKevin Wolf         head_buf = qemu_blockalign(bs, align);
32813b8242e0SKevin Wolf         head_iov = (struct iovec) {
32823b8242e0SKevin Wolf             .iov_base   = head_buf,
32833b8242e0SKevin Wolf             .iov_len    = align,
32843b8242e0SKevin Wolf         };
32853b8242e0SKevin Wolf         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
32863b8242e0SKevin Wolf 
32873b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
32883b8242e0SKevin Wolf                                   align, &head_qiov, 0);
32893b8242e0SKevin Wolf         if (ret < 0) {
32903b8242e0SKevin Wolf             goto fail;
32913b8242e0SKevin Wolf         }
32923b8242e0SKevin Wolf 
32933b8242e0SKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
32943b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
32953b8242e0SKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
32963b8242e0SKevin Wolf         use_local_qiov = true;
32973b8242e0SKevin Wolf 
32983b8242e0SKevin Wolf         bytes += offset & (align - 1);
32993b8242e0SKevin Wolf         offset = offset & ~(align - 1);
33003b8242e0SKevin Wolf     }
33013b8242e0SKevin Wolf 
33023b8242e0SKevin Wolf     if ((offset + bytes) & (align - 1)) {
33033b8242e0SKevin Wolf         QEMUIOVector tail_qiov;
33043b8242e0SKevin Wolf         struct iovec tail_iov;
33053b8242e0SKevin Wolf         size_t tail_bytes;
330628de2dcdSKevin Wolf         bool waited;
33073b8242e0SKevin Wolf 
33083b8242e0SKevin Wolf         mark_request_serialising(&req, align);
330928de2dcdSKevin Wolf         waited = wait_serialising_requests(&req);
331028de2dcdSKevin Wolf         assert(!waited || !use_local_qiov);
33113b8242e0SKevin Wolf 
33123b8242e0SKevin Wolf         tail_buf = qemu_blockalign(bs, align);
33133b8242e0SKevin Wolf         tail_iov = (struct iovec) {
33143b8242e0SKevin Wolf             .iov_base   = tail_buf,
33153b8242e0SKevin Wolf             .iov_len    = align,
33163b8242e0SKevin Wolf         };
33173b8242e0SKevin Wolf         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
33183b8242e0SKevin Wolf 
33193b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
33203b8242e0SKevin Wolf                                   align, &tail_qiov, 0);
33213b8242e0SKevin Wolf         if (ret < 0) {
33223b8242e0SKevin Wolf             goto fail;
33233b8242e0SKevin Wolf         }
33243b8242e0SKevin Wolf 
33253b8242e0SKevin Wolf         if (!use_local_qiov) {
33263b8242e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
33273b8242e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
33283b8242e0SKevin Wolf             use_local_qiov = true;
33293b8242e0SKevin Wolf         }
33303b8242e0SKevin Wolf 
33313b8242e0SKevin Wolf         tail_bytes = (offset + bytes) & (align - 1);
33323b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
33333b8242e0SKevin Wolf 
33343b8242e0SKevin Wolf         bytes = ROUND_UP(bytes, align);
33353b8242e0SKevin Wolf     }
33363b8242e0SKevin Wolf 
33373b8242e0SKevin Wolf     ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
33383b8242e0SKevin Wolf                                use_local_qiov ? &local_qiov : qiov,
33393b8242e0SKevin Wolf                                flags);
33403b8242e0SKevin Wolf 
33413b8242e0SKevin Wolf fail:
334265afd211SKevin Wolf     tracked_request_end(&req);
3343b404f720SKevin Wolf 
33443b8242e0SKevin Wolf     if (use_local_qiov) {
33453b8242e0SKevin Wolf         qemu_iovec_destroy(&local_qiov);
33463b8242e0SKevin Wolf         qemu_vfree(head_buf);
33473b8242e0SKevin Wolf         qemu_vfree(tail_buf);
33483b8242e0SKevin Wolf     }
33493b8242e0SKevin Wolf 
3350b404f720SKevin Wolf     return ret;
3351b404f720SKevin Wolf }
3352b404f720SKevin Wolf 
33536601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
33546601553eSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
33556601553eSKevin Wolf     BdrvRequestFlags flags)
33566601553eSKevin Wolf {
33576601553eSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
33586601553eSKevin Wolf         return -EINVAL;
33596601553eSKevin Wolf     }
33606601553eSKevin Wolf 
33616601553eSKevin Wolf     return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
33626601553eSKevin Wolf                               nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
33636601553eSKevin Wolf }
33646601553eSKevin Wolf 
3365c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3366c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3367c5fbe571SStefan Hajnoczi {
3368c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3369c5fbe571SStefan Hajnoczi 
3370f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3371f08f2ddaSStefan Hajnoczi }
3372f08f2ddaSStefan Hajnoczi 
3373f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3374aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3375aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3376f08f2ddaSStefan Hajnoczi {
337794d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3378f08f2ddaSStefan Hajnoczi 
3379d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3380d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3381d32f35cbSPeter Lieven     }
3382d32f35cbSPeter Lieven 
3383f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3384aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3385c5fbe571SStefan Hajnoczi }
3386c5fbe571SStefan Hajnoczi 
338783f64091Sbellard /**
338883f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
338983f64091Sbellard  */
339083f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
339183f64091Sbellard {
339283f64091Sbellard     BlockDriver *drv = bs->drv;
339351762288SStefan Hajnoczi     int ret;
339483f64091Sbellard     if (!drv)
339519cb3738Sbellard         return -ENOMEDIUM;
339683f64091Sbellard     if (!drv->bdrv_truncate)
339783f64091Sbellard         return -ENOTSUP;
339859f2689dSNaphtali Sprei     if (bs->read_only)
339959f2689dSNaphtali Sprei         return -EACCES;
34008591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
34018591675fSMarcelo Tosatti         return -EBUSY;
340251762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
340351762288SStefan Hajnoczi     if (ret == 0) {
340451762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3405145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
340651762288SStefan Hajnoczi     }
340751762288SStefan Hajnoczi     return ret;
340883f64091Sbellard }
340983f64091Sbellard 
341083f64091Sbellard /**
34114a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
34124a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
34134a1d5e1fSFam Zheng  */
34144a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
34154a1d5e1fSFam Zheng {
34164a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
34174a1d5e1fSFam Zheng     if (!drv) {
34184a1d5e1fSFam Zheng         return -ENOMEDIUM;
34194a1d5e1fSFam Zheng     }
34204a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
34214a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
34224a1d5e1fSFam Zheng     }
34234a1d5e1fSFam Zheng     if (bs->file) {
34244a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
34254a1d5e1fSFam Zheng     }
34264a1d5e1fSFam Zheng     return -ENOTSUP;
34274a1d5e1fSFam Zheng }
34284a1d5e1fSFam Zheng 
34294a1d5e1fSFam Zheng /**
343083f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
343183f64091Sbellard  */
343283f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
343383f64091Sbellard {
343483f64091Sbellard     BlockDriver *drv = bs->drv;
343583f64091Sbellard     if (!drv)
343619cb3738Sbellard         return -ENOMEDIUM;
343751762288SStefan Hajnoczi 
3438b94a2610SKevin Wolf     if (drv->has_variable_length) {
3439b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3440b94a2610SKevin Wolf         if (ret < 0) {
3441b94a2610SKevin Wolf             return ret;
3442fc01f7e7Sbellard         }
344346a4e4e6SStefan Hajnoczi     }
344446a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
344546a4e4e6SStefan Hajnoczi }
3446fc01f7e7Sbellard 
344719cb3738Sbellard /* return 0 as number of sectors if no device present or error */
344896b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3449fc01f7e7Sbellard {
345019cb3738Sbellard     int64_t length;
345119cb3738Sbellard     length = bdrv_getlength(bs);
345219cb3738Sbellard     if (length < 0)
345319cb3738Sbellard         length = 0;
345419cb3738Sbellard     else
34556ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
345619cb3738Sbellard     *nb_sectors_ptr = length;
3457fc01f7e7Sbellard }
3458cf98951bSbellard 
3459ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3460ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3461abd7f68dSMarkus Armbruster {
3462abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3463abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3464abd7f68dSMarkus Armbruster }
3465abd7f68dSMarkus Armbruster 
34661ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3467abd7f68dSMarkus Armbruster {
3468abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3469abd7f68dSMarkus Armbruster }
3470abd7f68dSMarkus Armbruster 
34713e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
34723e1caa5fSPaolo Bonzini {
34733e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
34743e1caa5fSPaolo Bonzini 
34753e1caa5fSPaolo Bonzini     switch (on_err) {
34763e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
34773e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
34783e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
34793e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
34803e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
34813e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
34823e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
34833e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
34843e1caa5fSPaolo Bonzini     default:
34853e1caa5fSPaolo Bonzini         abort();
34863e1caa5fSPaolo Bonzini     }
34873e1caa5fSPaolo Bonzini }
34883e1caa5fSPaolo Bonzini 
34893e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
34903e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
34913e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
34923e1caa5fSPaolo Bonzini  */
34933e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
34943e1caa5fSPaolo Bonzini                        bool is_read, int error)
34953e1caa5fSPaolo Bonzini {
34963e1caa5fSPaolo Bonzini     assert(error >= 0);
349732c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
34983e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
34993e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
35003e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
35013e1caa5fSPaolo Bonzini     }
35023e1caa5fSPaolo Bonzini }
35033e1caa5fSPaolo Bonzini 
3504b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3505b338082bSbellard {
3506b338082bSbellard     return bs->read_only;
3507b338082bSbellard }
3508b338082bSbellard 
3509985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3510985a03b0Sths {
3511985a03b0Sths     return bs->sg;
3512985a03b0Sths }
3513985a03b0Sths 
3514e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3515e900a7b7SChristoph Hellwig {
3516e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3517e900a7b7SChristoph Hellwig }
3518e900a7b7SChristoph Hellwig 
3519425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3520425b0148SPaolo Bonzini {
3521425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
352255b110f2SJeff Cody 
352355b110f2SJeff Cody     /* so a reopen() will preserve wce */
352455b110f2SJeff Cody     if (wce) {
352555b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
352655b110f2SJeff Cody     } else {
352755b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
352855b110f2SJeff Cody     }
3529425b0148SPaolo Bonzini }
3530425b0148SPaolo Bonzini 
3531ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3532ea2384d3Sbellard {
3533ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3534ea2384d3Sbellard         return 1;
3535ea2384d3Sbellard     return bs->encrypted;
3536ea2384d3Sbellard }
3537ea2384d3Sbellard 
3538c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3539c0f4ce77Saliguori {
3540c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3541c0f4ce77Saliguori 
3542c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3543c0f4ce77Saliguori         return 1;
3544c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3545c0f4ce77Saliguori }
3546c0f4ce77Saliguori 
3547ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3548ea2384d3Sbellard {
3549ea2384d3Sbellard     int ret;
3550ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3551ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3552ea2384d3Sbellard         if (ret < 0)
3553ea2384d3Sbellard             return ret;
3554ea2384d3Sbellard         if (!bs->encrypted)
3555ea2384d3Sbellard             return 0;
3556ea2384d3Sbellard     }
3557fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3558fd04a2aeSShahar Havivi         return -EINVAL;
3559fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3560fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3561fd04a2aeSShahar Havivi     }
3562c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3563bb5fc20fSaliguori     if (ret < 0) {
3564bb5fc20fSaliguori         bs->valid_key = 0;
3565bb5fc20fSaliguori     } else if (!bs->valid_key) {
3566bb5fc20fSaliguori         bs->valid_key = 1;
3567bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
35687d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3569bb5fc20fSaliguori     }
3570c0f4ce77Saliguori     return ret;
3571ea2384d3Sbellard }
3572ea2384d3Sbellard 
3573f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3574ea2384d3Sbellard {
3575f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3576ea2384d3Sbellard }
3577ea2384d3Sbellard 
3578ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3579ea2384d3Sbellard                          void *opaque)
3580ea2384d3Sbellard {
3581ea2384d3Sbellard     BlockDriver *drv;
3582ea2384d3Sbellard 
35838a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3584ea2384d3Sbellard         it(opaque, drv->format_name);
3585ea2384d3Sbellard     }
3586ea2384d3Sbellard }
3587ea2384d3Sbellard 
3588dc364f4cSBenoît Canet /* This function is to find block backend bs */
3589b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3590b338082bSbellard {
3591b338082bSbellard     BlockDriverState *bs;
3592b338082bSbellard 
3593dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
35941b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3595b338082bSbellard             return bs;
3596b338082bSbellard         }
35971b7bdbc1SStefan Hajnoczi     }
3598b338082bSbellard     return NULL;
3599b338082bSbellard }
3600b338082bSbellard 
3601dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3602dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3603dc364f4cSBenoît Canet {
3604dc364f4cSBenoît Canet     BlockDriverState *bs;
3605dc364f4cSBenoît Canet 
3606dc364f4cSBenoît Canet     assert(node_name);
3607dc364f4cSBenoît Canet 
3608dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3609dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3610dc364f4cSBenoît Canet             return bs;
3611dc364f4cSBenoît Canet         }
3612dc364f4cSBenoît Canet     }
3613dc364f4cSBenoît Canet     return NULL;
3614dc364f4cSBenoît Canet }
3615dc364f4cSBenoît Canet 
3616c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3617c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3618c13163fbSBenoît Canet {
3619c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3620c13163fbSBenoît Canet     BlockDriverState *bs;
3621c13163fbSBenoît Canet 
3622c13163fbSBenoît Canet     list = NULL;
3623c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3624c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3625c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3626c13163fbSBenoît Canet         entry->next = list;
3627c13163fbSBenoît Canet         list = entry;
3628c13163fbSBenoît Canet     }
3629c13163fbSBenoît Canet 
3630c13163fbSBenoît Canet     return list;
3631c13163fbSBenoît Canet }
3632c13163fbSBenoît Canet 
363312d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
363412d3ba82SBenoît Canet                                  const char *node_name,
363512d3ba82SBenoît Canet                                  Error **errp)
363612d3ba82SBenoît Canet {
363712d3ba82SBenoît Canet     BlockDriverState *bs = NULL;
363812d3ba82SBenoît Canet 
363912d3ba82SBenoît Canet     if ((!device && !node_name) || (device && node_name)) {
364012d3ba82SBenoît Canet         error_setg(errp, "Use either device or node-name but not both");
364112d3ba82SBenoît Canet         return NULL;
364212d3ba82SBenoît Canet     }
364312d3ba82SBenoît Canet 
364412d3ba82SBenoît Canet     if (device) {
364512d3ba82SBenoît Canet         bs = bdrv_find(device);
364612d3ba82SBenoît Canet 
364712d3ba82SBenoît Canet         if (!bs) {
364812d3ba82SBenoît Canet             error_set(errp, QERR_DEVICE_NOT_FOUND, device);
364912d3ba82SBenoît Canet             return NULL;
365012d3ba82SBenoît Canet         }
365112d3ba82SBenoît Canet 
365212d3ba82SBenoît Canet         return bs;
365312d3ba82SBenoît Canet     }
365412d3ba82SBenoît Canet 
365512d3ba82SBenoît Canet     bs = bdrv_find_node(node_name);
365612d3ba82SBenoît Canet 
365712d3ba82SBenoît Canet     if (!bs) {
365812d3ba82SBenoît Canet         error_set(errp, QERR_DEVICE_NOT_FOUND, node_name);
365912d3ba82SBenoît Canet         return NULL;
366012d3ba82SBenoît Canet     }
366112d3ba82SBenoît Canet 
366212d3ba82SBenoît Canet     return bs;
366312d3ba82SBenoît Canet }
366412d3ba82SBenoît Canet 
36652f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
36662f399b0aSMarkus Armbruster {
36672f399b0aSMarkus Armbruster     if (!bs) {
36682f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
36692f399b0aSMarkus Armbruster     }
3670dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
36712f399b0aSMarkus Armbruster }
36722f399b0aSMarkus Armbruster 
367351de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
367481d0912dSbellard {
367581d0912dSbellard     BlockDriverState *bs;
367681d0912dSbellard 
3677dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
367851de9760Saliguori         it(opaque, bs);
367981d0912dSbellard     }
368081d0912dSbellard }
368181d0912dSbellard 
3682ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3683ea2384d3Sbellard {
3684ea2384d3Sbellard     return bs->device_name;
3685ea2384d3Sbellard }
3686ea2384d3Sbellard 
3687c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3688c8433287SMarkus Armbruster {
3689c8433287SMarkus Armbruster     return bs->open_flags;
3690c8433287SMarkus Armbruster }
3691c8433287SMarkus Armbruster 
3692f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3693c6ca28d6Saliguori {
3694c6ca28d6Saliguori     BlockDriverState *bs;
3695f0f0fdfeSKevin Wolf     int result = 0;
3696c6ca28d6Saliguori 
3697dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3698f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3699f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3700f0f0fdfeSKevin Wolf             result = ret;
3701c6ca28d6Saliguori         }
37021b7bdbc1SStefan Hajnoczi     }
3703c6ca28d6Saliguori 
3704f0f0fdfeSKevin Wolf     return result;
3705f0f0fdfeSKevin Wolf }
3706f0f0fdfeSKevin Wolf 
37073ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
37083ac21627SPeter Lieven {
37093ac21627SPeter Lieven     return 1;
37103ac21627SPeter Lieven }
37113ac21627SPeter Lieven 
3712f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3713f2feebbdSKevin Wolf {
3714f2feebbdSKevin Wolf     assert(bs->drv);
3715f2feebbdSKevin Wolf 
371611212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
371711212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
371811212d8fSPaolo Bonzini     if (bs->backing_hd) {
371911212d8fSPaolo Bonzini         return 0;
372011212d8fSPaolo Bonzini     }
3721336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3722336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3723f2feebbdSKevin Wolf     }
3724f2feebbdSKevin Wolf 
37253ac21627SPeter Lieven     /* safe default */
37263ac21627SPeter Lieven     return 0;
3727f2feebbdSKevin Wolf }
3728f2feebbdSKevin Wolf 
37294ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
37304ce78691SPeter Lieven {
37314ce78691SPeter Lieven     BlockDriverInfo bdi;
37324ce78691SPeter Lieven 
37334ce78691SPeter Lieven     if (bs->backing_hd) {
37344ce78691SPeter Lieven         return false;
37354ce78691SPeter Lieven     }
37364ce78691SPeter Lieven 
37374ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
37384ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
37394ce78691SPeter Lieven     }
37404ce78691SPeter Lieven 
37414ce78691SPeter Lieven     return false;
37424ce78691SPeter Lieven }
37434ce78691SPeter Lieven 
37444ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
37454ce78691SPeter Lieven {
37464ce78691SPeter Lieven     BlockDriverInfo bdi;
37474ce78691SPeter Lieven 
37484ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
37494ce78691SPeter Lieven         return false;
37504ce78691SPeter Lieven     }
37514ce78691SPeter Lieven 
37524ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
37534ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
37544ce78691SPeter Lieven     }
37554ce78691SPeter Lieven 
37564ce78691SPeter Lieven     return false;
37574ce78691SPeter Lieven }
37584ce78691SPeter Lieven 
3759b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3760376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3761b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3762376ae3f1SStefan Hajnoczi     int64_t sector_num;
3763376ae3f1SStefan Hajnoczi     int nb_sectors;
3764376ae3f1SStefan Hajnoczi     int *pnum;
3765b6b8a333SPaolo Bonzini     int64_t ret;
3766376ae3f1SStefan Hajnoczi     bool done;
3767b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3768376ae3f1SStefan Hajnoczi 
3769f58c7b35Sths /*
3770f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3771f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3772f58c7b35Sths  * hence all their sectors are reported as allocated.
3773f58c7b35Sths  *
3774bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3775bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3776bd9533e3SStefan Hajnoczi  *
3777f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3778f58c7b35Sths  * the specified sector) that are known to be in the same
3779f58c7b35Sths  * allocated/unallocated state.
3780f58c7b35Sths  *
3781bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3782bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3783f58c7b35Sths  */
3784b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3785bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3786060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3787f58c7b35Sths {
3788617ccb46SPaolo Bonzini     int64_t length;
3789f58c7b35Sths     int64_t n;
37905daa74a6SPaolo Bonzini     int64_t ret, ret2;
3791bd9533e3SStefan Hajnoczi 
3792617ccb46SPaolo Bonzini     length = bdrv_getlength(bs);
3793617ccb46SPaolo Bonzini     if (length < 0) {
3794617ccb46SPaolo Bonzini         return length;
3795617ccb46SPaolo Bonzini     }
3796617ccb46SPaolo Bonzini 
3797617ccb46SPaolo Bonzini     if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
37986aebab14SStefan Hajnoczi         *pnum = 0;
37996aebab14SStefan Hajnoczi         return 0;
38006aebab14SStefan Hajnoczi     }
3801bd9533e3SStefan Hajnoczi 
38026aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3803bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3804bd9533e3SStefan Hajnoczi         nb_sectors = n;
3805bd9533e3SStefan Hajnoczi     }
3806bd9533e3SStefan Hajnoczi 
3807b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3808bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3809918e92d7SPaolo Bonzini         ret = BDRV_BLOCK_DATA;
3810918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3811918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3812918e92d7SPaolo Bonzini         }
3813918e92d7SPaolo Bonzini         return ret;
38146aebab14SStefan Hajnoczi     }
38156aebab14SStefan Hajnoczi 
3816415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3817415b5b01SPaolo Bonzini     if (ret < 0) {
38183e0a233dSPeter Lieven         *pnum = 0;
3819415b5b01SPaolo Bonzini         return ret;
3820415b5b01SPaolo Bonzini     }
3821415b5b01SPaolo Bonzini 
382292bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
382392bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
382492bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
382592bc50a5SPeter Lieven                                      *pnum, pnum);
382692bc50a5SPeter Lieven     }
382792bc50a5SPeter Lieven 
3828c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3829c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
3830415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
38311f9db224SPeter Lieven         } else if (bs->backing_hd) {
3832f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
3833f0ad5712SPaolo Bonzini             int64_t length2 = bdrv_getlength(bs2);
3834f0ad5712SPaolo Bonzini             if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3835f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3836f0ad5712SPaolo Bonzini             }
3837f0ad5712SPaolo Bonzini         }
3838415b5b01SPaolo Bonzini     }
38395daa74a6SPaolo Bonzini 
38405daa74a6SPaolo Bonzini     if (bs->file &&
38415daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
38425daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
38435daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
38445daa74a6SPaolo Bonzini                                         *pnum, pnum);
38455daa74a6SPaolo Bonzini         if (ret2 >= 0) {
38465daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
38475daa74a6SPaolo Bonzini              * is useful but not necessary.
38485daa74a6SPaolo Bonzini              */
38495daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
38505daa74a6SPaolo Bonzini         }
38515daa74a6SPaolo Bonzini     }
38525daa74a6SPaolo Bonzini 
3853415b5b01SPaolo Bonzini     return ret;
3854060f51c9SStefan Hajnoczi }
3855060f51c9SStefan Hajnoczi 
3856b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3857b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3858060f51c9SStefan Hajnoczi {
3859b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3860060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3861060f51c9SStefan Hajnoczi 
3862b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3863060f51c9SStefan Hajnoczi                                          data->pnum);
3864060f51c9SStefan Hajnoczi     data->done = true;
3865060f51c9SStefan Hajnoczi }
3866060f51c9SStefan Hajnoczi 
3867060f51c9SStefan Hajnoczi /*
3868b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3869060f51c9SStefan Hajnoczi  *
3870b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
3871060f51c9SStefan Hajnoczi  */
3872b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3873b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
3874060f51c9SStefan Hajnoczi {
3875376ae3f1SStefan Hajnoczi     Coroutine *co;
3876b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
3877376ae3f1SStefan Hajnoczi         .bs = bs,
3878376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3879376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3880376ae3f1SStefan Hajnoczi         .pnum = pnum,
3881376ae3f1SStefan Hajnoczi         .done = false,
3882376ae3f1SStefan Hajnoczi     };
3883376ae3f1SStefan Hajnoczi 
3884bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
3885bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
3886b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
3887bdad13b9SPaolo Bonzini     } else {
3888b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
3889376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
3890376ae3f1SStefan Hajnoczi         while (!data.done) {
3891376ae3f1SStefan Hajnoczi             qemu_aio_wait();
3892376ae3f1SStefan Hajnoczi         }
3893bdad13b9SPaolo Bonzini     }
3894376ae3f1SStefan Hajnoczi     return data.ret;
3895376ae3f1SStefan Hajnoczi }
3896f58c7b35Sths 
3897b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
3898b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
3899b6b8a333SPaolo Bonzini {
39004333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
39014333bb71SPaolo Bonzini     if (ret < 0) {
39024333bb71SPaolo Bonzini         return ret;
39034333bb71SPaolo Bonzini     }
39044333bb71SPaolo Bonzini     return
39054333bb71SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) ||
39064333bb71SPaolo Bonzini         ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
3907b6b8a333SPaolo Bonzini }
3908b6b8a333SPaolo Bonzini 
3909188a7bbfSPaolo Bonzini /*
3910188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3911188a7bbfSPaolo Bonzini  *
3912188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3913188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3914188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3915188a7bbfSPaolo Bonzini  *
3916188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3917188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3918188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3919188a7bbfSPaolo Bonzini  *
3920188a7bbfSPaolo Bonzini  */
39214f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
3922188a7bbfSPaolo Bonzini                             BlockDriverState *base,
3923188a7bbfSPaolo Bonzini                             int64_t sector_num,
3924188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
3925188a7bbfSPaolo Bonzini {
3926188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3927188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3928188a7bbfSPaolo Bonzini 
3929188a7bbfSPaolo Bonzini     intermediate = top;
3930188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3931188a7bbfSPaolo Bonzini         int pnum_inter;
3932bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
3933188a7bbfSPaolo Bonzini                                 &pnum_inter);
3934188a7bbfSPaolo Bonzini         if (ret < 0) {
3935188a7bbfSPaolo Bonzini             return ret;
3936188a7bbfSPaolo Bonzini         } else if (ret) {
3937188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3938188a7bbfSPaolo Bonzini             return 1;
3939188a7bbfSPaolo Bonzini         }
3940188a7bbfSPaolo Bonzini 
3941188a7bbfSPaolo Bonzini         /*
3942188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3943188a7bbfSPaolo Bonzini          * might have
3944188a7bbfSPaolo Bonzini          *
3945188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3946188a7bbfSPaolo Bonzini          */
394763ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
394863ba17d3SVishvananda Ishaya             (intermediate == top ||
394963ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3950188a7bbfSPaolo Bonzini             n = pnum_inter;
3951188a7bbfSPaolo Bonzini         }
3952188a7bbfSPaolo Bonzini 
3953188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3954188a7bbfSPaolo Bonzini     }
3955188a7bbfSPaolo Bonzini 
3956188a7bbfSPaolo Bonzini     *pnum = n;
3957188a7bbfSPaolo Bonzini     return 0;
3958188a7bbfSPaolo Bonzini }
3959188a7bbfSPaolo Bonzini 
3960045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3961045df330Saliguori {
3962045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3963045df330Saliguori         return bs->backing_file;
3964045df330Saliguori     else if (bs->encrypted)
3965045df330Saliguori         return bs->filename;
3966045df330Saliguori     else
3967045df330Saliguori         return NULL;
3968045df330Saliguori }
3969045df330Saliguori 
397083f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
397183f64091Sbellard                                char *filename, int filename_size)
397283f64091Sbellard {
397383f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
397483f64091Sbellard }
397583f64091Sbellard 
3976faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3977faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3978faea38e7Sbellard {
3979faea38e7Sbellard     BlockDriver *drv = bs->drv;
3980faea38e7Sbellard     if (!drv)
398119cb3738Sbellard         return -ENOMEDIUM;
3982faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3983faea38e7Sbellard         return -ENOTSUP;
3984fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3985fbb7b4e0SKevin Wolf         return -EIO;
39867cd1e32aSlirans@il.ibm.com 
3987e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
39887cd1e32aSlirans@il.ibm.com 
3989faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3990faea38e7Sbellard }
3991faea38e7Sbellard 
3992faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3993faea38e7Sbellard {
3994faea38e7Sbellard     BlockDriver *drv = bs->drv;
3995faea38e7Sbellard     if (!drv)
399619cb3738Sbellard         return -ENOMEDIUM;
3997faea38e7Sbellard     if (!drv->bdrv_get_info)
3998faea38e7Sbellard         return -ENOTSUP;
3999faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
4000faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
4001faea38e7Sbellard }
4002faea38e7Sbellard 
4003eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
4004eae041feSMax Reitz {
4005eae041feSMax Reitz     BlockDriver *drv = bs->drv;
4006eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
4007eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
4008eae041feSMax Reitz     }
4009eae041feSMax Reitz     return NULL;
4010eae041feSMax Reitz }
4011eae041feSMax Reitz 
401245566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
401345566e9cSChristoph Hellwig                       int64_t pos, int size)
4014178e08a5Saliguori {
4015cf8074b3SKevin Wolf     QEMUIOVector qiov;
4016cf8074b3SKevin Wolf     struct iovec iov = {
4017cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
4018cf8074b3SKevin Wolf         .iov_len    = size,
4019cf8074b3SKevin Wolf     };
4020cf8074b3SKevin Wolf 
4021cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
4022cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
4023cf8074b3SKevin Wolf }
4024cf8074b3SKevin Wolf 
4025cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
4026cf8074b3SKevin Wolf {
4027178e08a5Saliguori     BlockDriver *drv = bs->drv;
4028cf8074b3SKevin Wolf 
4029cf8074b3SKevin Wolf     if (!drv) {
4030178e08a5Saliguori         return -ENOMEDIUM;
4031cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
4032cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
4033cf8074b3SKevin Wolf     } else if (bs->file) {
4034cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
4035cf8074b3SKevin Wolf     }
4036cf8074b3SKevin Wolf 
40377cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4038178e08a5Saliguori }
4039178e08a5Saliguori 
404045566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
404145566e9cSChristoph Hellwig                       int64_t pos, int size)
4042178e08a5Saliguori {
4043178e08a5Saliguori     BlockDriver *drv = bs->drv;
4044178e08a5Saliguori     if (!drv)
4045178e08a5Saliguori         return -ENOMEDIUM;
40467cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
404745566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
40487cdb1f6dSMORITA Kazutaka     if (bs->file)
40497cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
40507cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4051178e08a5Saliguori }
4052178e08a5Saliguori 
40538b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
40548b9b0cc2SKevin Wolf {
4055bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
40568b9b0cc2SKevin Wolf         return;
40578b9b0cc2SKevin Wolf     }
40588b9b0cc2SKevin Wolf 
4059bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
406041c695c7SKevin Wolf }
40618b9b0cc2SKevin Wolf 
406241c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
406341c695c7SKevin Wolf                           const char *tag)
406441c695c7SKevin Wolf {
406541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
406641c695c7SKevin Wolf         bs = bs->file;
406741c695c7SKevin Wolf     }
406841c695c7SKevin Wolf 
406941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
407041c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
407141c695c7SKevin Wolf     }
407241c695c7SKevin Wolf 
407341c695c7SKevin Wolf     return -ENOTSUP;
407441c695c7SKevin Wolf }
407541c695c7SKevin Wolf 
40764cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
40774cc70e93SFam Zheng {
40784cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
40794cc70e93SFam Zheng         bs = bs->file;
40804cc70e93SFam Zheng     }
40814cc70e93SFam Zheng 
40824cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
40834cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
40844cc70e93SFam Zheng     }
40854cc70e93SFam Zheng 
40864cc70e93SFam Zheng     return -ENOTSUP;
40874cc70e93SFam Zheng }
40884cc70e93SFam Zheng 
408941c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
409041c695c7SKevin Wolf {
409141c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
409241c695c7SKevin Wolf         bs = bs->file;
409341c695c7SKevin Wolf     }
409441c695c7SKevin Wolf 
409541c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
409641c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
409741c695c7SKevin Wolf     }
409841c695c7SKevin Wolf 
409941c695c7SKevin Wolf     return -ENOTSUP;
410041c695c7SKevin Wolf }
410141c695c7SKevin Wolf 
410241c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
410341c695c7SKevin Wolf {
410441c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
410541c695c7SKevin Wolf         bs = bs->file;
410641c695c7SKevin Wolf     }
410741c695c7SKevin Wolf 
410841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
410941c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
411041c695c7SKevin Wolf     }
411141c695c7SKevin Wolf 
411241c695c7SKevin Wolf     return false;
41138b9b0cc2SKevin Wolf }
41148b9b0cc2SKevin Wolf 
4115199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
4116199630b6SBlue Swirl {
4117199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4118199630b6SBlue Swirl }
4119199630b6SBlue Swirl 
4120b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
4121b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
4122b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
4123b1b1d783SJeff Cody  * the CWD rather than the chain. */
4124e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4125e8a6bb9cSMarcelo Tosatti         const char *backing_file)
4126e8a6bb9cSMarcelo Tosatti {
4127b1b1d783SJeff Cody     char *filename_full = NULL;
4128b1b1d783SJeff Cody     char *backing_file_full = NULL;
4129b1b1d783SJeff Cody     char *filename_tmp = NULL;
4130b1b1d783SJeff Cody     int is_protocol = 0;
4131b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
4132b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
4133b1b1d783SJeff Cody 
4134b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
4135e8a6bb9cSMarcelo Tosatti         return NULL;
4136e8a6bb9cSMarcelo Tosatti     }
4137e8a6bb9cSMarcelo Tosatti 
4138b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
4139b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
4140b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
4141b1b1d783SJeff Cody 
4142b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
4143b1b1d783SJeff Cody 
4144b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4145b1b1d783SJeff Cody 
4146b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
4147b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
4148b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4149b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4150b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4151b1b1d783SJeff Cody                 break;
4152b1b1d783SJeff Cody             }
4153e8a6bb9cSMarcelo Tosatti         } else {
4154b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
4155b1b1d783SJeff Cody              * image's filename path */
4156b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4157b1b1d783SJeff Cody                          backing_file);
4158b1b1d783SJeff Cody 
4159b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
4160b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
4161b1b1d783SJeff Cody                 continue;
4162b1b1d783SJeff Cody             }
4163b1b1d783SJeff Cody 
4164b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
4165b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
4166b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4167b1b1d783SJeff Cody                          curr_bs->backing_file);
4168b1b1d783SJeff Cody 
4169b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
4170b1b1d783SJeff Cody                 continue;
4171b1b1d783SJeff Cody             }
4172b1b1d783SJeff Cody 
4173b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
4174b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4175b1b1d783SJeff Cody                 break;
4176b1b1d783SJeff Cody             }
4177e8a6bb9cSMarcelo Tosatti         }
4178e8a6bb9cSMarcelo Tosatti     }
4179e8a6bb9cSMarcelo Tosatti 
4180b1b1d783SJeff Cody     g_free(filename_full);
4181b1b1d783SJeff Cody     g_free(backing_file_full);
4182b1b1d783SJeff Cody     g_free(filename_tmp);
4183b1b1d783SJeff Cody     return retval;
4184e8a6bb9cSMarcelo Tosatti }
4185e8a6bb9cSMarcelo Tosatti 
4186f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
4187f198fd1cSBenoît Canet {
4188f198fd1cSBenoît Canet     if (!bs->drv) {
4189f198fd1cSBenoît Canet         return 0;
4190f198fd1cSBenoît Canet     }
4191f198fd1cSBenoît Canet 
4192f198fd1cSBenoît Canet     if (!bs->backing_hd) {
4193f198fd1cSBenoît Canet         return 0;
4194f198fd1cSBenoît Canet     }
4195f198fd1cSBenoît Canet 
4196f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4197f198fd1cSBenoît Canet }
4198f198fd1cSBenoît Canet 
419979fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
420079fac568SJeff Cody {
420179fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
420279fac568SJeff Cody 
420379fac568SJeff Cody     if (!bs) {
420479fac568SJeff Cody         return NULL;
420579fac568SJeff Cody     }
420679fac568SJeff Cody 
420779fac568SJeff Cody     curr_bs = bs;
420879fac568SJeff Cody 
420979fac568SJeff Cody     while (curr_bs->backing_hd) {
421079fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
421179fac568SJeff Cody     }
421279fac568SJeff Cody     return curr_bs;
421379fac568SJeff Cody }
421479fac568SJeff Cody 
4215ea2384d3Sbellard /**************************************************************/
421683f64091Sbellard /* async I/Os */
4217ea2384d3Sbellard 
42183b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
4219f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
422083f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
4221ea2384d3Sbellard {
4222bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4223bbf0a440SStefan Hajnoczi 
4224d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
42258c5873d6SStefan Hajnoczi                                  cb, opaque, false);
422683f64091Sbellard }
422783f64091Sbellard 
4228f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4229f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
423083f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
42317674e7bfSbellard {
4232bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4233bbf0a440SStefan Hajnoczi 
4234d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
42358c5873d6SStefan Hajnoczi                                  cb, opaque, true);
423683f64091Sbellard }
423783f64091Sbellard 
4238d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4239d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4240d5ef94d4SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
4241d5ef94d4SPaolo Bonzini {
4242d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4243d5ef94d4SPaolo Bonzini 
4244d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4245d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4246d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4247d5ef94d4SPaolo Bonzini }
4248d5ef94d4SPaolo Bonzini 
424940b4f539SKevin Wolf 
425040b4f539SKevin Wolf typedef struct MultiwriteCB {
425140b4f539SKevin Wolf     int error;
425240b4f539SKevin Wolf     int num_requests;
425340b4f539SKevin Wolf     int num_callbacks;
425440b4f539SKevin Wolf     struct {
425540b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
425640b4f539SKevin Wolf         void *opaque;
425740b4f539SKevin Wolf         QEMUIOVector *free_qiov;
425840b4f539SKevin Wolf     } callbacks[];
425940b4f539SKevin Wolf } MultiwriteCB;
426040b4f539SKevin Wolf 
426140b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
426240b4f539SKevin Wolf {
426340b4f539SKevin Wolf     int i;
426440b4f539SKevin Wolf 
426540b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
426640b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
42671e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
42681e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
42691e1ea48dSStefan Hajnoczi         }
42707267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
427140b4f539SKevin Wolf     }
427240b4f539SKevin Wolf }
427340b4f539SKevin Wolf 
427440b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
427540b4f539SKevin Wolf {
427640b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
427740b4f539SKevin Wolf 
42786d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
42796d519a5fSStefan Hajnoczi 
4280cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
428140b4f539SKevin Wolf         mcb->error = ret;
428240b4f539SKevin Wolf     }
428340b4f539SKevin Wolf 
428440b4f539SKevin Wolf     mcb->num_requests--;
428540b4f539SKevin Wolf     if (mcb->num_requests == 0) {
428640b4f539SKevin Wolf         multiwrite_user_cb(mcb);
42877267c094SAnthony Liguori         g_free(mcb);
428840b4f539SKevin Wolf     }
428940b4f539SKevin Wolf }
429040b4f539SKevin Wolf 
429140b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
429240b4f539SKevin Wolf {
429377be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
429477be4366SChristoph Hellwig 
429577be4366SChristoph Hellwig     /*
429677be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
429777be4366SChristoph Hellwig      * here as that could overflow the return value.
429877be4366SChristoph Hellwig      */
429977be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
430077be4366SChristoph Hellwig         return 1;
430177be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
430277be4366SChristoph Hellwig         return -1;
430377be4366SChristoph Hellwig     } else {
430477be4366SChristoph Hellwig         return 0;
430577be4366SChristoph Hellwig     }
430640b4f539SKevin Wolf }
430740b4f539SKevin Wolf 
430840b4f539SKevin Wolf /*
430940b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
431040b4f539SKevin Wolf  * requests that remain after merging.
431140b4f539SKevin Wolf  */
431240b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
431340b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
431440b4f539SKevin Wolf {
431540b4f539SKevin Wolf     int i, outidx;
431640b4f539SKevin Wolf 
431740b4f539SKevin Wolf     // Sort requests by start sector
431840b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
431940b4f539SKevin Wolf 
432040b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
432140b4f539SKevin Wolf     // filling up gaps with zero sectors.
432240b4f539SKevin Wolf     outidx = 0;
432340b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
432440b4f539SKevin Wolf         int merge = 0;
432540b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
432640b4f539SKevin Wolf 
4327b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
432840b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
432940b4f539SKevin Wolf             merge = 1;
433040b4f539SKevin Wolf         }
433140b4f539SKevin Wolf 
4332e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4333e2a305fbSChristoph Hellwig             merge = 0;
4334e2a305fbSChristoph Hellwig         }
4335e2a305fbSChristoph Hellwig 
433640b4f539SKevin Wolf         if (merge) {
433740b4f539SKevin Wolf             size_t size;
43387267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
433940b4f539SKevin Wolf             qemu_iovec_init(qiov,
434040b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
434140b4f539SKevin Wolf 
434240b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
434340b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
434440b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
43451b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
434640b4f539SKevin Wolf 
4347b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4348b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
434940b4f539SKevin Wolf 
435040b4f539SKevin Wolf             // Add the second request
43511b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
435240b4f539SKevin Wolf 
4353cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
435440b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
435540b4f539SKevin Wolf 
435640b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
435740b4f539SKevin Wolf         } else {
435840b4f539SKevin Wolf             outidx++;
435940b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
436040b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
436140b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
436240b4f539SKevin Wolf         }
436340b4f539SKevin Wolf     }
436440b4f539SKevin Wolf 
436540b4f539SKevin Wolf     return outidx + 1;
436640b4f539SKevin Wolf }
436740b4f539SKevin Wolf 
436840b4f539SKevin Wolf /*
436940b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
437040b4f539SKevin Wolf  *
437140b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
437240b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
437340b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
437440b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
437540b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
437640b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
437740b4f539SKevin Wolf  *
437840b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
437940b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
438040b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
438140b4f539SKevin Wolf  */
438240b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
438340b4f539SKevin Wolf {
438440b4f539SKevin Wolf     MultiwriteCB *mcb;
438540b4f539SKevin Wolf     int i;
438640b4f539SKevin Wolf 
4387301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4388301db7c2SRyan Harper     if (bs->drv == NULL) {
4389301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4390301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4391301db7c2SRyan Harper         }
4392301db7c2SRyan Harper         return -1;
4393301db7c2SRyan Harper     }
4394301db7c2SRyan Harper 
439540b4f539SKevin Wolf     if (num_reqs == 0) {
439640b4f539SKevin Wolf         return 0;
439740b4f539SKevin Wolf     }
439840b4f539SKevin Wolf 
439940b4f539SKevin Wolf     // Create MultiwriteCB structure
44007267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
440140b4f539SKevin Wolf     mcb->num_requests = 0;
440240b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
440340b4f539SKevin Wolf 
440440b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
440540b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
440640b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
440740b4f539SKevin Wolf     }
440840b4f539SKevin Wolf 
440940b4f539SKevin Wolf     // Check for mergable requests
441040b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
441140b4f539SKevin Wolf 
44126d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
44136d519a5fSStefan Hajnoczi 
4414df9309fbSPaolo Bonzini     /* Run the aio requests. */
4415df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
441640b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4417d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4418d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4419d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4420d20d9b7cSPaolo Bonzini                               true);
442140b4f539SKevin Wolf     }
442240b4f539SKevin Wolf 
442340b4f539SKevin Wolf     return 0;
442440b4f539SKevin Wolf }
442540b4f539SKevin Wolf 
442683f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
442783f64091Sbellard {
4428d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
442983f64091Sbellard }
443083f64091Sbellard 
443183f64091Sbellard /**************************************************************/
443283f64091Sbellard /* async block device emulation */
443383f64091Sbellard 
4434c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4435c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4436c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4437c16b5a2cSChristoph Hellwig     int ret;
4438c16b5a2cSChristoph Hellwig     /* vector translation state */
4439c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4440c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4441c16b5a2cSChristoph Hellwig     int is_write;
4442c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4443c16b5a2cSChristoph Hellwig 
4444c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4445c16b5a2cSChristoph Hellwig {
4446b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
4447b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
44486a7ad299SDor Laor     qemu_bh_delete(acb->bh);
444936afc451SAvi Kivity     acb->bh = NULL;
4450c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
4451c16b5a2cSChristoph Hellwig }
4452c16b5a2cSChristoph Hellwig 
4453d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4454c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4455c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
4456c16b5a2cSChristoph Hellwig };
4457c16b5a2cSChristoph Hellwig 
445883f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4459beac80cdSbellard {
4460ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4461f141eafeSaliguori 
4462f141eafeSaliguori     if (!acb->is_write)
446303396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4464ceb42de8Saliguori     qemu_vfree(acb->bounce);
4465ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
44666a7ad299SDor Laor     qemu_bh_delete(acb->bh);
446736afc451SAvi Kivity     acb->bh = NULL;
4468ce1a14dcSpbrook     qemu_aio_release(acb);
4469beac80cdSbellard }
4470beac80cdSbellard 
4471f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4472f141eafeSaliguori                                             int64_t sector_num,
4473f141eafeSaliguori                                             QEMUIOVector *qiov,
4474f141eafeSaliguori                                             int nb_sectors,
4475f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4476f141eafeSaliguori                                             void *opaque,
4477f141eafeSaliguori                                             int is_write)
4478f141eafeSaliguori 
4479ea2384d3Sbellard {
4480ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
448183f64091Sbellard 
4482d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4483f141eafeSaliguori     acb->is_write = is_write;
4484f141eafeSaliguori     acb->qiov = qiov;
4485e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
4486ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4487f141eafeSaliguori 
4488f141eafeSaliguori     if (is_write) {
4489d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
44901ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4491f141eafeSaliguori     } else {
44921ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4493f141eafeSaliguori     }
4494f141eafeSaliguori 
4495ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4496f141eafeSaliguori 
4497ce1a14dcSpbrook     return &acb->common;
44987a6cba61Spbrook }
44997a6cba61Spbrook 
4500f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4501f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4502ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
450383f64091Sbellard {
4504f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
450583f64091Sbellard }
450683f64091Sbellard 
4507f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4508f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4509f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4510f141eafeSaliguori {
4511f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4512f141eafeSaliguori }
4513f141eafeSaliguori 
451468485420SKevin Wolf 
451568485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
451668485420SKevin Wolf     BlockDriverAIOCB common;
451768485420SKevin Wolf     BlockRequest req;
451868485420SKevin Wolf     bool is_write;
4519d318aea9SKevin Wolf     bool *done;
452068485420SKevin Wolf     QEMUBH* bh;
452168485420SKevin Wolf } BlockDriverAIOCBCoroutine;
452268485420SKevin Wolf 
452368485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
452468485420SKevin Wolf {
4525d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
4526d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4527d318aea9SKevin Wolf     bool done = false;
4528d318aea9SKevin Wolf 
4529d318aea9SKevin Wolf     acb->done = &done;
4530d318aea9SKevin Wolf     while (!done) {
4531d318aea9SKevin Wolf         qemu_aio_wait();
4532d318aea9SKevin Wolf     }
453368485420SKevin Wolf }
453468485420SKevin Wolf 
4535d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
453668485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
453768485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
453868485420SKevin Wolf };
453968485420SKevin Wolf 
454035246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
454168485420SKevin Wolf {
454268485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
454368485420SKevin Wolf 
454468485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4545d318aea9SKevin Wolf 
4546d318aea9SKevin Wolf     if (acb->done) {
4547d318aea9SKevin Wolf         *acb->done = true;
4548d318aea9SKevin Wolf     }
4549d318aea9SKevin Wolf 
455068485420SKevin Wolf     qemu_bh_delete(acb->bh);
455168485420SKevin Wolf     qemu_aio_release(acb);
455268485420SKevin Wolf }
455368485420SKevin Wolf 
4554b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4555b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4556b2a61371SStefan Hajnoczi {
4557b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4558b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4559b2a61371SStefan Hajnoczi 
4560b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4561b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4562d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4563b2a61371SStefan Hajnoczi     } else {
4564b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4565d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4566b2a61371SStefan Hajnoczi     }
4567b2a61371SStefan Hajnoczi 
456835246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4569b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4570b2a61371SStefan Hajnoczi }
4571b2a61371SStefan Hajnoczi 
457268485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
457368485420SKevin Wolf                                                int64_t sector_num,
457468485420SKevin Wolf                                                QEMUIOVector *qiov,
457568485420SKevin Wolf                                                int nb_sectors,
4576d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
457768485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
457868485420SKevin Wolf                                                void *opaque,
45798c5873d6SStefan Hajnoczi                                                bool is_write)
458068485420SKevin Wolf {
458168485420SKevin Wolf     Coroutine *co;
458268485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
458368485420SKevin Wolf 
4584d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
458568485420SKevin Wolf     acb->req.sector = sector_num;
458668485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
458768485420SKevin Wolf     acb->req.qiov = qiov;
4588d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
458968485420SKevin Wolf     acb->is_write = is_write;
4590d318aea9SKevin Wolf     acb->done = NULL;
459168485420SKevin Wolf 
45928c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
459368485420SKevin Wolf     qemu_coroutine_enter(co, acb);
459468485420SKevin Wolf 
459568485420SKevin Wolf     return &acb->common;
459668485420SKevin Wolf }
459768485420SKevin Wolf 
459807f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4599b2e12bc6SChristoph Hellwig {
460007f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
460107f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4602b2e12bc6SChristoph Hellwig 
460307f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
460407f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4605b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4606b2e12bc6SChristoph Hellwig }
4607b2e12bc6SChristoph Hellwig 
460807f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4609016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4610016f5cf6SAlexander Graf {
461107f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4612016f5cf6SAlexander Graf 
461307f07615SPaolo Bonzini     Coroutine *co;
461407f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4615016f5cf6SAlexander Graf 
4616d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4617d318aea9SKevin Wolf     acb->done = NULL;
4618d318aea9SKevin Wolf 
461907f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
462007f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4621016f5cf6SAlexander Graf 
4622016f5cf6SAlexander Graf     return &acb->common;
4623016f5cf6SAlexander Graf }
4624016f5cf6SAlexander Graf 
46254265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
46264265d620SPaolo Bonzini {
46274265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
46284265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
46294265d620SPaolo Bonzini 
46304265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
46314265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
46324265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
46334265d620SPaolo Bonzini }
46344265d620SPaolo Bonzini 
46354265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
46364265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
46374265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
46384265d620SPaolo Bonzini {
46394265d620SPaolo Bonzini     Coroutine *co;
46404265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
46414265d620SPaolo Bonzini 
46424265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
46434265d620SPaolo Bonzini 
4644d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
46454265d620SPaolo Bonzini     acb->req.sector = sector_num;
46464265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4647d318aea9SKevin Wolf     acb->done = NULL;
46484265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
46494265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
46504265d620SPaolo Bonzini 
46514265d620SPaolo Bonzini     return &acb->common;
46524265d620SPaolo Bonzini }
46534265d620SPaolo Bonzini 
4654ea2384d3Sbellard void bdrv_init(void)
4655ea2384d3Sbellard {
46565efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4657ea2384d3Sbellard }
4658ce1a14dcSpbrook 
4659eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4660eb852011SMarkus Armbruster {
4661eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4662eb852011SMarkus Armbruster     bdrv_init();
4663eb852011SMarkus Armbruster }
4664eb852011SMarkus Armbruster 
4665d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
46666bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
46676bbff9a0Saliguori {
4668ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4669ce1a14dcSpbrook 
4670d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4671d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4672ce1a14dcSpbrook     acb->bs = bs;
4673ce1a14dcSpbrook     acb->cb = cb;
4674ce1a14dcSpbrook     acb->opaque = opaque;
4675ce1a14dcSpbrook     return acb;
4676ce1a14dcSpbrook }
4677ce1a14dcSpbrook 
4678ce1a14dcSpbrook void qemu_aio_release(void *p)
4679ce1a14dcSpbrook {
4680d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4681d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4682ce1a14dcSpbrook }
468319cb3738Sbellard 
468419cb3738Sbellard /**************************************************************/
4685f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4686f9f05dc5SKevin Wolf 
4687f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4688f9f05dc5SKevin Wolf     Coroutine *coroutine;
4689f9f05dc5SKevin Wolf     int ret;
4690f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4691f9f05dc5SKevin Wolf 
4692f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4693f9f05dc5SKevin Wolf {
4694f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4695f9f05dc5SKevin Wolf 
4696f9f05dc5SKevin Wolf     co->ret = ret;
4697f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4698f9f05dc5SKevin Wolf }
4699f9f05dc5SKevin Wolf 
4700f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4701f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4702f9f05dc5SKevin Wolf                                       bool is_write)
4703f9f05dc5SKevin Wolf {
4704f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4705f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4706f9f05dc5SKevin Wolf     };
4707f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4708f9f05dc5SKevin Wolf 
4709f9f05dc5SKevin Wolf     if (is_write) {
4710a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4711f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4712f9f05dc5SKevin Wolf     } else {
4713a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4714f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4715f9f05dc5SKevin Wolf     }
4716f9f05dc5SKevin Wolf 
471759370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4718f9f05dc5SKevin Wolf     if (!acb) {
4719f9f05dc5SKevin Wolf         return -EIO;
4720f9f05dc5SKevin Wolf     }
4721f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4722f9f05dc5SKevin Wolf 
4723f9f05dc5SKevin Wolf     return co.ret;
4724f9f05dc5SKevin Wolf }
4725f9f05dc5SKevin Wolf 
4726f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4727f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4728f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4729f9f05dc5SKevin Wolf {
4730f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4731f9f05dc5SKevin Wolf }
4732f9f05dc5SKevin Wolf 
4733f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4734f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4735f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4736f9f05dc5SKevin Wolf {
4737f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4738f9f05dc5SKevin Wolf }
4739f9f05dc5SKevin Wolf 
474007f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4741e7a8a783SKevin Wolf {
474207f07615SPaolo Bonzini     RwCo *rwco = opaque;
474307f07615SPaolo Bonzini 
474407f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
474507f07615SPaolo Bonzini }
474607f07615SPaolo Bonzini 
474707f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
474807f07615SPaolo Bonzini {
4749eb489bb1SKevin Wolf     int ret;
4750eb489bb1SKevin Wolf 
475129cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
475207f07615SPaolo Bonzini         return 0;
4753eb489bb1SKevin Wolf     }
4754eb489bb1SKevin Wolf 
4755ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4756bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4757eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4758eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4759eb489bb1SKevin Wolf         if (ret < 0) {
4760eb489bb1SKevin Wolf             return ret;
4761eb489bb1SKevin Wolf         }
4762eb489bb1SKevin Wolf     }
4763eb489bb1SKevin Wolf 
4764ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4765ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4766d4c82329SKevin Wolf         goto flush_parent;
4767ca716364SKevin Wolf     }
4768ca716364SKevin Wolf 
4769bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4770eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
477129cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
477207f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
477307f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4774e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4775e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4776e7a8a783SKevin Wolf         };
4777e7a8a783SKevin Wolf 
477807f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
477907f07615SPaolo Bonzini         if (acb == NULL) {
478029cdb251SPaolo Bonzini             ret = -EIO;
478107f07615SPaolo Bonzini         } else {
4782e7a8a783SKevin Wolf             qemu_coroutine_yield();
478329cdb251SPaolo Bonzini             ret = co.ret;
4784e7a8a783SKevin Wolf         }
478507f07615SPaolo Bonzini     } else {
478607f07615SPaolo Bonzini         /*
478707f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
478807f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
478907f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
479007f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
479107f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
479207f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
479307f07615SPaolo Bonzini          * mode.
479407f07615SPaolo Bonzini          *
479507f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
479607f07615SPaolo Bonzini          */
479729cdb251SPaolo Bonzini         ret = 0;
479807f07615SPaolo Bonzini     }
479929cdb251SPaolo Bonzini     if (ret < 0) {
480029cdb251SPaolo Bonzini         return ret;
480129cdb251SPaolo Bonzini     }
480229cdb251SPaolo Bonzini 
480329cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
480429cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
480529cdb251SPaolo Bonzini      */
4806d4c82329SKevin Wolf flush_parent:
480729cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
480807f07615SPaolo Bonzini }
480907f07615SPaolo Bonzini 
48100f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
48110f15423cSAnthony Liguori {
48120f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
48130f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
48140f15423cSAnthony Liguori     }
48150f15423cSAnthony Liguori }
48160f15423cSAnthony Liguori 
48170f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
48180f15423cSAnthony Liguori {
48190f15423cSAnthony Liguori     BlockDriverState *bs;
48200f15423cSAnthony Liguori 
4821dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
48220f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
48230f15423cSAnthony Liguori     }
48240f15423cSAnthony Liguori }
48250f15423cSAnthony Liguori 
482607789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
482707789269SBenoît Canet {
482807789269SBenoît Canet     BlockDriverState *bs;
482907789269SBenoît Canet 
4830dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
483107789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
483207789269SBenoît Canet     }
483307789269SBenoît Canet }
483407789269SBenoît Canet 
483507f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
483607f07615SPaolo Bonzini {
483707f07615SPaolo Bonzini     Coroutine *co;
483807f07615SPaolo Bonzini     RwCo rwco = {
483907f07615SPaolo Bonzini         .bs = bs,
484007f07615SPaolo Bonzini         .ret = NOT_DONE,
484107f07615SPaolo Bonzini     };
484207f07615SPaolo Bonzini 
484307f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
484407f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
484507f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
484607f07615SPaolo Bonzini     } else {
484707f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
484807f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
484907f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
485007f07615SPaolo Bonzini             qemu_aio_wait();
485107f07615SPaolo Bonzini         }
485207f07615SPaolo Bonzini     }
485307f07615SPaolo Bonzini 
485407f07615SPaolo Bonzini     return rwco.ret;
485507f07615SPaolo Bonzini }
4856e7a8a783SKevin Wolf 
4857*775aa8b6SKevin Wolf typedef struct DiscardCo {
4858*775aa8b6SKevin Wolf     BlockDriverState *bs;
4859*775aa8b6SKevin Wolf     int64_t sector_num;
4860*775aa8b6SKevin Wolf     int nb_sectors;
4861*775aa8b6SKevin Wolf     int ret;
4862*775aa8b6SKevin Wolf } DiscardCo;
48634265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
48644265d620SPaolo Bonzini {
4865*775aa8b6SKevin Wolf     DiscardCo *rwco = opaque;
48664265d620SPaolo Bonzini 
48674265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
48684265d620SPaolo Bonzini }
48694265d620SPaolo Bonzini 
48706f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
48716f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
48726f14da52SPeter Lieven  */
48736f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
48746f14da52SPeter Lieven 
48754265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
48764265d620SPaolo Bonzini                                  int nb_sectors)
48774265d620SPaolo Bonzini {
4878d51e9fe5SPaolo Bonzini     int max_discard;
4879d51e9fe5SPaolo Bonzini 
48804265d620SPaolo Bonzini     if (!bs->drv) {
48814265d620SPaolo Bonzini         return -ENOMEDIUM;
48824265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
48834265d620SPaolo Bonzini         return -EIO;
48844265d620SPaolo Bonzini     } else if (bs->read_only) {
48854265d620SPaolo Bonzini         return -EROFS;
4886df702c9bSPaolo Bonzini     }
4887df702c9bSPaolo Bonzini 
48888f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
4889df702c9bSPaolo Bonzini 
48909e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
48919e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
48929e8f1835SPaolo Bonzini         return 0;
48939e8f1835SPaolo Bonzini     }
48949e8f1835SPaolo Bonzini 
4895d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
4896d51e9fe5SPaolo Bonzini         return 0;
4897d51e9fe5SPaolo Bonzini     }
48986f14da52SPeter Lieven 
4899d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
49006f14da52SPeter Lieven     while (nb_sectors > 0) {
49016f14da52SPeter Lieven         int ret;
49026f14da52SPeter Lieven         int num = nb_sectors;
49036f14da52SPeter Lieven 
49046f14da52SPeter Lieven         /* align request */
49056f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
49066f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
49076f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
49086f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
49096f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
49106f14da52SPeter Lieven             }
49116f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
49126f14da52SPeter Lieven         }
49136f14da52SPeter Lieven 
49146f14da52SPeter Lieven         /* limit request size */
49156f14da52SPeter Lieven         if (num > max_discard) {
49166f14da52SPeter Lieven             num = max_discard;
49176f14da52SPeter Lieven         }
49186f14da52SPeter Lieven 
4919d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
49206f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
4921d51e9fe5SPaolo Bonzini         } else {
49224265d620SPaolo Bonzini             BlockDriverAIOCB *acb;
49234265d620SPaolo Bonzini             CoroutineIOCompletion co = {
49244265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
49254265d620SPaolo Bonzini             };
49264265d620SPaolo Bonzini 
49274265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
49284265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
49294265d620SPaolo Bonzini             if (acb == NULL) {
49304265d620SPaolo Bonzini                 return -EIO;
49314265d620SPaolo Bonzini             } else {
49324265d620SPaolo Bonzini                 qemu_coroutine_yield();
4933d51e9fe5SPaolo Bonzini                 ret = co.ret;
49344265d620SPaolo Bonzini             }
4935d51e9fe5SPaolo Bonzini         }
49367ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
4937d51e9fe5SPaolo Bonzini             return ret;
4938d51e9fe5SPaolo Bonzini         }
4939d51e9fe5SPaolo Bonzini 
4940d51e9fe5SPaolo Bonzini         sector_num += num;
4941d51e9fe5SPaolo Bonzini         nb_sectors -= num;
4942d51e9fe5SPaolo Bonzini     }
49434265d620SPaolo Bonzini     return 0;
49444265d620SPaolo Bonzini }
49454265d620SPaolo Bonzini 
49464265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
49474265d620SPaolo Bonzini {
49484265d620SPaolo Bonzini     Coroutine *co;
4949*775aa8b6SKevin Wolf     DiscardCo rwco = {
49504265d620SPaolo Bonzini         .bs = bs,
49514265d620SPaolo Bonzini         .sector_num = sector_num,
49524265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
49534265d620SPaolo Bonzini         .ret = NOT_DONE,
49544265d620SPaolo Bonzini     };
49554265d620SPaolo Bonzini 
49564265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
49574265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
49584265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
49594265d620SPaolo Bonzini     } else {
49604265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
49614265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
49624265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
49634265d620SPaolo Bonzini             qemu_aio_wait();
49644265d620SPaolo Bonzini         }
49654265d620SPaolo Bonzini     }
49664265d620SPaolo Bonzini 
49674265d620SPaolo Bonzini     return rwco.ret;
49684265d620SPaolo Bonzini }
49694265d620SPaolo Bonzini 
4970f9f05dc5SKevin Wolf /**************************************************************/
497119cb3738Sbellard /* removable device support */
497219cb3738Sbellard 
497319cb3738Sbellard /**
497419cb3738Sbellard  * Return TRUE if the media is present
497519cb3738Sbellard  */
497619cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
497719cb3738Sbellard {
497819cb3738Sbellard     BlockDriver *drv = bs->drv;
4979a1aff5bfSMarkus Armbruster 
498019cb3738Sbellard     if (!drv)
498119cb3738Sbellard         return 0;
498219cb3738Sbellard     if (!drv->bdrv_is_inserted)
4983a1aff5bfSMarkus Armbruster         return 1;
4984a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
498519cb3738Sbellard }
498619cb3738Sbellard 
498719cb3738Sbellard /**
49888e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
49898e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
499019cb3738Sbellard  */
499119cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
499219cb3738Sbellard {
499319cb3738Sbellard     BlockDriver *drv = bs->drv;
499419cb3738Sbellard 
49958e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
49968e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
49978e49ca46SMarkus Armbruster     }
49988e49ca46SMarkus Armbruster     return -ENOTSUP;
499919cb3738Sbellard }
500019cb3738Sbellard 
500119cb3738Sbellard /**
500219cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
500319cb3738Sbellard  */
5004f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
500519cb3738Sbellard {
500619cb3738Sbellard     BlockDriver *drv = bs->drv;
500719cb3738Sbellard 
5008822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
5009822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
501019cb3738Sbellard     }
50116f382ed2SLuiz Capitulino 
50126f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
50136f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
50146f382ed2SLuiz Capitulino     }
501519cb3738Sbellard }
501619cb3738Sbellard 
501719cb3738Sbellard /**
501819cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
501919cb3738Sbellard  * to eject it manually).
502019cb3738Sbellard  */
5021025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
502219cb3738Sbellard {
502319cb3738Sbellard     BlockDriver *drv = bs->drv;
502419cb3738Sbellard 
5025025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
5026b8c6d095SStefan Hajnoczi 
5027025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
5028025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
502919cb3738Sbellard     }
503019cb3738Sbellard }
5031985a03b0Sths 
5032985a03b0Sths /* needed for generic scsi interface */
5033985a03b0Sths 
5034985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
5035985a03b0Sths {
5036985a03b0Sths     BlockDriver *drv = bs->drv;
5037985a03b0Sths 
5038985a03b0Sths     if (drv && drv->bdrv_ioctl)
5039985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
5040985a03b0Sths     return -ENOTSUP;
5041985a03b0Sths }
50427d780669Saliguori 
5043221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
5044221f715dSaliguori         unsigned long int req, void *buf,
50457d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
50467d780669Saliguori {
5047221f715dSaliguori     BlockDriver *drv = bs->drv;
50487d780669Saliguori 
5049221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
5050221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
5051221f715dSaliguori     return NULL;
50527d780669Saliguori }
5053e268ca52Saliguori 
50541b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
50557b6f9300SMarkus Armbruster {
50561b7fd729SPaolo Bonzini     bs->guest_block_size = align;
50577b6f9300SMarkus Armbruster }
50587cd1e32aSlirans@il.ibm.com 
5059e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
5060e268ca52Saliguori {
5061339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
5062e268ca52Saliguori }
50637cd1e32aSlirans@il.ibm.com 
5064c53b1c51SStefan Hajnoczi /*
5065c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
5066c53b1c51SStefan Hajnoczi  */
5067c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5068c53b1c51SStefan Hajnoczi {
5069c53b1c51SStefan Hajnoczi     int i;
5070339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
5071c53b1c51SStefan Hajnoczi 
5072c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
5073339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
5074c53b1c51SStefan Hajnoczi             return false;
5075c53b1c51SStefan Hajnoczi         }
5076339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
50771ff735bdSKevin Wolf             return false;
50781ff735bdSKevin Wolf         }
5079c53b1c51SStefan Hajnoczi     }
5080c53b1c51SStefan Hajnoczi 
5081c53b1c51SStefan Hajnoczi     return true;
5082c53b1c51SStefan Hajnoczi }
5083c53b1c51SStefan Hajnoczi 
5084e4654d2dSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity)
50857cd1e32aSlirans@il.ibm.com {
50867cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
5087e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5088a55eb92cSJan Kiszka 
508950717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
509050717e94SPaolo Bonzini 
509150717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
5092e4654d2dSFam Zheng     assert(granularity);
50938f0720ecSPaolo Bonzini     bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
5094e4654d2dSFam Zheng     bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
5095e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5096e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5097e4654d2dSFam Zheng     return bitmap;
5098e4654d2dSFam Zheng }
5099e4654d2dSFam Zheng 
5100e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5101e4654d2dSFam Zheng {
5102e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
5103e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5104e4654d2dSFam Zheng         if (bm == bitmap) {
5105e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
5106e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
5107e4654d2dSFam Zheng             g_free(bitmap);
5108e4654d2dSFam Zheng             return;
51097cd1e32aSlirans@il.ibm.com         }
51107cd1e32aSlirans@il.ibm.com     }
51117cd1e32aSlirans@il.ibm.com }
51127cd1e32aSlirans@il.ibm.com 
511321b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
511421b56835SFam Zheng {
511521b56835SFam Zheng     BdrvDirtyBitmap *bm;
511621b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
511721b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
511821b56835SFam Zheng 
511921b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
512021b56835SFam Zheng         BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
512121b56835SFam Zheng         BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
512221b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
512321b56835SFam Zheng         info->granularity =
512421b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
512521b56835SFam Zheng         entry->value = info;
512621b56835SFam Zheng         *plist = entry;
512721b56835SFam Zheng         plist = &entry->next;
512821b56835SFam Zheng     }
512921b56835SFam Zheng 
513021b56835SFam Zheng     return list;
513121b56835SFam Zheng }
513221b56835SFam Zheng 
5133e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
51347cd1e32aSlirans@il.ibm.com {
5135e4654d2dSFam Zheng     if (bitmap) {
5136e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
51377cd1e32aSlirans@il.ibm.com     } else {
51387cd1e32aSlirans@il.ibm.com         return 0;
51397cd1e32aSlirans@il.ibm.com     }
51407cd1e32aSlirans@il.ibm.com }
51417cd1e32aSlirans@il.ibm.com 
5142e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
5143e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
51441755da16SPaolo Bonzini {
5145e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
51461755da16SPaolo Bonzini }
51471755da16SPaolo Bonzini 
51481755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
51491755da16SPaolo Bonzini                     int nr_sectors)
51501755da16SPaolo Bonzini {
5151e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5152e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5153e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5154e4654d2dSFam Zheng     }
51551755da16SPaolo Bonzini }
51561755da16SPaolo Bonzini 
5157e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
51587cd1e32aSlirans@il.ibm.com {
5159e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5160e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5161e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5162e4654d2dSFam Zheng     }
51637cd1e32aSlirans@il.ibm.com }
5164aaa0eb75SLiran Schour 
5165e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5166aaa0eb75SLiran Schour {
5167e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
5168aaa0eb75SLiran Schour }
5169f88e1a42SJes Sorensen 
51709fcb0251SFam Zheng /* Get a reference to bs */
51719fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
51729fcb0251SFam Zheng {
51739fcb0251SFam Zheng     bs->refcnt++;
51749fcb0251SFam Zheng }
51759fcb0251SFam Zheng 
51769fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
51779fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
51789fcb0251SFam Zheng  * deleted. */
51799fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
51809fcb0251SFam Zheng {
51819fcb0251SFam Zheng     assert(bs->refcnt > 0);
51829fcb0251SFam Zheng     if (--bs->refcnt == 0) {
51839fcb0251SFam Zheng         bdrv_delete(bs);
51849fcb0251SFam Zheng     }
51859fcb0251SFam Zheng }
51869fcb0251SFam Zheng 
5187db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
5188db593f25SMarcelo Tosatti {
5189db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
5190db593f25SMarcelo Tosatti     bs->in_use = in_use;
5191db593f25SMarcelo Tosatti }
5192db593f25SMarcelo Tosatti 
5193db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
5194db593f25SMarcelo Tosatti {
5195db593f25SMarcelo Tosatti     return bs->in_use;
5196db593f25SMarcelo Tosatti }
5197db593f25SMarcelo Tosatti 
519828a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
519928a7282aSLuiz Capitulino {
5200d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
520158e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
520228a7282aSLuiz Capitulino }
520328a7282aSLuiz Capitulino 
520428a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
520528a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
520628a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
520728a7282aSLuiz Capitulino {
5208d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
520992aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
521092aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
521192aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
521228a7282aSLuiz Capitulino }
521328a7282aSLuiz Capitulino 
521428a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
521528a7282aSLuiz Capitulino {
5216d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
521728a7282aSLuiz Capitulino }
521828a7282aSLuiz Capitulino 
521928a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
522028a7282aSLuiz Capitulino {
522128a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
522258e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
52233bd293c3SPaolo Bonzini         if (bs->job) {
52243bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
52253bd293c3SPaolo Bonzini         }
522628a7282aSLuiz Capitulino     }
522728a7282aSLuiz Capitulino }
522828a7282aSLuiz Capitulino 
522928a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
523028a7282aSLuiz Capitulino {
52313e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
52323e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
523358e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
523458e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
523528a7282aSLuiz Capitulino     }
523628a7282aSLuiz Capitulino }
523728a7282aSLuiz Capitulino 
5238a597e79cSChristoph Hellwig void
5239a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
5240a597e79cSChristoph Hellwig         enum BlockAcctType type)
5241a597e79cSChristoph Hellwig {
5242a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
5243a597e79cSChristoph Hellwig 
5244a597e79cSChristoph Hellwig     cookie->bytes = bytes;
5245c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
5246a597e79cSChristoph Hellwig     cookie->type = type;
5247a597e79cSChristoph Hellwig }
5248a597e79cSChristoph Hellwig 
5249a597e79cSChristoph Hellwig void
5250a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
5251a597e79cSChristoph Hellwig {
5252a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
5253a597e79cSChristoph Hellwig 
5254a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
5255a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
5256c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
5257a597e79cSChristoph Hellwig }
5258a597e79cSChristoph Hellwig 
5259d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5260f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5261f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5262f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5263f88e1a42SJes Sorensen {
5264f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
5265d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
5266f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
526796df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5268cc84d90fSMax Reitz     Error *local_err = NULL;
5269f88e1a42SJes Sorensen     int ret = 0;
5270f88e1a42SJes Sorensen 
5271f88e1a42SJes Sorensen     /* Find driver and parse its options */
5272f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5273f88e1a42SJes Sorensen     if (!drv) {
527471c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5275d92ada22SLuiz Capitulino         return;
5276f88e1a42SJes Sorensen     }
5277f88e1a42SJes Sorensen 
527898289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5279f88e1a42SJes Sorensen     if (!proto_drv) {
528071c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5281d92ada22SLuiz Capitulino         return;
5282f88e1a42SJes Sorensen     }
5283f88e1a42SJes Sorensen 
5284f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5285f88e1a42SJes Sorensen                                               drv->create_options);
5286f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5287f88e1a42SJes Sorensen                                               proto_drv->create_options);
5288f88e1a42SJes Sorensen 
5289f88e1a42SJes Sorensen     /* Create parameter list with default values */
5290f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
5291f88e1a42SJes Sorensen 
5292f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
5293f88e1a42SJes Sorensen 
5294f88e1a42SJes Sorensen     /* Parse -o options */
5295f88e1a42SJes Sorensen     if (options) {
5296f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
5297f88e1a42SJes Sorensen         if (param == NULL) {
529871c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
5299f88e1a42SJes Sorensen             goto out;
5300f88e1a42SJes Sorensen         }
5301f88e1a42SJes Sorensen     }
5302f88e1a42SJes Sorensen 
5303f88e1a42SJes Sorensen     if (base_filename) {
5304f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
5305f88e1a42SJes Sorensen                                  base_filename)) {
530671c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
530771c79813SLuiz Capitulino                        fmt);
5308f88e1a42SJes Sorensen             goto out;
5309f88e1a42SJes Sorensen         }
5310f88e1a42SJes Sorensen     }
5311f88e1a42SJes Sorensen 
5312f88e1a42SJes Sorensen     if (base_fmt) {
5313f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
531471c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
531571c79813SLuiz Capitulino                              "format '%s'", fmt);
5316f88e1a42SJes Sorensen             goto out;
5317f88e1a42SJes Sorensen         }
5318f88e1a42SJes Sorensen     }
5319f88e1a42SJes Sorensen 
5320792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
5321792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
5322792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
532371c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
532471c79813SLuiz Capitulino                              "same filename as the backing file");
5325792da93aSJes Sorensen             goto out;
5326792da93aSJes Sorensen         }
5327792da93aSJes Sorensen     }
5328792da93aSJes Sorensen 
5329f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
5330f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
533196df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
533296df67d1SStefan Hajnoczi         if (!backing_drv) {
533371c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
533471c79813SLuiz Capitulino                        backing_fmt->value.s);
5335f88e1a42SJes Sorensen             goto out;
5336f88e1a42SJes Sorensen         }
5337f88e1a42SJes Sorensen     }
5338f88e1a42SJes Sorensen 
5339f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5340f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
5341d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
5342d220894eSKevin Wolf     if (size && size->value.n == -1) {
5343f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
534466f6b814SMax Reitz             BlockDriverState *bs;
5345f88e1a42SJes Sorensen             uint64_t size;
5346f88e1a42SJes Sorensen             char buf[32];
534763090dacSPaolo Bonzini             int back_flags;
534863090dacSPaolo Bonzini 
534963090dacSPaolo Bonzini             /* backing files always opened read-only */
535063090dacSPaolo Bonzini             back_flags =
535163090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5352f88e1a42SJes Sorensen 
5353f88e1a42SJes Sorensen             bs = bdrv_new("");
5354f88e1a42SJes Sorensen 
5355de9c0cecSKevin Wolf             ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
5356cc84d90fSMax Reitz                             backing_drv, &local_err);
5357f88e1a42SJes Sorensen             if (ret < 0) {
5358cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
5359cc84d90fSMax Reitz                                  backing_file->value.s,
5360cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5361cc84d90fSMax Reitz                 error_free(local_err);
5362cc84d90fSMax Reitz                 local_err = NULL;
536366f6b814SMax Reitz                 bdrv_unref(bs);
5364f88e1a42SJes Sorensen                 goto out;
5365f88e1a42SJes Sorensen             }
5366f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
5367f88e1a42SJes Sorensen             size *= 512;
5368f88e1a42SJes Sorensen 
5369f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
5370f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
537166f6b814SMax Reitz 
537266f6b814SMax Reitz             bdrv_unref(bs);
5373f88e1a42SJes Sorensen         } else {
537471c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5375f88e1a42SJes Sorensen             goto out;
5376f88e1a42SJes Sorensen         }
5377f88e1a42SJes Sorensen     }
5378f88e1a42SJes Sorensen 
5379f382d43aSMiroslav Rezanina     if (!quiet) {
5380f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
5381f88e1a42SJes Sorensen         print_option_parameters(param);
5382f88e1a42SJes Sorensen         puts("");
5383f382d43aSMiroslav Rezanina     }
5384cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, param, &local_err);
5385cc84d90fSMax Reitz     if (ret == -EFBIG) {
5386cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5387cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5388cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5389f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
5390f3f4d2c0SKevin Wolf         if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
5391f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5392f3f4d2c0SKevin Wolf         }
5393cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5394cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5395cc84d90fSMax Reitz         error_free(local_err);
5396cc84d90fSMax Reitz         local_err = NULL;
5397f88e1a42SJes Sorensen     }
5398f88e1a42SJes Sorensen 
5399f88e1a42SJes Sorensen out:
5400f88e1a42SJes Sorensen     free_option_parameters(create_options);
5401f88e1a42SJes Sorensen     free_option_parameters(param);
5402f88e1a42SJes Sorensen 
5403cc84d90fSMax Reitz     if (error_is_set(&local_err)) {
5404cc84d90fSMax Reitz         error_propagate(errp, local_err);
5405cc84d90fSMax Reitz     }
5406f88e1a42SJes Sorensen }
540785d126f3SStefan Hajnoczi 
540885d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
540985d126f3SStefan Hajnoczi {
541085d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
541185d126f3SStefan Hajnoczi     return qemu_get_aio_context();
541285d126f3SStefan Hajnoczi }
5413d616b224SStefan Hajnoczi 
5414d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5415d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5416d616b224SStefan Hajnoczi {
5417d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5418d616b224SStefan Hajnoczi }
54196f176b48SMax Reitz 
54206f176b48SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
54216f176b48SMax Reitz {
54226f176b48SMax Reitz     if (bs->drv->bdrv_amend_options == NULL) {
54236f176b48SMax Reitz         return -ENOTSUP;
54246f176b48SMax Reitz     }
54256f176b48SMax Reitz     return bs->drv->bdrv_amend_options(bs, options);
54266f176b48SMax Reitz }
5427f6186f49SBenoît Canet 
5428212a5a8fSBenoît Canet /* Used to recurse on single child block filters.
5429212a5a8fSBenoît Canet  * Single child block filter will store their child in bs->file.
5430212a5a8fSBenoît Canet  */
5431212a5a8fSBenoît Canet bool bdrv_generic_is_first_non_filter(BlockDriverState *bs,
5432212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5433f6186f49SBenoît Canet {
5434212a5a8fSBenoît Canet     if (!bs->drv) {
5435212a5a8fSBenoît Canet         return false;
5436f6186f49SBenoît Canet     }
5437f6186f49SBenoît Canet 
5438212a5a8fSBenoît Canet     if (!bs->drv->authorizations[BS_IS_A_FILTER]) {
5439212a5a8fSBenoît Canet         if (bs == candidate) {
5440212a5a8fSBenoît Canet             return true;
5441212a5a8fSBenoît Canet         } else {
5442212a5a8fSBenoît Canet             return false;
5443212a5a8fSBenoît Canet         }
5444f6186f49SBenoît Canet     }
5445f6186f49SBenoît Canet 
5446212a5a8fSBenoît Canet     if (!bs->drv->authorizations[BS_FILTER_PASS_DOWN]) {
5447212a5a8fSBenoît Canet         return false;
5448f6186f49SBenoît Canet     }
5449f6186f49SBenoît Canet 
5450212a5a8fSBenoît Canet     if (!bs->file) {
5451212a5a8fSBenoît Canet         return false;
5452212a5a8fSBenoît Canet     }
5453212a5a8fSBenoît Canet 
5454212a5a8fSBenoît Canet     return bdrv_recurse_is_first_non_filter(bs->file, candidate);
5455212a5a8fSBenoît Canet }
5456212a5a8fSBenoît Canet 
5457212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5458212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5459f6186f49SBenoît Canet {
5460212a5a8fSBenoît Canet     if (bs->drv && bs->drv->bdrv_recurse_is_first_non_filter) {
5461212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5462212a5a8fSBenoît Canet     }
5463212a5a8fSBenoît Canet 
5464212a5a8fSBenoît Canet     return bdrv_generic_is_first_non_filter(bs, candidate);
5465212a5a8fSBenoît Canet }
5466212a5a8fSBenoît Canet 
5467212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5468212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5469212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5470212a5a8fSBenoît Canet  */
5471212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5472212a5a8fSBenoît Canet {
5473212a5a8fSBenoît Canet     BlockDriverState *bs;
5474212a5a8fSBenoît Canet 
5475212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5476212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5477212a5a8fSBenoît Canet         bool perm;
5478212a5a8fSBenoît Canet 
5479212a5a8fSBenoît Canet         if (!bs->file) {
5480212a5a8fSBenoît Canet             continue;
5481212a5a8fSBenoît Canet         }
5482212a5a8fSBenoît Canet 
5483212a5a8fSBenoît Canet         perm = bdrv_recurse_is_first_non_filter(bs->file, candidate);
5484212a5a8fSBenoît Canet 
5485212a5a8fSBenoît Canet         /* candidate is the first non filter */
5486212a5a8fSBenoît Canet         if (perm) {
5487212a5a8fSBenoît Canet             return true;
5488212a5a8fSBenoît Canet         }
5489212a5a8fSBenoît Canet     }
5490212a5a8fSBenoît Canet 
5491212a5a8fSBenoît Canet     return false;
5492f6186f49SBenoît Canet }
5493