xref: /openbmc/qemu/block.c (revision 339064d5063924e5176842abbf6c8089f3479c5b)
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);
73c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
74470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
75470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
761c9805a3SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
77f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, 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 
221*339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
222*339064d5SKevin Wolf {
223*339064d5SKevin Wolf     if (!bs || !bs->drv) {
224*339064d5SKevin Wolf         /* 4k should be on the safe side */
225*339064d5SKevin Wolf         return 4096;
226*339064d5SKevin Wolf     }
227*339064d5SKevin Wolf 
228*339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
229*339064d5SKevin Wolf }
230*339064d5SKevin 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;
510*339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
511*339064d5SKevin Wolf     } else {
512*339064d5SKevin 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);
520*339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
521*339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
522*339064d5SKevin 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;
85457915332SKevin Wolf     bs->buffer_alignment = 512;
8550d51b4deSAsias He     bs->zero_beyond_eof = true;
856b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
857b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
858b64ec4e4SFam Zheng 
859b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8608f94a6e4SKevin Wolf         error_setg(errp,
8618f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8628f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8638f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8648f94a6e4SKevin Wolf                    drv->format_name);
865b64ec4e4SFam Zheng         return -ENOTSUP;
866b64ec4e4SFam Zheng     }
86757915332SKevin Wolf 
86853fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8690ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8700ebd24e0SKevin Wolf         if (!bs->read_only) {
87153fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8720ebd24e0SKevin Wolf         } else {
8730ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
8740ebd24e0SKevin Wolf             return -EINVAL;
8750ebd24e0SKevin Wolf         }
87653fec9d3SStefan Hajnoczi     }
87753fec9d3SStefan Hajnoczi 
878c2ad1b0cSKevin Wolf     if (filename != NULL) {
87957915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
880c2ad1b0cSKevin Wolf     } else {
881c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
882c2ad1b0cSKevin Wolf     }
88357915332SKevin Wolf 
88457915332SKevin Wolf     bs->drv = drv;
8857267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
88657915332SKevin Wolf 
88703f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
888e7c63796SStefan Hajnoczi 
88966f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
89066f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
8915d186eb0SKevin Wolf         assert(file == NULL);
892030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
89334b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
894f500a6d3SKevin Wolf     } else {
8952af5ef70SKevin Wolf         if (file == NULL) {
89634b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
89734b5d2c6SMax Reitz                        "protocol level", drv->format_name);
8982af5ef70SKevin Wolf             ret = -EINVAL;
8992af5ef70SKevin Wolf             goto free_and_fail;
9002af5ef70SKevin Wolf         }
901f500a6d3SKevin Wolf         bs->file = file;
90234b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
90366f82ceeSKevin Wolf     }
90466f82ceeSKevin Wolf 
90557915332SKevin Wolf     if (ret < 0) {
90634b5d2c6SMax Reitz         if (error_is_set(&local_err)) {
90734b5d2c6SMax Reitz             error_propagate(errp, local_err);
9082fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9092fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
91034b5d2c6SMax Reitz         } else {
91134b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
91234b5d2c6SMax Reitz         }
91357915332SKevin Wolf         goto free_and_fail;
91457915332SKevin Wolf     }
91557915332SKevin Wolf 
91651762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
91751762288SStefan Hajnoczi     if (ret < 0) {
91834b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
91951762288SStefan Hajnoczi         goto free_and_fail;
92057915332SKevin Wolf     }
92151762288SStefan Hajnoczi 
922d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
923d34682cdSKevin Wolf 
92457915332SKevin Wolf #ifndef _WIN32
92557915332SKevin Wolf     if (bs->is_temporary) {
926d4cea8dfSDunrong Huang         assert(bs->filename[0] != '\0');
927d4cea8dfSDunrong Huang         unlink(bs->filename);
92857915332SKevin Wolf     }
92957915332SKevin Wolf #endif
93057915332SKevin Wolf     return 0;
93157915332SKevin Wolf 
93257915332SKevin Wolf free_and_fail:
93366f82ceeSKevin Wolf     bs->file = NULL;
9347267c094SAnthony Liguori     g_free(bs->opaque);
93557915332SKevin Wolf     bs->opaque = NULL;
93657915332SKevin Wolf     bs->drv = NULL;
93757915332SKevin Wolf     return ret;
93857915332SKevin Wolf }
93957915332SKevin Wolf 
94057915332SKevin Wolf /*
941b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
942787e4a85SKevin Wolf  *
943787e4a85SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
944787e4a85SKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
945787e4a85SKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
946787e4a85SKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
947b6ce07aaSKevin Wolf  */
948787e4a85SKevin Wolf int bdrv_file_open(BlockDriverState **pbs, const char *filename,
94972daa72eSMax Reitz                    const char *reference, QDict *options, int flags,
95072daa72eSMax Reitz                    Error **errp)
951b338082bSbellard {
95272daa72eSMax Reitz     BlockDriverState *bs = NULL;
9536db95603SChristoph Hellwig     BlockDriver *drv;
954c2ad1b0cSKevin Wolf     const char *drvname;
95598289620SKevin Wolf     bool allow_protocol_prefix = false;
95634b5d2c6SMax Reitz     Error *local_err = NULL;
95783f64091Sbellard     int ret;
9583b0d4f61Sbellard 
959707ff828SKevin Wolf     /* NULL means an empty set of options */
960707ff828SKevin Wolf     if (options == NULL) {
961707ff828SKevin Wolf         options = qdict_new();
9623b0d4f61Sbellard     }
963707ff828SKevin Wolf 
96472daa72eSMax Reitz     if (reference) {
96572daa72eSMax Reitz         if (filename || qdict_size(options)) {
96672daa72eSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
96772daa72eSMax Reitz                        "additional options or a new filename");
96872daa72eSMax Reitz             return -EINVAL;
96972daa72eSMax Reitz         }
97072daa72eSMax Reitz         QDECREF(options);
97172daa72eSMax Reitz 
97272daa72eSMax Reitz         bs = bdrv_find(reference);
97372daa72eSMax Reitz         if (!bs) {
97472daa72eSMax Reitz             error_setg(errp, "Cannot find block device '%s'", reference);
97572daa72eSMax Reitz             return -ENODEV;
97672daa72eSMax Reitz         }
97772daa72eSMax Reitz         bdrv_ref(bs);
97872daa72eSMax Reitz         *pbs = bs;
97972daa72eSMax Reitz         return 0;
98072daa72eSMax Reitz     }
98172daa72eSMax Reitz 
982707ff828SKevin Wolf     bs = bdrv_new("");
983707ff828SKevin Wolf     bs->options = options;
984707ff828SKevin Wolf     options = qdict_clone_shallow(options);
985707ff828SKevin Wolf 
986035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
987035fccdfSKevin Wolf     if (!filename) {
988035fccdfSKevin Wolf         filename = qdict_get_try_str(options, "filename");
989035fccdfSKevin Wolf     } else if (filename && !qdict_haskey(options, "filename")) {
990035fccdfSKevin Wolf         qdict_put(options, "filename", qstring_from_str(filename));
99198289620SKevin Wolf         allow_protocol_prefix = true;
992035fccdfSKevin Wolf     } else {
99334b5d2c6SMax Reitz         error_setg(errp, "Can't specify 'file' and 'filename' options at the "
99434b5d2c6SMax Reitz                    "same time");
995035fccdfSKevin Wolf         ret = -EINVAL;
996035fccdfSKevin Wolf         goto fail;
997035fccdfSKevin Wolf     }
998035fccdfSKevin Wolf 
999c2ad1b0cSKevin Wolf     /* Find the right block driver */
1000c2ad1b0cSKevin Wolf     drvname = qdict_get_try_str(options, "driver");
1001c2ad1b0cSKevin Wolf     if (drvname) {
10028f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
100334b5d2c6SMax Reitz         if (!drv) {
100434b5d2c6SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
100534b5d2c6SMax Reitz         }
1006c2ad1b0cSKevin Wolf         qdict_del(options, "driver");
1007c2ad1b0cSKevin Wolf     } else if (filename) {
100898289620SKevin Wolf         drv = bdrv_find_protocol(filename, allow_protocol_prefix);
100998289620SKevin Wolf         if (!drv) {
101034b5d2c6SMax Reitz             error_setg(errp, "Unknown protocol");
101198289620SKevin Wolf         }
1012c2ad1b0cSKevin Wolf     } else {
101334b5d2c6SMax Reitz         error_setg(errp, "Must specify either driver or file");
1014c2ad1b0cSKevin Wolf         drv = NULL;
1015c2ad1b0cSKevin Wolf     }
1016c2ad1b0cSKevin Wolf 
1017c2ad1b0cSKevin Wolf     if (!drv) {
101834b5d2c6SMax Reitz         /* errp has been set already */
1019c2ad1b0cSKevin Wolf         ret = -ENOENT;
1020c2ad1b0cSKevin Wolf         goto fail;
1021c2ad1b0cSKevin Wolf     }
1022c2ad1b0cSKevin Wolf 
1023c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
1024c2ad1b0cSKevin Wolf     if (drv->bdrv_parse_filename && filename) {
10256963a30dSKevin Wolf         drv->bdrv_parse_filename(filename, options, &local_err);
10266963a30dSKevin Wolf         if (error_is_set(&local_err)) {
102734b5d2c6SMax Reitz             error_propagate(errp, local_err);
10286963a30dSKevin Wolf             ret = -EINVAL;
10296963a30dSKevin Wolf             goto fail;
10306963a30dSKevin Wolf         }
103156d1b4d2SKevin Wolf         qdict_del(options, "filename");
1032030be321SBenoît Canet     } else if (drv->bdrv_needs_filename && !filename) {
103334b5d2c6SMax Reitz         error_setg(errp, "The '%s' block driver requires a file name",
1034c2ad1b0cSKevin Wolf                    drv->format_name);
1035c2ad1b0cSKevin Wolf         ret = -EINVAL;
1036c2ad1b0cSKevin Wolf         goto fail;
10376963a30dSKevin Wolf     }
10386963a30dSKevin Wolf 
1039505d7583SMax Reitz     if (!drv->bdrv_file_open) {
1040505d7583SMax Reitz         ret = bdrv_open(bs, filename, options, flags, drv, &local_err);
1041505d7583SMax Reitz         options = NULL;
1042505d7583SMax Reitz     } else {
104334b5d2c6SMax Reitz         ret = bdrv_open_common(bs, NULL, options, flags, drv, &local_err);
1044505d7583SMax Reitz     }
1045707ff828SKevin Wolf     if (ret < 0) {
104634b5d2c6SMax Reitz         error_propagate(errp, local_err);
1047707ff828SKevin Wolf         goto fail;
1048707ff828SKevin Wolf     }
1049707ff828SKevin Wolf 
1050707ff828SKevin Wolf     /* Check if any unknown options were used */
1051505d7583SMax Reitz     if (options && (qdict_size(options) != 0)) {
1052707ff828SKevin Wolf         const QDictEntry *entry = qdict_first(options);
105334b5d2c6SMax Reitz         error_setg(errp, "Block protocol '%s' doesn't support the option '%s'",
1054707ff828SKevin Wolf                    drv->format_name, entry->key);
1055707ff828SKevin Wolf         ret = -EINVAL;
1056707ff828SKevin Wolf         goto fail;
1057707ff828SKevin Wolf     }
1058707ff828SKevin Wolf     QDECREF(options);
1059707ff828SKevin Wolf 
106071d0770cSaliguori     bs->growable = 1;
106183f64091Sbellard     *pbs = bs;
106283f64091Sbellard     return 0;
1063707ff828SKevin Wolf 
1064707ff828SKevin Wolf fail:
1065707ff828SKevin Wolf     QDECREF(options);
1066707ff828SKevin Wolf     if (!bs->drv) {
1067707ff828SKevin Wolf         QDECREF(bs->options);
1068707ff828SKevin Wolf     }
10694f6fd349SFam Zheng     bdrv_unref(bs);
1070707ff828SKevin Wolf     return ret;
10713b0d4f61Sbellard }
10723b0d4f61Sbellard 
107331ca6d07SKevin Wolf /*
107431ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
107531ca6d07SKevin Wolf  *
107631ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
107731ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
107831ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
107931ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
108031ca6d07SKevin Wolf  */
108134b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
10829156df12SPaolo Bonzini {
10839156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
10849156df12SPaolo Bonzini     int back_flags, ret;
10859156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
108634b5d2c6SMax Reitz     Error *local_err = NULL;
10879156df12SPaolo Bonzini 
10889156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
108931ca6d07SKevin Wolf         QDECREF(options);
10909156df12SPaolo Bonzini         return 0;
10919156df12SPaolo Bonzini     }
10929156df12SPaolo Bonzini 
109331ca6d07SKevin Wolf     /* NULL means an empty set of options */
109431ca6d07SKevin Wolf     if (options == NULL) {
109531ca6d07SKevin Wolf         options = qdict_new();
109631ca6d07SKevin Wolf     }
109731ca6d07SKevin Wolf 
10989156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
10991cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
11001cb6f506SKevin Wolf         backing_filename[0] = '\0';
11011cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
110231ca6d07SKevin Wolf         QDECREF(options);
11039156df12SPaolo Bonzini         return 0;
1104dbecebddSFam Zheng     } else {
1105dbecebddSFam Zheng         bdrv_get_full_backing_filename(bs, backing_filename,
1106dbecebddSFam Zheng                                        sizeof(backing_filename));
11079156df12SPaolo Bonzini     }
11089156df12SPaolo Bonzini 
11099156df12SPaolo Bonzini     bs->backing_hd = bdrv_new("");
11109156df12SPaolo Bonzini 
11119156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
11129156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
11139156df12SPaolo Bonzini     }
11149156df12SPaolo Bonzini 
11159156df12SPaolo Bonzini     /* backing files always opened read-only */
111687a5debdSThibaut LAURENT     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
111787a5debdSThibaut LAURENT                                     BDRV_O_COPY_ON_READ);
11189156df12SPaolo Bonzini 
111931ca6d07SKevin Wolf     ret = bdrv_open(bs->backing_hd,
112031ca6d07SKevin Wolf                     *backing_filename ? backing_filename : NULL, options,
112134b5d2c6SMax Reitz                     back_flags, back_drv, &local_err);
11229156df12SPaolo Bonzini     if (ret < 0) {
11234f6fd349SFam Zheng         bdrv_unref(bs->backing_hd);
11249156df12SPaolo Bonzini         bs->backing_hd = NULL;
11259156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1126b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1127b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1128b04b6b6eSFam Zheng         error_free(local_err);
11299156df12SPaolo Bonzini         return ret;
11309156df12SPaolo Bonzini     }
1131d80ac658SPeter Feiner 
1132d80ac658SPeter Feiner     if (bs->backing_hd->file) {
113361ed2684SMax Reitz         pstrcpy(bs->backing_file, sizeof(bs->backing_file),
113461ed2684SMax Reitz                 bs->backing_hd->file->filename);
1135d80ac658SPeter Feiner     }
1136d80ac658SPeter Feiner 
1137d34682cdSKevin Wolf     /* Recalculate the BlockLimits with the backing file */
1138d34682cdSKevin Wolf     bdrv_refresh_limits(bs);
1139d34682cdSKevin Wolf 
11409156df12SPaolo Bonzini     return 0;
11419156df12SPaolo Bonzini }
11429156df12SPaolo Bonzini 
1143b6ce07aaSKevin Wolf /*
1144da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1145da557aacSMax Reitz  * device's options.
1146da557aacSMax Reitz  *
1147da557aacSMax Reitz  * If force_raw is true, bdrv_file_open() will be used, thereby preventing any
1148da557aacSMax Reitz  * image format auto-detection. If it is false and a filename is given,
1149da557aacSMax Reitz  * bdrv_open() will be used for auto-detection.
1150da557aacSMax Reitz  *
1151da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1152da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1153da557aacSMax Reitz  *
1154da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1155da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1156da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1157da557aacSMax Reitz  * BlockdevRef.
1158da557aacSMax Reitz  *
1159da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1160da557aacSMax Reitz  */
1161da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1162da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1163da557aacSMax Reitz                     bool force_raw, bool allow_none, Error **errp)
1164da557aacSMax Reitz {
1165da557aacSMax Reitz     QDict *image_options;
1166da557aacSMax Reitz     int ret;
1167da557aacSMax Reitz     char *bdref_key_dot;
1168da557aacSMax Reitz     const char *reference;
1169da557aacSMax Reitz 
1170da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1171da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1172da557aacSMax Reitz     g_free(bdref_key_dot);
1173da557aacSMax Reitz 
1174da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1175da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1176da557aacSMax Reitz         if (allow_none) {
1177da557aacSMax Reitz             ret = 0;
1178da557aacSMax Reitz         } else {
1179da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1180da557aacSMax Reitz                        bdref_key);
1181da557aacSMax Reitz             ret = -EINVAL;
1182da557aacSMax Reitz         }
1183da557aacSMax Reitz         goto done;
1184da557aacSMax Reitz     }
1185da557aacSMax Reitz 
1186da557aacSMax Reitz     if (filename && !force_raw) {
1187da557aacSMax Reitz         /* If a filename is given and the block driver should be detected
1188da557aacSMax Reitz            automatically (instead of using none), use bdrv_open() in order to do
1189da557aacSMax Reitz            that auto-detection. */
1190da557aacSMax Reitz         BlockDriverState *bs;
1191da557aacSMax Reitz 
1192da557aacSMax Reitz         if (reference) {
1193da557aacSMax Reitz             error_setg(errp, "Cannot reference an existing block device while "
1194da557aacSMax Reitz                        "giving a filename");
1195da557aacSMax Reitz             ret = -EINVAL;
1196da557aacSMax Reitz             goto done;
1197da557aacSMax Reitz         }
1198da557aacSMax Reitz 
1199da557aacSMax Reitz         bs = bdrv_new("");
1200da557aacSMax Reitz         ret = bdrv_open(bs, filename, image_options, flags, NULL, errp);
1201da557aacSMax Reitz         if (ret < 0) {
1202da557aacSMax Reitz             bdrv_unref(bs);
1203da557aacSMax Reitz         } else {
1204da557aacSMax Reitz             *pbs = bs;
1205da557aacSMax Reitz         }
1206da557aacSMax Reitz     } else {
1207da557aacSMax Reitz         ret = bdrv_file_open(pbs, filename, reference, image_options, flags,
1208da557aacSMax Reitz                              errp);
1209da557aacSMax Reitz     }
1210da557aacSMax Reitz 
1211da557aacSMax Reitz done:
1212da557aacSMax Reitz     qdict_del(options, bdref_key);
1213da557aacSMax Reitz     return ret;
1214da557aacSMax Reitz }
1215da557aacSMax Reitz 
1216da557aacSMax Reitz /*
1217b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1218de9c0cecSKevin Wolf  *
1219de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1220de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1221de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1222de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1223b6ce07aaSKevin Wolf  */
1224de9c0cecSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
122534b5d2c6SMax Reitz               int flags, BlockDriver *drv, Error **errp)
1226ea2384d3Sbellard {
1227b6ce07aaSKevin Wolf     int ret;
122889c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
122989c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
1230f500a6d3SKevin Wolf     BlockDriverState *file = NULL;
123174fe54f2SKevin Wolf     const char *drvname;
123234b5d2c6SMax Reitz     Error *local_err = NULL;
123333e3963eSbellard 
1234de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1235de9c0cecSKevin Wolf     if (options == NULL) {
1236de9c0cecSKevin Wolf         options = qdict_new();
1237de9c0cecSKevin Wolf     }
1238de9c0cecSKevin Wolf 
1239de9c0cecSKevin Wolf     bs->options = options;
1240b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1241de9c0cecSKevin Wolf 
1242de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
124383f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
1244ea2384d3Sbellard         BlockDriverState *bs1;
1245ea2384d3Sbellard         int64_t total_size;
124691a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
124708b392e1SKevin Wolf         QEMUOptionParameter *create_options;
12489fd3171aSKevin Wolf         QDict *snapshot_options;
1249c2ad1b0cSKevin Wolf 
1250ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
1251ea2384d3Sbellard            instead of opening 'filename' directly */
1252ea2384d3Sbellard 
12539fd3171aSKevin Wolf         /* Get the required size from the image */
1254ea2384d3Sbellard         bs1 = bdrv_new("");
12559fd3171aSKevin Wolf         QINCREF(options);
1256c9fbb99dSKevin Wolf         ret = bdrv_open(bs1, filename, options, BDRV_O_NO_BACKING,
1257c9fbb99dSKevin Wolf                         drv, &local_err);
125851d7c00cSaliguori         if (ret < 0) {
12594f6fd349SFam Zheng             bdrv_unref(bs1);
1260de9c0cecSKevin Wolf             goto fail;
1261ea2384d3Sbellard         }
12623e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
12637c96d46eSaliguori 
12644f6fd349SFam Zheng         bdrv_unref(bs1);
1265ea2384d3Sbellard 
12669fd3171aSKevin Wolf         /* Create the temporary image */
1267eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1268eba25057SJim Meyering         if (ret < 0) {
126934b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not get temporary filename");
1270de9c0cecSKevin Wolf             goto fail;
1271eba25057SJim Meyering         }
12727c96d46eSaliguori 
127391a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
127408b392e1SKevin Wolf         create_options = parse_option_parameters("", bdrv_qcow2->create_options,
127508b392e1SKevin Wolf                                                  NULL);
127691a073a9SKevin Wolf 
127708b392e1SKevin Wolf         set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
127891a073a9SKevin Wolf 
1279cc84d90fSMax Reitz         ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
128008b392e1SKevin Wolf         free_option_parameters(create_options);
128151d7c00cSaliguori         if (ret < 0) {
128234b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not create temporary overlay "
1283cc84d90fSMax Reitz                              "'%s': %s", tmp_filename,
1284cc84d90fSMax Reitz                              error_get_pretty(local_err));
1285cc84d90fSMax Reitz             error_free(local_err);
1286cc84d90fSMax Reitz             local_err = NULL;
1287de9c0cecSKevin Wolf             goto fail;
1288ea2384d3Sbellard         }
128991a073a9SKevin Wolf 
12909fd3171aSKevin Wolf         /* Prepare a new options QDict for the temporary file, where user
12919fd3171aSKevin Wolf          * options refer to the backing file */
12929fd3171aSKevin Wolf         if (filename) {
12939fd3171aSKevin Wolf             qdict_put(options, "file.filename", qstring_from_str(filename));
12949fd3171aSKevin Wolf         }
12959fd3171aSKevin Wolf         if (drv) {
12969fd3171aSKevin Wolf             qdict_put(options, "driver", qstring_from_str(drv->format_name));
12979fd3171aSKevin Wolf         }
12989fd3171aSKevin Wolf 
12999fd3171aSKevin Wolf         snapshot_options = qdict_new();
13009fd3171aSKevin Wolf         qdict_put(snapshot_options, "backing", options);
13019fd3171aSKevin Wolf         qdict_flatten(snapshot_options);
13029fd3171aSKevin Wolf 
13039fd3171aSKevin Wolf         bs->options = snapshot_options;
13049fd3171aSKevin Wolf         options = qdict_clone_shallow(bs->options);
13059fd3171aSKevin Wolf 
1306ea2384d3Sbellard         filename = tmp_filename;
130791a073a9SKevin Wolf         drv = bdrv_qcow2;
1308ea2384d3Sbellard         bs->is_temporary = 1;
1309ea2384d3Sbellard     }
1310ea2384d3Sbellard 
1311f500a6d3SKevin Wolf     /* Open image file without format layer */
1312be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1313be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1314be028adcSJeff Cody     }
1315be028adcSJeff Cody 
1316054963f8SMax Reitz     ret = bdrv_open_image(&file, filename, options, "file",
1317054963f8SMax Reitz                           bdrv_open_flags(bs, flags | BDRV_O_UNMAP), true, true,
13182a05cbe4SMax Reitz                           &local_err);
1319f500a6d3SKevin Wolf     if (ret < 0) {
1320de9c0cecSKevin Wolf         goto fail;
1321f500a6d3SKevin Wolf     }
1322f500a6d3SKevin Wolf 
1323f500a6d3SKevin Wolf     /* Find the right image format driver */
132474fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
132574fe54f2SKevin Wolf     if (drvname) {
13268f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
132774fe54f2SKevin Wolf         qdict_del(options, "driver");
132806d22aa3SKevin Wolf         if (!drv) {
132906d22aa3SKevin Wolf             error_setg(errp, "Invalid driver: '%s'", drvname);
133006d22aa3SKevin Wolf             ret = -EINVAL;
133106d22aa3SKevin Wolf             goto unlink_and_fail;
133206d22aa3SKevin Wolf         }
133374fe54f2SKevin Wolf     }
133474fe54f2SKevin Wolf 
1335f500a6d3SKevin Wolf     if (!drv) {
13362a05cbe4SMax Reitz         if (file) {
133734b5d2c6SMax Reitz             ret = find_image_format(file, filename, &drv, &local_err);
13382a05cbe4SMax Reitz         } else {
13392a05cbe4SMax Reitz             error_setg(errp, "Must specify either driver or file");
13402a05cbe4SMax Reitz             ret = -EINVAL;
13412a05cbe4SMax Reitz             goto unlink_and_fail;
13422a05cbe4SMax Reitz         }
1343f500a6d3SKevin Wolf     }
1344f500a6d3SKevin Wolf 
1345f500a6d3SKevin Wolf     if (!drv) {
1346f500a6d3SKevin Wolf         goto unlink_and_fail;
1347f500a6d3SKevin Wolf     }
1348f500a6d3SKevin Wolf 
1349b6ce07aaSKevin Wolf     /* Open the image */
135034b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1351b6ce07aaSKevin Wolf     if (ret < 0) {
13526987307cSChristoph Hellwig         goto unlink_and_fail;
13536987307cSChristoph Hellwig     }
13546987307cSChristoph Hellwig 
13552a05cbe4SMax Reitz     if (file && (bs->file != file)) {
13564f6fd349SFam Zheng         bdrv_unref(file);
1357f500a6d3SKevin Wolf         file = NULL;
1358f500a6d3SKevin Wolf     }
1359f500a6d3SKevin Wolf 
1360b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
13619156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
136231ca6d07SKevin Wolf         QDict *backing_options;
136331ca6d07SKevin Wolf 
13645726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
136534b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1366b6ce07aaSKevin Wolf         if (ret < 0) {
1367b6ad491aSKevin Wolf             goto close_and_fail;
1368b6ce07aaSKevin Wolf         }
1369b6ce07aaSKevin Wolf     }
1370b6ce07aaSKevin Wolf 
1371b6ad491aSKevin Wolf     /* Check if any unknown options were used */
1372b6ad491aSKevin Wolf     if (qdict_size(options) != 0) {
1373b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
137434b5d2c6SMax Reitz         error_setg(errp, "Block format '%s' used by device '%s' doesn't "
137534b5d2c6SMax Reitz                    "support the option '%s'", drv->format_name, bs->device_name,
137634b5d2c6SMax Reitz                    entry->key);
1377b6ad491aSKevin Wolf 
1378b6ad491aSKevin Wolf         ret = -EINVAL;
1379b6ad491aSKevin Wolf         goto close_and_fail;
1380b6ad491aSKevin Wolf     }
1381b6ad491aSKevin Wolf     QDECREF(options);
1382b6ad491aSKevin Wolf 
1383b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
13847d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1385b6ce07aaSKevin Wolf     }
1386b6ce07aaSKevin Wolf 
1387b6ce07aaSKevin Wolf     return 0;
1388b6ce07aaSKevin Wolf 
1389b6ce07aaSKevin Wolf unlink_and_fail:
1390f500a6d3SKevin Wolf     if (file != NULL) {
13914f6fd349SFam Zheng         bdrv_unref(file);
1392f500a6d3SKevin Wolf     }
1393b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1394b6ce07aaSKevin Wolf         unlink(filename);
1395b6ce07aaSKevin Wolf     }
1396de9c0cecSKevin Wolf fail:
1397de9c0cecSKevin Wolf     QDECREF(bs->options);
1398b6ad491aSKevin Wolf     QDECREF(options);
1399de9c0cecSKevin Wolf     bs->options = NULL;
140034b5d2c6SMax Reitz     if (error_is_set(&local_err)) {
140134b5d2c6SMax Reitz         error_propagate(errp, local_err);
140234b5d2c6SMax Reitz     }
1403b6ad491aSKevin Wolf     return ret;
1404de9c0cecSKevin Wolf 
1405b6ad491aSKevin Wolf close_and_fail:
1406b6ad491aSKevin Wolf     bdrv_close(bs);
1407b6ad491aSKevin Wolf     QDECREF(options);
140834b5d2c6SMax Reitz     if (error_is_set(&local_err)) {
140934b5d2c6SMax Reitz         error_propagate(errp, local_err);
141034b5d2c6SMax Reitz     }
1411b6ce07aaSKevin Wolf     return ret;
1412b6ce07aaSKevin Wolf }
1413b6ce07aaSKevin Wolf 
1414e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1415e971aa12SJeff Cody      bool prepared;
1416e971aa12SJeff Cody      BDRVReopenState state;
1417e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1418e971aa12SJeff Cody } BlockReopenQueueEntry;
1419e971aa12SJeff Cody 
1420e971aa12SJeff Cody /*
1421e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1422e971aa12SJeff Cody  * reopen of multiple devices.
1423e971aa12SJeff Cody  *
1424e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1425e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1426e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1427e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1428e971aa12SJeff Cody  * atomic 'set'.
1429e971aa12SJeff Cody  *
1430e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1431e971aa12SJeff Cody  *
1432e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1433e971aa12SJeff Cody  *
1434e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1435e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1436e971aa12SJeff Cody  *
1437e971aa12SJeff Cody  */
1438e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1439e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1440e971aa12SJeff Cody {
1441e971aa12SJeff Cody     assert(bs != NULL);
1442e971aa12SJeff Cody 
1443e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1444e971aa12SJeff Cody     if (bs_queue == NULL) {
1445e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1446e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1447e971aa12SJeff Cody     }
1448e971aa12SJeff Cody 
1449e971aa12SJeff Cody     if (bs->file) {
1450e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1451e971aa12SJeff Cody     }
1452e971aa12SJeff Cody 
1453e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1454e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1455e971aa12SJeff Cody 
1456e971aa12SJeff Cody     bs_entry->state.bs = bs;
1457e971aa12SJeff Cody     bs_entry->state.flags = flags;
1458e971aa12SJeff Cody 
1459e971aa12SJeff Cody     return bs_queue;
1460e971aa12SJeff Cody }
1461e971aa12SJeff Cody 
1462e971aa12SJeff Cody /*
1463e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1464e971aa12SJeff Cody  *
1465e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1466e971aa12SJeff Cody  * via bdrv_reopen_queue().
1467e971aa12SJeff Cody  *
1468e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1469e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1470e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1471e971aa12SJeff Cody  * data cleaned up.
1472e971aa12SJeff Cody  *
1473e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1474e971aa12SJeff Cody  * to all devices.
1475e971aa12SJeff Cody  *
1476e971aa12SJeff Cody  */
1477e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1478e971aa12SJeff Cody {
1479e971aa12SJeff Cody     int ret = -1;
1480e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1481e971aa12SJeff Cody     Error *local_err = NULL;
1482e971aa12SJeff Cody 
1483e971aa12SJeff Cody     assert(bs_queue != NULL);
1484e971aa12SJeff Cody 
1485e971aa12SJeff Cody     bdrv_drain_all();
1486e971aa12SJeff Cody 
1487e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1488e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1489e971aa12SJeff Cody             error_propagate(errp, local_err);
1490e971aa12SJeff Cody             goto cleanup;
1491e971aa12SJeff Cody         }
1492e971aa12SJeff Cody         bs_entry->prepared = true;
1493e971aa12SJeff Cody     }
1494e971aa12SJeff Cody 
1495e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1496e971aa12SJeff Cody      * changes
1497e971aa12SJeff Cody      */
1498e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1499e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1500e971aa12SJeff Cody     }
1501e971aa12SJeff Cody 
1502e971aa12SJeff Cody     ret = 0;
1503e971aa12SJeff Cody 
1504e971aa12SJeff Cody cleanup:
1505e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1506e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1507e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1508e971aa12SJeff Cody         }
1509e971aa12SJeff Cody         g_free(bs_entry);
1510e971aa12SJeff Cody     }
1511e971aa12SJeff Cody     g_free(bs_queue);
1512e971aa12SJeff Cody     return ret;
1513e971aa12SJeff Cody }
1514e971aa12SJeff Cody 
1515e971aa12SJeff Cody 
1516e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1517e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1518e971aa12SJeff Cody {
1519e971aa12SJeff Cody     int ret = -1;
1520e971aa12SJeff Cody     Error *local_err = NULL;
1521e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1522e971aa12SJeff Cody 
1523e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1524e971aa12SJeff Cody     if (local_err != NULL) {
1525e971aa12SJeff Cody         error_propagate(errp, local_err);
1526e971aa12SJeff Cody     }
1527e971aa12SJeff Cody     return ret;
1528e971aa12SJeff Cody }
1529e971aa12SJeff Cody 
1530e971aa12SJeff Cody 
1531e971aa12SJeff Cody /*
1532e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1533e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1534e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1535e971aa12SJeff Cody  *
1536e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1537e971aa12SJeff Cody  * flags are the new open flags
1538e971aa12SJeff Cody  * queue is the reopen queue
1539e971aa12SJeff Cody  *
1540e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1541e971aa12SJeff Cody  * as well.
1542e971aa12SJeff Cody  *
1543e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1544e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1545e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1546e971aa12SJeff Cody  *
1547e971aa12SJeff Cody  */
1548e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1549e971aa12SJeff Cody                         Error **errp)
1550e971aa12SJeff Cody {
1551e971aa12SJeff Cody     int ret = -1;
1552e971aa12SJeff Cody     Error *local_err = NULL;
1553e971aa12SJeff Cody     BlockDriver *drv;
1554e971aa12SJeff Cody 
1555e971aa12SJeff Cody     assert(reopen_state != NULL);
1556e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1557e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1558e971aa12SJeff Cody 
1559e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1560e971aa12SJeff Cody      * to r/w */
1561e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1562e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1563e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1564e971aa12SJeff Cody                   reopen_state->bs->device_name);
1565e971aa12SJeff Cody         goto error;
1566e971aa12SJeff Cody     }
1567e971aa12SJeff Cody 
1568e971aa12SJeff Cody 
1569e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1570e971aa12SJeff Cody     if (ret) {
1571e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1572e971aa12SJeff Cody                   strerror(-ret));
1573e971aa12SJeff Cody         goto error;
1574e971aa12SJeff Cody     }
1575e971aa12SJeff Cody 
1576e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1577e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1578e971aa12SJeff Cody         if (ret) {
1579e971aa12SJeff Cody             if (local_err != NULL) {
1580e971aa12SJeff Cody                 error_propagate(errp, local_err);
1581e971aa12SJeff Cody             } else {
1582d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1583e971aa12SJeff Cody                            reopen_state->bs->filename);
1584e971aa12SJeff Cody             }
1585e971aa12SJeff Cody             goto error;
1586e971aa12SJeff Cody         }
1587e971aa12SJeff Cody     } else {
1588e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1589e971aa12SJeff Cody          * handler for each supported drv. */
1590e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1591e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1592e971aa12SJeff Cody                  "reopening of file");
1593e971aa12SJeff Cody         ret = -1;
1594e971aa12SJeff Cody         goto error;
1595e971aa12SJeff Cody     }
1596e971aa12SJeff Cody 
1597e971aa12SJeff Cody     ret = 0;
1598e971aa12SJeff Cody 
1599e971aa12SJeff Cody error:
1600e971aa12SJeff Cody     return ret;
1601e971aa12SJeff Cody }
1602e971aa12SJeff Cody 
1603e971aa12SJeff Cody /*
1604e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1605e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1606e971aa12SJeff Cody  * the active BlockDriverState contents.
1607e971aa12SJeff Cody  */
1608e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1609e971aa12SJeff Cody {
1610e971aa12SJeff Cody     BlockDriver *drv;
1611e971aa12SJeff Cody 
1612e971aa12SJeff Cody     assert(reopen_state != NULL);
1613e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1614e971aa12SJeff Cody     assert(drv != NULL);
1615e971aa12SJeff Cody 
1616e971aa12SJeff Cody     /* If there are any driver level actions to take */
1617e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1618e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1619e971aa12SJeff Cody     }
1620e971aa12SJeff Cody 
1621e971aa12SJeff Cody     /* set BDS specific flags now */
1622e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1623e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1624e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1625e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1626355ef4acSKevin Wolf 
1627355ef4acSKevin Wolf     bdrv_refresh_limits(reopen_state->bs);
1628e971aa12SJeff Cody }
1629e971aa12SJeff Cody 
1630e971aa12SJeff Cody /*
1631e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1632e971aa12SJeff Cody  * reopen_state
1633e971aa12SJeff Cody  */
1634e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1635e971aa12SJeff Cody {
1636e971aa12SJeff Cody     BlockDriver *drv;
1637e971aa12SJeff Cody 
1638e971aa12SJeff Cody     assert(reopen_state != NULL);
1639e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1640e971aa12SJeff Cody     assert(drv != NULL);
1641e971aa12SJeff Cody 
1642e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1643e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1644e971aa12SJeff Cody     }
1645e971aa12SJeff Cody }
1646e971aa12SJeff Cody 
1647e971aa12SJeff Cody 
1648fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1649fc01f7e7Sbellard {
16503e914655SPaolo Bonzini     if (bs->job) {
16513e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
16523e914655SPaolo Bonzini     }
165358fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
165458fda173SStefan Hajnoczi     bdrv_flush(bs);
165558fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1656d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
16577094f12fSKevin Wolf 
16583cbc002cSPaolo Bonzini     if (bs->drv) {
1659557df6acSStefan Hajnoczi         if (bs->backing_hd) {
16604f6fd349SFam Zheng             bdrv_unref(bs->backing_hd);
1661557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1662557df6acSStefan Hajnoczi         }
1663ea2384d3Sbellard         bs->drv->bdrv_close(bs);
16647267c094SAnthony Liguori         g_free(bs->opaque);
1665ea2384d3Sbellard #ifdef _WIN32
1666ea2384d3Sbellard         if (bs->is_temporary) {
1667ea2384d3Sbellard             unlink(bs->filename);
1668ea2384d3Sbellard         }
166967b915a5Sbellard #endif
1670ea2384d3Sbellard         bs->opaque = NULL;
1671ea2384d3Sbellard         bs->drv = NULL;
167253fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1673a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1674a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
16756405875cSPaolo Bonzini         bs->total_sectors = 0;
16766405875cSPaolo Bonzini         bs->encrypted = 0;
16776405875cSPaolo Bonzini         bs->valid_key = 0;
16786405875cSPaolo Bonzini         bs->sg = 0;
16796405875cSPaolo Bonzini         bs->growable = 0;
16800d51b4deSAsias He         bs->zero_beyond_eof = false;
1681de9c0cecSKevin Wolf         QDECREF(bs->options);
1682de9c0cecSKevin Wolf         bs->options = NULL;
1683b338082bSbellard 
168466f82ceeSKevin Wolf         if (bs->file != NULL) {
16854f6fd349SFam Zheng             bdrv_unref(bs->file);
16860ac9377dSPaolo Bonzini             bs->file = NULL;
168766f82ceeSKevin Wolf         }
16889ca11154SPavel Hrdina     }
168966f82ceeSKevin Wolf 
16907d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
169198f90dbaSZhi Yong Wu 
169298f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
169398f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
169498f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
169598f90dbaSZhi Yong Wu     }
1696b338082bSbellard }
1697b338082bSbellard 
16982bc93fedSMORITA Kazutaka void bdrv_close_all(void)
16992bc93fedSMORITA Kazutaka {
17002bc93fedSMORITA Kazutaka     BlockDriverState *bs;
17012bc93fedSMORITA Kazutaka 
1702dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17032bc93fedSMORITA Kazutaka         bdrv_close(bs);
17042bc93fedSMORITA Kazutaka     }
17052bc93fedSMORITA Kazutaka }
17062bc93fedSMORITA Kazutaka 
170788266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
170888266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
170988266f5aSStefan Hajnoczi {
171088266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
171188266f5aSStefan Hajnoczi         return true;
171288266f5aSStefan Hajnoczi     }
1713cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1714cc0681c4SBenoît Canet         return true;
1715cc0681c4SBenoît Canet     }
1716cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
171788266f5aSStefan Hajnoczi         return true;
171888266f5aSStefan Hajnoczi     }
171988266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
172088266f5aSStefan Hajnoczi         return true;
172188266f5aSStefan Hajnoczi     }
172288266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
172388266f5aSStefan Hajnoczi         return true;
172488266f5aSStefan Hajnoczi     }
172588266f5aSStefan Hajnoczi     return false;
172688266f5aSStefan Hajnoczi }
172788266f5aSStefan Hajnoczi 
172888266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
172988266f5aSStefan Hajnoczi {
173088266f5aSStefan Hajnoczi     BlockDriverState *bs;
1731dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
173288266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
173388266f5aSStefan Hajnoczi             return true;
173488266f5aSStefan Hajnoczi         }
173588266f5aSStefan Hajnoczi     }
173688266f5aSStefan Hajnoczi     return false;
173788266f5aSStefan Hajnoczi }
173888266f5aSStefan Hajnoczi 
1739922453bcSStefan Hajnoczi /*
1740922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1741922453bcSStefan Hajnoczi  *
1742922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1743922453bcSStefan Hajnoczi  * after calling this function.
17444c355d53SZhi Yong Wu  *
17454c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
17464c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
17474c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
17484c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
17494c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1750922453bcSStefan Hajnoczi  */
1751922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1752922453bcSStefan Hajnoczi {
175388266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
175488266f5aSStefan Hajnoczi     bool busy = true;
1755922453bcSStefan Hajnoczi     BlockDriverState *bs;
1756922453bcSStefan Hajnoczi 
175788266f5aSStefan Hajnoczi     while (busy) {
1758dc364f4cSBenoît Canet         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
17590b06ef3bSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
17604c355d53SZhi Yong Wu         }
1761922453bcSStefan Hajnoczi 
176288266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
176388266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1764922453bcSStefan Hajnoczi     }
1765922453bcSStefan Hajnoczi }
1766922453bcSStefan Hajnoczi 
1767dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1768dc364f4cSBenoît Canet  * graph_bdrv_state list.
1769d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1770d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1771d22b2f41SRyan Harper {
1772d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1773dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1774d22b2f41SRyan Harper     }
1775d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1776dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1777dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1778dc364f4cSBenoît Canet     }
1779dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1780d22b2f41SRyan Harper }
1781d22b2f41SRyan Harper 
1782e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1783e023b2e2SPaolo Bonzini {
1784e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1785e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1786e023b2e2SPaolo Bonzini     }
1787e023b2e2SPaolo Bonzini }
1788e023b2e2SPaolo Bonzini 
17894ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
17904ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
17914ddc07caSPaolo Bonzini {
17924ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
17934ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
17944ddc07caSPaolo Bonzini 
17954ddc07caSPaolo Bonzini     /* dev info */
17964ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
17974ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
17984ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
17994ddc07caSPaolo Bonzini     bs_dest->buffer_alignment   = bs_src->buffer_alignment;
18004ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
18014ddc07caSPaolo Bonzini 
18024ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
18034ddc07caSPaolo Bonzini 
1804cc0681c4SBenoît Canet     /* i/o throttled req */
1805cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1806cc0681c4SBenoît Canet            &bs_src->throttle_state,
1807cc0681c4SBenoît Canet            sizeof(ThrottleState));
1808cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1809cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
18104ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
18114ddc07caSPaolo Bonzini 
18124ddc07caSPaolo Bonzini     /* r/w error */
18134ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
18144ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
18154ddc07caSPaolo Bonzini 
18164ddc07caSPaolo Bonzini     /* i/o status */
18174ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
18184ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
18194ddc07caSPaolo Bonzini 
18204ddc07caSPaolo Bonzini     /* dirty bitmap */
1821e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
18224ddc07caSPaolo Bonzini 
18239fcb0251SFam Zheng     /* reference count */
18249fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
18259fcb0251SFam Zheng 
18264ddc07caSPaolo Bonzini     /* job */
18274ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
18284ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
18294ddc07caSPaolo Bonzini 
18304ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
18314ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
18324ddc07caSPaolo Bonzini             bs_src->device_name);
1833dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
1834dc364f4cSBenoît Canet 
1835dc364f4cSBenoît Canet     /* keep the same entry in graph_bdrv_states
1836dc364f4cSBenoît Canet      * We do want to swap name but don't want to swap linked list entries
1837dc364f4cSBenoît Canet      */
1838dc364f4cSBenoît Canet     bs_dest->node_list   = bs_src->node_list;
18394ddc07caSPaolo Bonzini }
18404ddc07caSPaolo Bonzini 
18414ddc07caSPaolo Bonzini /*
18424ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
18434ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
18444ddc07caSPaolo Bonzini  * actually attached to a device.
18454ddc07caSPaolo Bonzini  *
18464ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
18474ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
18484ddc07caSPaolo Bonzini  *
18494ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
18504ddc07caSPaolo Bonzini  *
18514ddc07caSPaolo Bonzini  * This function does not create any image files.
18524ddc07caSPaolo Bonzini  */
18534ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
18544ddc07caSPaolo Bonzini {
18554ddc07caSPaolo Bonzini     BlockDriverState tmp;
18564ddc07caSPaolo Bonzini 
18574ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
18584ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
1859e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
18604ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
18614ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
18624ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
18634ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1864cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
18654ddc07caSPaolo Bonzini 
18664ddc07caSPaolo Bonzini     tmp = *bs_new;
18674ddc07caSPaolo Bonzini     *bs_new = *bs_old;
18684ddc07caSPaolo Bonzini     *bs_old = tmp;
18694ddc07caSPaolo Bonzini 
18704ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
18714ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
18724ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
18734ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
18744ddc07caSPaolo Bonzini 
18754ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
18764ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
18774ddc07caSPaolo Bonzini 
18784ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
18794ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
18804ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
18814ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
18824ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1883cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
18844ddc07caSPaolo Bonzini 
18854ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
18864ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
18874ddc07caSPaolo Bonzini }
18884ddc07caSPaolo Bonzini 
18898802d1fdSJeff Cody /*
18908802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
18918802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
18928802d1fdSJeff Cody  *
18938802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
18948802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
18958802d1fdSJeff Cody  *
1896f6801b83SJeff Cody  * bs_new is required to be anonymous.
1897f6801b83SJeff Cody  *
18988802d1fdSJeff Cody  * This function does not create any image files.
18998802d1fdSJeff Cody  */
19008802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
19018802d1fdSJeff Cody {
19024ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
19038802d1fdSJeff Cody 
19048802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
19058802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
19064ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
19074ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
19084ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
19094ddc07caSPaolo Bonzini             bs_new->filename);
19104ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
19114ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
19128802d1fdSJeff Cody }
19138802d1fdSJeff Cody 
19144f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
1915b338082bSbellard {
1916fa879d62SMarkus Armbruster     assert(!bs->dev);
19173e914655SPaolo Bonzini     assert(!bs->job);
19183e914655SPaolo Bonzini     assert(!bs->in_use);
19194f6fd349SFam Zheng     assert(!bs->refcnt);
1920e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
192118846deeSMarkus Armbruster 
1922e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1923e1b5c52eSStefan Hajnoczi 
19241b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1925d22b2f41SRyan Harper     bdrv_make_anon(bs);
192634c6f050Saurel32 
19277267c094SAnthony Liguori     g_free(bs);
1928fc01f7e7Sbellard }
1929fc01f7e7Sbellard 
1930fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1931fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
193218846deeSMarkus Armbruster {
1933fa879d62SMarkus Armbruster     if (bs->dev) {
193418846deeSMarkus Armbruster         return -EBUSY;
193518846deeSMarkus Armbruster     }
1936fa879d62SMarkus Armbruster     bs->dev = dev;
193728a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
193818846deeSMarkus Armbruster     return 0;
193918846deeSMarkus Armbruster }
194018846deeSMarkus Armbruster 
1941fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1942fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
194318846deeSMarkus Armbruster {
1944fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1945fa879d62SMarkus Armbruster         abort();
1946fa879d62SMarkus Armbruster     }
1947fa879d62SMarkus Armbruster }
1948fa879d62SMarkus Armbruster 
1949fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1950fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1951fa879d62SMarkus Armbruster {
1952fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1953fa879d62SMarkus Armbruster     bs->dev = NULL;
19540e49de52SMarkus Armbruster     bs->dev_ops = NULL;
19550e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
195629e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
195718846deeSMarkus Armbruster }
195818846deeSMarkus Armbruster 
1959fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1960fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
196118846deeSMarkus Armbruster {
1962fa879d62SMarkus Armbruster     return bs->dev;
196318846deeSMarkus Armbruster }
196418846deeSMarkus Armbruster 
19650e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
19660e49de52SMarkus Armbruster                       void *opaque)
19670e49de52SMarkus Armbruster {
19680e49de52SMarkus Armbruster     bs->dev_ops = ops;
19690e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
19700e49de52SMarkus Armbruster }
19710e49de52SMarkus Armbruster 
197232c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
197332c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
19741ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1975329c0a48SLuiz Capitulino {
1976329c0a48SLuiz Capitulino     QObject *data;
1977329c0a48SLuiz Capitulino     const char *action_str;
1978329c0a48SLuiz Capitulino 
1979329c0a48SLuiz Capitulino     switch (action) {
1980329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1981329c0a48SLuiz Capitulino         action_str = "report";
1982329c0a48SLuiz Capitulino         break;
1983329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1984329c0a48SLuiz Capitulino         action_str = "ignore";
1985329c0a48SLuiz Capitulino         break;
1986329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1987329c0a48SLuiz Capitulino         action_str = "stop";
1988329c0a48SLuiz Capitulino         break;
1989329c0a48SLuiz Capitulino     default:
1990329c0a48SLuiz Capitulino         abort();
1991329c0a48SLuiz Capitulino     }
1992329c0a48SLuiz Capitulino 
1993329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1994329c0a48SLuiz Capitulino                               bdrv->device_name,
1995329c0a48SLuiz Capitulino                               action_str,
1996329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
199732c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
1998329c0a48SLuiz Capitulino 
1999329c0a48SLuiz Capitulino     qobject_decref(data);
2000329c0a48SLuiz Capitulino }
2001329c0a48SLuiz Capitulino 
20026f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
20036f382ed2SLuiz Capitulino {
20046f382ed2SLuiz Capitulino     QObject *data;
20056f382ed2SLuiz Capitulino 
20066f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
20076f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
20086f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
20096f382ed2SLuiz Capitulino 
20106f382ed2SLuiz Capitulino     qobject_decref(data);
20116f382ed2SLuiz Capitulino }
20126f382ed2SLuiz Capitulino 
20137d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
20140e49de52SMarkus Armbruster {
2015145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
20166f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
20177d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
20186f382ed2SLuiz Capitulino         if (tray_was_closed) {
20196f382ed2SLuiz Capitulino             /* tray open */
20206f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
20216f382ed2SLuiz Capitulino         }
20226f382ed2SLuiz Capitulino         if (load) {
20236f382ed2SLuiz Capitulino             /* tray close */
20246f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
20256f382ed2SLuiz Capitulino         }
2026145feb17SMarkus Armbruster     }
2027145feb17SMarkus Armbruster }
2028145feb17SMarkus Armbruster 
20292c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
20302c6942faSMarkus Armbruster {
20312c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
20322c6942faSMarkus Armbruster }
20332c6942faSMarkus Armbruster 
2034025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2035025ccaa7SPaolo Bonzini {
2036025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2037025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2038025ccaa7SPaolo Bonzini     }
2039025ccaa7SPaolo Bonzini }
2040025ccaa7SPaolo Bonzini 
2041e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2042e4def80bSMarkus Armbruster {
2043e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2044e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
2045e4def80bSMarkus Armbruster     }
2046e4def80bSMarkus Armbruster     return false;
2047e4def80bSMarkus Armbruster }
2048e4def80bSMarkus Armbruster 
2049145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
2050145feb17SMarkus Armbruster {
2051145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
2052145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
20530e49de52SMarkus Armbruster     }
20540e49de52SMarkus Armbruster }
20550e49de52SMarkus Armbruster 
2056f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2057f107639aSMarkus Armbruster {
2058f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2059f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2060f107639aSMarkus Armbruster     }
2061f107639aSMarkus Armbruster     return false;
2062f107639aSMarkus Armbruster }
2063f107639aSMarkus Armbruster 
2064e97fc193Saliguori /*
2065e97fc193Saliguori  * Run consistency checks on an image
2066e97fc193Saliguori  *
2067e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2068a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2069e076f338SKevin Wolf  * check are stored in res.
2070e97fc193Saliguori  */
20714534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2072e97fc193Saliguori {
2073e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2074e97fc193Saliguori         return -ENOTSUP;
2075e97fc193Saliguori     }
2076e97fc193Saliguori 
2077e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
20784534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2079e97fc193Saliguori }
2080e97fc193Saliguori 
20818a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
20828a426614SKevin Wolf 
208333e3963eSbellard /* commit COW file into the raw image */
208433e3963eSbellard int bdrv_commit(BlockDriverState *bs)
208533e3963eSbellard {
208619cb3738Sbellard     BlockDriver *drv = bs->drv;
208772706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
20888a426614SKevin Wolf     int n, ro, open_flags;
20890bce597dSJeff Cody     int ret = 0;
209072706ea4SJeff Cody     uint8_t *buf = NULL;
2091c2cba3d9SJim Meyering     char filename[PATH_MAX];
209233e3963eSbellard 
209319cb3738Sbellard     if (!drv)
209419cb3738Sbellard         return -ENOMEDIUM;
209533e3963eSbellard 
20964dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
20974dca4b63SNaphtali Sprei         return -ENOTSUP;
20984dca4b63SNaphtali Sprei     }
20994dca4b63SNaphtali Sprei 
21002d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
21012d3735d3SStefan Hajnoczi         return -EBUSY;
21022d3735d3SStefan Hajnoczi     }
21032d3735d3SStefan Hajnoczi 
21044dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2105c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2106c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
21074dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
21084dca4b63SNaphtali Sprei 
21094dca4b63SNaphtali Sprei     if (ro) {
21100bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
21110bce597dSJeff Cody             return -EACCES;
21124dca4b63SNaphtali Sprei         }
2113ea2384d3Sbellard     }
2114ea2384d3Sbellard 
211572706ea4SJeff Cody     length = bdrv_getlength(bs);
211672706ea4SJeff Cody     if (length < 0) {
211772706ea4SJeff Cody         ret = length;
211872706ea4SJeff Cody         goto ro_cleanup;
211972706ea4SJeff Cody     }
212072706ea4SJeff Cody 
212172706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
212272706ea4SJeff Cody     if (backing_length < 0) {
212372706ea4SJeff Cody         ret = backing_length;
212472706ea4SJeff Cody         goto ro_cleanup;
212572706ea4SJeff Cody     }
212672706ea4SJeff Cody 
212772706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
212872706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
212972706ea4SJeff Cody      * we must return an error */
213072706ea4SJeff Cody     if (length > backing_length) {
213172706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
213272706ea4SJeff Cody         if (ret < 0) {
213372706ea4SJeff Cody             goto ro_cleanup;
213472706ea4SJeff Cody         }
213572706ea4SJeff Cody     }
213672706ea4SJeff Cody 
213772706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
21387267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
21398a426614SKevin Wolf 
21408a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2141d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2142d663640cSPaolo Bonzini         if (ret < 0) {
2143d663640cSPaolo Bonzini             goto ro_cleanup;
2144d663640cSPaolo Bonzini         }
2145d663640cSPaolo Bonzini         if (ret) {
2146dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2147dabfa6ccSKevin Wolf             if (ret < 0) {
21484dca4b63SNaphtali Sprei                 goto ro_cleanup;
214933e3963eSbellard             }
215033e3963eSbellard 
2151dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2152dabfa6ccSKevin Wolf             if (ret < 0) {
21534dca4b63SNaphtali Sprei                 goto ro_cleanup;
215433e3963eSbellard             }
215533e3963eSbellard         }
215633e3963eSbellard     }
215795389c86Sbellard 
21581d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
21591d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2160dabfa6ccSKevin Wolf         if (ret < 0) {
2161dabfa6ccSKevin Wolf             goto ro_cleanup;
2162dabfa6ccSKevin Wolf         }
21631d44952fSChristoph Hellwig         bdrv_flush(bs);
21641d44952fSChristoph Hellwig     }
216595389c86Sbellard 
21663f5075aeSChristoph Hellwig     /*
21673f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
21683f5075aeSChristoph Hellwig      * stable on disk.
21693f5075aeSChristoph Hellwig      */
2170dabfa6ccSKevin Wolf     if (bs->backing_hd) {
21713f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2172dabfa6ccSKevin Wolf     }
21734dca4b63SNaphtali Sprei 
2174dabfa6ccSKevin Wolf     ret = 0;
21754dca4b63SNaphtali Sprei ro_cleanup:
21767267c094SAnthony Liguori     g_free(buf);
21774dca4b63SNaphtali Sprei 
21784dca4b63SNaphtali Sprei     if (ro) {
21790bce597dSJeff Cody         /* ignoring error return here */
21800bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
21814dca4b63SNaphtali Sprei     }
21824dca4b63SNaphtali Sprei 
21831d44952fSChristoph Hellwig     return ret;
218433e3963eSbellard }
218533e3963eSbellard 
2186e8877497SStefan Hajnoczi int bdrv_commit_all(void)
21876ab4b5abSMarkus Armbruster {
21886ab4b5abSMarkus Armbruster     BlockDriverState *bs;
21896ab4b5abSMarkus Armbruster 
2190dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2191272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2192e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2193e8877497SStefan Hajnoczi             if (ret < 0) {
2194e8877497SStefan Hajnoczi                 return ret;
21956ab4b5abSMarkus Armbruster             }
21966ab4b5abSMarkus Armbruster         }
2197272d2d8eSJeff Cody     }
2198e8877497SStefan Hajnoczi     return 0;
2199e8877497SStefan Hajnoczi }
22006ab4b5abSMarkus Armbruster 
2201dbffbdcfSStefan Hajnoczi /**
2202dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2203dbffbdcfSStefan Hajnoczi  *
2204dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2205dbffbdcfSStefan Hajnoczi  */
2206dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2207dbffbdcfSStefan Hajnoczi {
2208dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2209f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2210dbffbdcfSStefan Hajnoczi }
2211dbffbdcfSStefan Hajnoczi 
2212dbffbdcfSStefan Hajnoczi /**
2213dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2214dbffbdcfSStefan Hajnoczi  */
2215dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2216dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2217dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
2218dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
2219dbffbdcfSStefan Hajnoczi {
2220dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2221dbffbdcfSStefan Hajnoczi         .bs = bs,
2222dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
2223dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
2224dbffbdcfSStefan Hajnoczi         .is_write = is_write,
22255f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
2226dbffbdcfSStefan Hajnoczi     };
2227dbffbdcfSStefan Hajnoczi 
2228f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2229f4658285SStefan Hajnoczi 
2230dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2231dbffbdcfSStefan Hajnoczi }
2232dbffbdcfSStefan Hajnoczi 
2233d83947acSStefan Hajnoczi /**
2234d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2235d83947acSStefan Hajnoczi  */
2236343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2237d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2238d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2239d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2240d83947acSStefan Hajnoczi {
2241d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2242d83947acSStefan Hajnoczi 
2243d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2244d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2245d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2246d83947acSStefan Hajnoczi     } else {
2247d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2248d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2249d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2250d83947acSStefan Hajnoczi                                             nb_sectors, c);
2251d83947acSStefan Hajnoczi     }
2252d83947acSStefan Hajnoczi }
2253d83947acSStefan Hajnoczi 
2254f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2255f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
2256d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
2257d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
2258d83947acSStefan Hajnoczi         return false;
2259d83947acSStefan Hajnoczi     }
2260d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
2261d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
2262d83947acSStefan Hajnoczi         return false;
2263d83947acSStefan Hajnoczi     }
2264d83947acSStefan Hajnoczi     return true;
2265f4658285SStefan Hajnoczi }
2266f4658285SStefan Hajnoczi 
2267f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
2268f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
2269f4658285SStefan Hajnoczi {
2270f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2271d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
2272d83947acSStefan Hajnoczi     int cluster_nb_sectors;
2273f4658285SStefan Hajnoczi     bool retry;
2274f4658285SStefan Hajnoczi 
2275d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
2276d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
2277d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
2278d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
2279d83947acSStefan Hajnoczi      * interleave between them.
2280d83947acSStefan Hajnoczi      */
2281343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2282d83947acSStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2283d83947acSStefan Hajnoczi 
2284f4658285SStefan Hajnoczi     do {
2285f4658285SStefan Hajnoczi         retry = false;
2286f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
2287d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
2288d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
22895f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
22905f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
22915f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
22925f8b6491SStefan Hajnoczi                  */
22935f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
22945f8b6491SStefan Hajnoczi 
2295f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
2296f4658285SStefan Hajnoczi                 retry = true;
2297f4658285SStefan Hajnoczi                 break;
2298f4658285SStefan Hajnoczi             }
2299f4658285SStefan Hajnoczi         }
2300f4658285SStefan Hajnoczi     } while (retry);
2301f4658285SStefan Hajnoczi }
2302f4658285SStefan Hajnoczi 
2303756e6736SKevin Wolf /*
2304756e6736SKevin Wolf  * Return values:
2305756e6736SKevin Wolf  * 0        - success
2306756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2307756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2308756e6736SKevin Wolf  *            image file header
2309756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2310756e6736SKevin Wolf  */
2311756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2312756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2313756e6736SKevin Wolf {
2314756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2315469ef350SPaolo Bonzini     int ret;
2316756e6736SKevin Wolf 
23175f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23185f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23195f377794SPaolo Bonzini         return -EINVAL;
23205f377794SPaolo Bonzini     }
23215f377794SPaolo Bonzini 
2322756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2323469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2324756e6736SKevin Wolf     } else {
2325469ef350SPaolo Bonzini         ret = -ENOTSUP;
2326756e6736SKevin Wolf     }
2327469ef350SPaolo Bonzini 
2328469ef350SPaolo Bonzini     if (ret == 0) {
2329469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2330469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2331469ef350SPaolo Bonzini     }
2332469ef350SPaolo Bonzini     return ret;
2333756e6736SKevin Wolf }
2334756e6736SKevin Wolf 
23356ebdcee2SJeff Cody /*
23366ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23376ebdcee2SJeff Cody  *
23386ebdcee2SJeff Cody  * active is the current topmost image.
23396ebdcee2SJeff Cody  *
23406ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
23416ebdcee2SJeff Cody  * or if active == bs.
23426ebdcee2SJeff Cody  */
23436ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
23446ebdcee2SJeff Cody                                     BlockDriverState *bs)
23456ebdcee2SJeff Cody {
23466ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
23476ebdcee2SJeff Cody     BlockDriverState *intermediate;
23486ebdcee2SJeff Cody 
23496ebdcee2SJeff Cody     assert(active != NULL);
23506ebdcee2SJeff Cody     assert(bs != NULL);
23516ebdcee2SJeff Cody 
23526ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
23536ebdcee2SJeff Cody      */
23546ebdcee2SJeff Cody     if (active == bs) {
23556ebdcee2SJeff Cody         return NULL;
23566ebdcee2SJeff Cody     }
23576ebdcee2SJeff Cody 
23586ebdcee2SJeff Cody     intermediate = active;
23596ebdcee2SJeff Cody     while (intermediate->backing_hd) {
23606ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
23616ebdcee2SJeff Cody             overlay = intermediate;
23626ebdcee2SJeff Cody             break;
23636ebdcee2SJeff Cody         }
23646ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
23656ebdcee2SJeff Cody     }
23666ebdcee2SJeff Cody 
23676ebdcee2SJeff Cody     return overlay;
23686ebdcee2SJeff Cody }
23696ebdcee2SJeff Cody 
23706ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
23716ebdcee2SJeff Cody     BlockDriverState *bs;
23726ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
23736ebdcee2SJeff Cody } BlkIntermediateStates;
23746ebdcee2SJeff Cody 
23756ebdcee2SJeff Cody 
23766ebdcee2SJeff Cody /*
23776ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
23786ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
23796ebdcee2SJeff Cody  *
23806ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
23816ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
23826ebdcee2SJeff Cody  *
23836ebdcee2SJeff Cody  * E.g., this will convert the following chain:
23846ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
23856ebdcee2SJeff Cody  *
23866ebdcee2SJeff Cody  * to
23876ebdcee2SJeff Cody  *
23886ebdcee2SJeff Cody  * bottom <- base <- active
23896ebdcee2SJeff Cody  *
23906ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
23916ebdcee2SJeff Cody  *
23926ebdcee2SJeff Cody  * base <- intermediate <- top <- active
23936ebdcee2SJeff Cody  *
23946ebdcee2SJeff Cody  * to
23956ebdcee2SJeff Cody  *
23966ebdcee2SJeff Cody  * base <- active
23976ebdcee2SJeff Cody  *
23986ebdcee2SJeff Cody  * Error conditions:
23996ebdcee2SJeff Cody  *  if active == top, that is considered an error
24006ebdcee2SJeff Cody  *
24016ebdcee2SJeff Cody  */
24026ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
24036ebdcee2SJeff Cody                            BlockDriverState *base)
24046ebdcee2SJeff Cody {
24056ebdcee2SJeff Cody     BlockDriverState *intermediate;
24066ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
24076ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
24086ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
24096ebdcee2SJeff Cody     int ret = -EIO;
24106ebdcee2SJeff Cody 
24116ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
24126ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
24136ebdcee2SJeff Cody 
24146ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
24156ebdcee2SJeff Cody         goto exit;
24166ebdcee2SJeff Cody     }
24176ebdcee2SJeff Cody 
24186ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
24196ebdcee2SJeff Cody 
24206ebdcee2SJeff Cody     if (new_top_bs == NULL) {
24216ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
24226ebdcee2SJeff Cody         goto exit;
24236ebdcee2SJeff Cody     }
24246ebdcee2SJeff Cody 
24256ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
24266ebdcee2SJeff Cody      * to do, no intermediate images */
24276ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
24286ebdcee2SJeff Cody         ret = 0;
24296ebdcee2SJeff Cody         goto exit;
24306ebdcee2SJeff Cody     }
24316ebdcee2SJeff Cody 
24326ebdcee2SJeff Cody     intermediate = top;
24336ebdcee2SJeff Cody 
24346ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
24356ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
24366ebdcee2SJeff Cody      */
24376ebdcee2SJeff Cody     while (intermediate) {
24386ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
24396ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
24406ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
24416ebdcee2SJeff Cody 
24426ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
24436ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
24446ebdcee2SJeff Cody             break;
24456ebdcee2SJeff Cody         }
24466ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
24476ebdcee2SJeff Cody     }
24486ebdcee2SJeff Cody     if (base_bs == NULL) {
24496ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
24506ebdcee2SJeff Cody          * unravel everything, and exit with error */
24516ebdcee2SJeff Cody         goto exit;
24526ebdcee2SJeff Cody     }
24536ebdcee2SJeff Cody 
24546ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
24556ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
24566ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
24576ebdcee2SJeff Cody     if (ret) {
24586ebdcee2SJeff Cody         goto exit;
24596ebdcee2SJeff Cody     }
24606ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
24616ebdcee2SJeff Cody 
2462355ef4acSKevin Wolf     bdrv_refresh_limits(new_top_bs);
24636ebdcee2SJeff Cody 
24646ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
24656ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
24666ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
24674f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
24686ebdcee2SJeff Cody     }
24696ebdcee2SJeff Cody     ret = 0;
24706ebdcee2SJeff Cody 
24716ebdcee2SJeff Cody exit:
24726ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
24736ebdcee2SJeff Cody         g_free(intermediate_state);
24746ebdcee2SJeff Cody     }
24756ebdcee2SJeff Cody     return ret;
24766ebdcee2SJeff Cody }
24776ebdcee2SJeff Cody 
24786ebdcee2SJeff Cody 
247971d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
248071d0770cSaliguori                                    size_t size)
248171d0770cSaliguori {
248271d0770cSaliguori     int64_t len;
248371d0770cSaliguori 
248471d0770cSaliguori     if (!bdrv_is_inserted(bs))
248571d0770cSaliguori         return -ENOMEDIUM;
248671d0770cSaliguori 
248771d0770cSaliguori     if (bs->growable)
248871d0770cSaliguori         return 0;
248971d0770cSaliguori 
249071d0770cSaliguori     len = bdrv_getlength(bs);
249171d0770cSaliguori 
2492fbb7b4e0SKevin Wolf     if (offset < 0)
2493fbb7b4e0SKevin Wolf         return -EIO;
2494fbb7b4e0SKevin Wolf 
2495fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
249671d0770cSaliguori         return -EIO;
249771d0770cSaliguori 
249871d0770cSaliguori     return 0;
249971d0770cSaliguori }
250071d0770cSaliguori 
250171d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
250271d0770cSaliguori                               int nb_sectors)
250371d0770cSaliguori {
2504eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2505eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
250671d0770cSaliguori }
250771d0770cSaliguori 
25081c9805a3SStefan Hajnoczi typedef struct RwCo {
25091c9805a3SStefan Hajnoczi     BlockDriverState *bs;
25101c9805a3SStefan Hajnoczi     int64_t sector_num;
25111c9805a3SStefan Hajnoczi     int nb_sectors;
25121c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
25131c9805a3SStefan Hajnoczi     bool is_write;
25141c9805a3SStefan Hajnoczi     int ret;
25154105eaaaSPeter Lieven     BdrvRequestFlags flags;
25161c9805a3SStefan Hajnoczi } RwCo;
25171c9805a3SStefan Hajnoczi 
25181c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2519fc01f7e7Sbellard {
25201c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2521fc01f7e7Sbellard 
25221c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
25231c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
25244105eaaaSPeter Lieven                                      rwco->nb_sectors, rwco->qiov,
25254105eaaaSPeter Lieven                                      rwco->flags);
25261c9805a3SStefan Hajnoczi     } else {
25271c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
25284105eaaaSPeter Lieven                                       rwco->nb_sectors, rwco->qiov,
25294105eaaaSPeter Lieven                                       rwco->flags);
25301c9805a3SStefan Hajnoczi     }
25311c9805a3SStefan Hajnoczi }
2532e7a8a783SKevin Wolf 
25331c9805a3SStefan Hajnoczi /*
25348d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
25351c9805a3SStefan Hajnoczi  */
25368d3b1a2dSKevin Wolf static int bdrv_rwv_co(BlockDriverState *bs, int64_t sector_num,
25374105eaaaSPeter Lieven                        QEMUIOVector *qiov, bool is_write,
25384105eaaaSPeter Lieven                        BdrvRequestFlags flags)
25391c9805a3SStefan Hajnoczi {
25401c9805a3SStefan Hajnoczi     Coroutine *co;
25411c9805a3SStefan Hajnoczi     RwCo rwco = {
25421c9805a3SStefan Hajnoczi         .bs = bs,
25431c9805a3SStefan Hajnoczi         .sector_num = sector_num,
25448d3b1a2dSKevin Wolf         .nb_sectors = qiov->size >> BDRV_SECTOR_BITS,
25458d3b1a2dSKevin Wolf         .qiov = qiov,
25461c9805a3SStefan Hajnoczi         .is_write = is_write,
25471c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
25484105eaaaSPeter Lieven         .flags = flags,
25491c9805a3SStefan Hajnoczi     };
25508d3b1a2dSKevin Wolf     assert((qiov->size & (BDRV_SECTOR_SIZE - 1)) == 0);
25511c9805a3SStefan Hajnoczi 
2552498e386cSZhi Yong Wu     /**
2553498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2554498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2555498e386cSZhi Yong Wu      * if it has been enabled.
2556498e386cSZhi Yong Wu      */
2557498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2558498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2559498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2560498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2561498e386cSZhi Yong Wu     }
2562498e386cSZhi Yong Wu 
25631c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
25641c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
25651c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
25661c9805a3SStefan Hajnoczi     } else {
25671c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
25681c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
25691c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
25701c9805a3SStefan Hajnoczi             qemu_aio_wait();
25711c9805a3SStefan Hajnoczi         }
25721c9805a3SStefan Hajnoczi     }
25731c9805a3SStefan Hajnoczi     return rwco.ret;
2574e7a8a783SKevin Wolf }
2575e7a8a783SKevin Wolf 
25768d3b1a2dSKevin Wolf /*
25778d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
25788d3b1a2dSKevin Wolf  */
25798d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
25804105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
25818d3b1a2dSKevin Wolf {
25828d3b1a2dSKevin Wolf     QEMUIOVector qiov;
25838d3b1a2dSKevin Wolf     struct iovec iov = {
25848d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
25858d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
25868d3b1a2dSKevin Wolf     };
25878d3b1a2dSKevin Wolf 
25888d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
25894105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, &qiov, is_write, flags);
25908d3b1a2dSKevin Wolf }
25918d3b1a2dSKevin Wolf 
25921c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
25931c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
25941c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
25951c9805a3SStefan Hajnoczi {
25964105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
259783f64091Sbellard }
2598fc01f7e7Sbellard 
259907d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
260007d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
260107d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
260207d27a44SMarkus Armbruster {
260307d27a44SMarkus Armbruster     bool enabled;
260407d27a44SMarkus Armbruster     int ret;
260507d27a44SMarkus Armbruster 
260607d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
260707d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
26084e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
260907d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
261007d27a44SMarkus Armbruster     return ret;
261107d27a44SMarkus Armbruster }
261207d27a44SMarkus Armbruster 
261319cb3738Sbellard /* Return < 0 if error. Important errors are:
261419cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
261519cb3738Sbellard   -ENOMEDIUM   No media inserted.
261619cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
261719cb3738Sbellard   -EACCES      Trying to write a read-only device
261819cb3738Sbellard */
2619fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2620fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2621fc01f7e7Sbellard {
26224105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
262383f64091Sbellard }
262483f64091Sbellard 
26258d3b1a2dSKevin Wolf int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
26268d3b1a2dSKevin Wolf {
26274105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, qiov, true, 0);
26284105eaaaSPeter Lieven }
26294105eaaaSPeter Lieven 
2630aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2631aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
26324105eaaaSPeter Lieven {
26334105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2634aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
26358d3b1a2dSKevin Wolf }
26368d3b1a2dSKevin Wolf 
2637d75cbb5eSPeter Lieven /*
2638d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2639d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2640d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2641d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2642d75cbb5eSPeter Lieven  *
2643d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2644d75cbb5eSPeter Lieven  */
2645d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2646d75cbb5eSPeter Lieven {
2647d75cbb5eSPeter Lieven     int64_t target_size = bdrv_getlength(bs) / BDRV_SECTOR_SIZE;
2648d75cbb5eSPeter Lieven     int64_t ret, nb_sectors, sector_num = 0;
2649d75cbb5eSPeter Lieven     int n;
2650d75cbb5eSPeter Lieven 
2651d75cbb5eSPeter Lieven     for (;;) {
2652d75cbb5eSPeter Lieven         nb_sectors = target_size - sector_num;
2653d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2654d75cbb5eSPeter Lieven             return 0;
2655d75cbb5eSPeter Lieven         }
2656d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2657d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2658d75cbb5eSPeter Lieven         }
2659d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
26603d94ce60SPeter Lieven         if (ret < 0) {
26613d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
26623d94ce60SPeter Lieven                          sector_num, strerror(-ret));
26633d94ce60SPeter Lieven             return ret;
26643d94ce60SPeter Lieven         }
2665d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2666d75cbb5eSPeter Lieven             sector_num += n;
2667d75cbb5eSPeter Lieven             continue;
2668d75cbb5eSPeter Lieven         }
2669d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2670d75cbb5eSPeter Lieven         if (ret < 0) {
2671d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2672d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2673d75cbb5eSPeter Lieven             return ret;
2674d75cbb5eSPeter Lieven         }
2675d75cbb5eSPeter Lieven         sector_num += n;
2676d75cbb5eSPeter Lieven     }
2677d75cbb5eSPeter Lieven }
2678d75cbb5eSPeter Lieven 
2679eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2680eda578e5Saliguori                void *buf, int count1)
268183f64091Sbellard {
26826ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
268383f64091Sbellard     int len, nb_sectors, count;
268483f64091Sbellard     int64_t sector_num;
26859a8c4cceSKevin Wolf     int ret;
268683f64091Sbellard 
268783f64091Sbellard     count = count1;
268883f64091Sbellard     /* first read to align to sector start */
26896ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
269083f64091Sbellard     if (len > count)
269183f64091Sbellard         len = count;
26926ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
269383f64091Sbellard     if (len > 0) {
26949a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
26959a8c4cceSKevin Wolf             return ret;
26966ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
269783f64091Sbellard         count -= len;
269883f64091Sbellard         if (count == 0)
269983f64091Sbellard             return count1;
270083f64091Sbellard         sector_num++;
270183f64091Sbellard         buf += len;
270283f64091Sbellard     }
270383f64091Sbellard 
270483f64091Sbellard     /* read the sectors "in place" */
27056ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
270683f64091Sbellard     if (nb_sectors > 0) {
27079a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
27089a8c4cceSKevin Wolf             return ret;
270983f64091Sbellard         sector_num += nb_sectors;
27106ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
271183f64091Sbellard         buf += len;
271283f64091Sbellard         count -= len;
271383f64091Sbellard     }
271483f64091Sbellard 
271583f64091Sbellard     /* add data from the last sector */
271683f64091Sbellard     if (count > 0) {
27179a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
27189a8c4cceSKevin Wolf             return ret;
271983f64091Sbellard         memcpy(buf, tmp_buf, count);
272083f64091Sbellard     }
272183f64091Sbellard     return count1;
272283f64091Sbellard }
272383f64091Sbellard 
27248d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
272583f64091Sbellard {
27266ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
272783f64091Sbellard     int len, nb_sectors, count;
272883f64091Sbellard     int64_t sector_num;
27299a8c4cceSKevin Wolf     int ret;
273083f64091Sbellard 
27318d3b1a2dSKevin Wolf     count = qiov->size;
27328d3b1a2dSKevin Wolf 
273383f64091Sbellard     /* first write 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;
27418d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
27428d3b1a2dSKevin Wolf                           len);
27439a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
27449a8c4cceSKevin Wolf             return ret;
274583f64091Sbellard         count -= len;
274683f64091Sbellard         if (count == 0)
27478d3b1a2dSKevin Wolf             return qiov->size;
274883f64091Sbellard         sector_num++;
274983f64091Sbellard     }
275083f64091Sbellard 
275183f64091Sbellard     /* write the sectors "in place" */
27526ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
275383f64091Sbellard     if (nb_sectors > 0) {
27548d3b1a2dSKevin Wolf         QEMUIOVector qiov_inplace;
27558d3b1a2dSKevin Wolf 
27568d3b1a2dSKevin Wolf         qemu_iovec_init(&qiov_inplace, qiov->niov);
27578d3b1a2dSKevin Wolf         qemu_iovec_concat(&qiov_inplace, qiov, len,
27588d3b1a2dSKevin Wolf                           nb_sectors << BDRV_SECTOR_BITS);
27598d3b1a2dSKevin Wolf         ret = bdrv_writev(bs, sector_num, &qiov_inplace);
27608d3b1a2dSKevin Wolf         qemu_iovec_destroy(&qiov_inplace);
27618d3b1a2dSKevin Wolf         if (ret < 0) {
27629a8c4cceSKevin Wolf             return ret;
27638d3b1a2dSKevin Wolf         }
27648d3b1a2dSKevin Wolf 
276583f64091Sbellard         sector_num += nb_sectors;
27666ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
276783f64091Sbellard         count -= len;
276883f64091Sbellard     }
276983f64091Sbellard 
277083f64091Sbellard     /* add data from the last sector */
277183f64091Sbellard     if (count > 0) {
27729a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
27739a8c4cceSKevin Wolf             return ret;
27748d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
27759a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
27769a8c4cceSKevin Wolf             return ret;
277783f64091Sbellard     }
27788d3b1a2dSKevin Wolf     return qiov->size;
27798d3b1a2dSKevin Wolf }
27808d3b1a2dSKevin Wolf 
27818d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
27828d3b1a2dSKevin Wolf                 const void *buf, int count1)
27838d3b1a2dSKevin Wolf {
27848d3b1a2dSKevin Wolf     QEMUIOVector qiov;
27858d3b1a2dSKevin Wolf     struct iovec iov = {
27868d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
27878d3b1a2dSKevin Wolf         .iov_len    = count1,
27888d3b1a2dSKevin Wolf     };
27898d3b1a2dSKevin Wolf 
27908d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
27918d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
279283f64091Sbellard }
279383f64091Sbellard 
2794f08145feSKevin Wolf /*
2795f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2796f08145feSKevin Wolf  * request (acts as a barrier)
2797f08145feSKevin Wolf  *
2798f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2799f08145feSKevin Wolf  */
2800f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2801f08145feSKevin Wolf     const void *buf, int count)
2802f08145feSKevin Wolf {
2803f08145feSKevin Wolf     int ret;
2804f08145feSKevin Wolf 
2805f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2806f08145feSKevin Wolf     if (ret < 0) {
2807f08145feSKevin Wolf         return ret;
2808f08145feSKevin Wolf     }
2809f08145feSKevin Wolf 
2810f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2811f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2812f08145feSKevin Wolf         bdrv_flush(bs);
2813f08145feSKevin Wolf     }
2814f08145feSKevin Wolf 
2815f08145feSKevin Wolf     return 0;
2816f08145feSKevin Wolf }
2817f08145feSKevin Wolf 
2818470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2819ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2820ab185921SStefan Hajnoczi {
2821ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2822ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2823ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2824ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2825ab185921SStefan Hajnoczi      */
2826ab185921SStefan Hajnoczi     void *bounce_buffer;
2827ab185921SStefan Hajnoczi 
282879c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2829ab185921SStefan Hajnoczi     struct iovec iov;
2830ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2831ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2832ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2833ab185921SStefan Hajnoczi     size_t skip_bytes;
2834ab185921SStefan Hajnoczi     int ret;
2835ab185921SStefan Hajnoczi 
2836ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2837ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2838ab185921SStefan Hajnoczi      */
2839343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2840ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2841ab185921SStefan Hajnoczi 
2842470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2843ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2844ab185921SStefan Hajnoczi 
2845ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2846ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2847ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2848ab185921SStefan Hajnoczi 
284979c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2850ab185921SStefan Hajnoczi                              &bounce_qiov);
2851ab185921SStefan Hajnoczi     if (ret < 0) {
2852ab185921SStefan Hajnoczi         goto err;
2853ab185921SStefan Hajnoczi     }
2854ab185921SStefan Hajnoczi 
285579c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
285679c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2857621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2858aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
285979c053bdSStefan Hajnoczi     } else {
2860f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2861f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2862f05fa4adSPaolo Bonzini          */
286379c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2864ab185921SStefan Hajnoczi                                   &bounce_qiov);
286579c053bdSStefan Hajnoczi     }
286679c053bdSStefan Hajnoczi 
2867ab185921SStefan Hajnoczi     if (ret < 0) {
2868ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2869ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2870ab185921SStefan Hajnoczi          * Simply report it in all cases.
2871ab185921SStefan Hajnoczi          */
2872ab185921SStefan Hajnoczi         goto err;
2873ab185921SStefan Hajnoczi     }
2874ab185921SStefan Hajnoczi 
2875ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
287603396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2877ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2878ab185921SStefan Hajnoczi 
2879ab185921SStefan Hajnoczi err:
2880ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2881ab185921SStefan Hajnoczi     return ret;
2882ab185921SStefan Hajnoczi }
2883ab185921SStefan Hajnoczi 
2884c5fbe571SStefan Hajnoczi /*
2885c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
2886c5fbe571SStefan Hajnoczi  */
2887c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2888470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2889470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
2890da1fa91dSKevin Wolf {
2891da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2892dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
2893dbffbdcfSStefan Hajnoczi     int ret;
2894da1fa91dSKevin Wolf 
2895da1fa91dSKevin Wolf     if (!drv) {
2896da1fa91dSKevin Wolf         return -ENOMEDIUM;
2897da1fa91dSKevin Wolf     }
2898da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2899da1fa91dSKevin Wolf         return -EIO;
2900da1fa91dSKevin Wolf     }
2901da1fa91dSKevin Wolf 
2902f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
2903470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
2904470c0504SStefan Hajnoczi     }
2905470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2906470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
2907470c0504SStefan Hajnoczi     }
2908470c0504SStefan Hajnoczi 
2909470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2910f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2911f4658285SStefan Hajnoczi     }
2912f4658285SStefan Hajnoczi 
2913cc0681c4SBenoît Canet     /* throttling disk I/O */
2914cc0681c4SBenoît Canet     if (bs->io_limits_enabled) {
2915cc0681c4SBenoît Canet         bdrv_io_limits_intercept(bs, nb_sectors, false);
2916cc0681c4SBenoît Canet     }
2917cc0681c4SBenoît Canet 
2918dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2919ab185921SStefan Hajnoczi 
2920470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2921ab185921SStefan Hajnoczi         int pnum;
2922ab185921SStefan Hajnoczi 
2923bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2924ab185921SStefan Hajnoczi         if (ret < 0) {
2925ab185921SStefan Hajnoczi             goto out;
2926ab185921SStefan Hajnoczi         }
2927ab185921SStefan Hajnoczi 
2928ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2929470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2930ab185921SStefan Hajnoczi             goto out;
2931ab185921SStefan Hajnoczi         }
2932ab185921SStefan Hajnoczi     }
2933ab185921SStefan Hajnoczi 
2934893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2935dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2936893a8f62SMORITA Kazutaka     } else {
2937893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2938893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2939893a8f62SMORITA Kazutaka 
2940893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2941893a8f62SMORITA Kazutaka         if (len < 0) {
2942893a8f62SMORITA Kazutaka             ret = len;
2943893a8f62SMORITA Kazutaka             goto out;
2944893a8f62SMORITA Kazutaka         }
2945893a8f62SMORITA Kazutaka 
2946d055a1feSFam Zheng         total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
2947893a8f62SMORITA Kazutaka         max_nb_sectors = MAX(0, total_sectors - sector_num);
2948893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
2949893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
2950893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
2951893a8f62SMORITA Kazutaka         } else {
2952893a8f62SMORITA Kazutaka             ret = 0;
2953893a8f62SMORITA Kazutaka         }
2954893a8f62SMORITA Kazutaka 
2955893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
2956893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2957893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
2958893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
2959893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
2960893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
2961893a8f62SMORITA Kazutaka         }
2962893a8f62SMORITA Kazutaka     }
2963ab185921SStefan Hajnoczi 
2964ab185921SStefan Hajnoczi out:
2965dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2966470c0504SStefan Hajnoczi 
2967470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2968470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
2969470c0504SStefan Hajnoczi     }
2970470c0504SStefan Hajnoczi 
2971dbffbdcfSStefan Hajnoczi     return ret;
2972da1fa91dSKevin Wolf }
2973da1fa91dSKevin Wolf 
2974c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2975da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
2976da1fa91dSKevin Wolf {
2977c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2978da1fa91dSKevin Wolf 
2979470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2980470c0504SStefan Hajnoczi }
2981470c0504SStefan Hajnoczi 
2982470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2983470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2984470c0504SStefan Hajnoczi {
2985470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2986470c0504SStefan Hajnoczi 
2987470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2988470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
2989c5fbe571SStefan Hajnoczi }
2990c5fbe571SStefan Hajnoczi 
2991c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
2992c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
2993c31cb707SPeter Lieven  */
2994c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
2995c31cb707SPeter Lieven 
2996f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2997aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2998f08f2ddaSStefan Hajnoczi {
2999f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3000f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3001c31cb707SPeter Lieven     struct iovec iov = {0};
3002c31cb707SPeter Lieven     int ret = 0;
3003f08f2ddaSStefan Hajnoczi 
3004c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3005c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3006621f0589SKevin Wolf 
3007c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3008c31cb707SPeter Lieven         int num = nb_sectors;
3009c31cb707SPeter Lieven 
3010b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3011b8d71c09SPaolo Bonzini          * to be aligned.
3012b8d71c09SPaolo Bonzini          */
3013b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3014b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3015b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3016b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3017c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3018c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3019b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3020b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3021b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3022b8d71c09SPaolo Bonzini                  */
3023b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3024b8d71c09SPaolo Bonzini             }
3025c31cb707SPeter Lieven         }
3026c31cb707SPeter Lieven 
3027c31cb707SPeter Lieven         /* limit request size */
3028c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3029c31cb707SPeter Lieven             num = max_write_zeroes;
3030c31cb707SPeter Lieven         }
3031c31cb707SPeter Lieven 
3032c31cb707SPeter Lieven         ret = -ENOTSUP;
3033f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3034f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3035c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3036f08f2ddaSStefan Hajnoczi         }
3037f08f2ddaSStefan Hajnoczi 
3038c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3039f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3040c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3041c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3042b8d71c09SPaolo Bonzini                 iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
3043b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3044c31cb707SPeter Lieven             }
3045f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3046f08f2ddaSStefan Hajnoczi 
3047c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3048b8d71c09SPaolo Bonzini 
3049b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3050b8d71c09SPaolo Bonzini              * all future requests.
3051b8d71c09SPaolo Bonzini              */
3052b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3053b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3054b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3055b8d71c09SPaolo Bonzini             }
3056c31cb707SPeter Lieven         }
3057c31cb707SPeter Lieven 
3058c31cb707SPeter Lieven         sector_num += num;
3059c31cb707SPeter Lieven         nb_sectors -= num;
3060c31cb707SPeter Lieven     }
3061f08f2ddaSStefan Hajnoczi 
3062f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3063f08f2ddaSStefan Hajnoczi     return ret;
3064f08f2ddaSStefan Hajnoczi }
3065f08f2ddaSStefan Hajnoczi 
3066c5fbe571SStefan Hajnoczi /*
3067c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
3068c5fbe571SStefan Hajnoczi  */
3069c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
3070f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
3071f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
3072c5fbe571SStefan Hajnoczi {
3073c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
3074dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
30756b7cb247SStefan Hajnoczi     int ret;
3076da1fa91dSKevin Wolf 
3077da1fa91dSKevin Wolf     if (!bs->drv) {
3078da1fa91dSKevin Wolf         return -ENOMEDIUM;
3079da1fa91dSKevin Wolf     }
3080da1fa91dSKevin Wolf     if (bs->read_only) {
3081da1fa91dSKevin Wolf         return -EACCES;
3082da1fa91dSKevin Wolf     }
3083da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
3084da1fa91dSKevin Wolf         return -EIO;
3085da1fa91dSKevin Wolf     }
3086da1fa91dSKevin Wolf 
3087470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
3088f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
3089f4658285SStefan Hajnoczi     }
3090f4658285SStefan Hajnoczi 
3091cc0681c4SBenoît Canet     /* throttling disk I/O */
3092cc0681c4SBenoît Canet     if (bs->io_limits_enabled) {
3093cc0681c4SBenoît Canet         bdrv_io_limits_intercept(bs, nb_sectors, true);
3094cc0681c4SBenoît Canet     }
3095cc0681c4SBenoît Canet 
3096dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
3097dbffbdcfSStefan Hajnoczi 
3098d616b224SStefan Hajnoczi     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
3099d616b224SStefan Hajnoczi 
3100d616b224SStefan Hajnoczi     if (ret < 0) {
3101d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3102d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
3103aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3104f08f2ddaSStefan Hajnoczi     } else {
31056b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3106f08f2ddaSStefan Hajnoczi     }
31076b7cb247SStefan Hajnoczi 
3108f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3109f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3110f05fa4adSPaolo Bonzini     }
3111f05fa4adSPaolo Bonzini 
31121755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3113da1fa91dSKevin Wolf 
3114da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
3115da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
3116da1fa91dSKevin Wolf     }
3117df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3118df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3119df2a6f29SPaolo Bonzini     }
3120da1fa91dSKevin Wolf 
3121dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
3122dbffbdcfSStefan Hajnoczi 
31236b7cb247SStefan Hajnoczi     return ret;
3124da1fa91dSKevin Wolf }
3125da1fa91dSKevin Wolf 
3126c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3127c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3128c5fbe571SStefan Hajnoczi {
3129c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3130c5fbe571SStefan Hajnoczi 
3131f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3132f08f2ddaSStefan Hajnoczi }
3133f08f2ddaSStefan Hajnoczi 
3134f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3135aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3136aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3137f08f2ddaSStefan Hajnoczi {
313894d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3139f08f2ddaSStefan Hajnoczi 
3140d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3141d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3142d32f35cbSPeter Lieven     }
3143d32f35cbSPeter Lieven 
3144f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3145aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3146c5fbe571SStefan Hajnoczi }
3147c5fbe571SStefan Hajnoczi 
314883f64091Sbellard /**
314983f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
315083f64091Sbellard  */
315183f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
315283f64091Sbellard {
315383f64091Sbellard     BlockDriver *drv = bs->drv;
315451762288SStefan Hajnoczi     int ret;
315583f64091Sbellard     if (!drv)
315619cb3738Sbellard         return -ENOMEDIUM;
315783f64091Sbellard     if (!drv->bdrv_truncate)
315883f64091Sbellard         return -ENOTSUP;
315959f2689dSNaphtali Sprei     if (bs->read_only)
316059f2689dSNaphtali Sprei         return -EACCES;
31618591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
31628591675fSMarcelo Tosatti         return -EBUSY;
316351762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
316451762288SStefan Hajnoczi     if (ret == 0) {
316551762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3166145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
316751762288SStefan Hajnoczi     }
316851762288SStefan Hajnoczi     return ret;
316983f64091Sbellard }
317083f64091Sbellard 
317183f64091Sbellard /**
31724a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
31734a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
31744a1d5e1fSFam Zheng  */
31754a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
31764a1d5e1fSFam Zheng {
31774a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
31784a1d5e1fSFam Zheng     if (!drv) {
31794a1d5e1fSFam Zheng         return -ENOMEDIUM;
31804a1d5e1fSFam Zheng     }
31814a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
31824a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
31834a1d5e1fSFam Zheng     }
31844a1d5e1fSFam Zheng     if (bs->file) {
31854a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
31864a1d5e1fSFam Zheng     }
31874a1d5e1fSFam Zheng     return -ENOTSUP;
31884a1d5e1fSFam Zheng }
31894a1d5e1fSFam Zheng 
31904a1d5e1fSFam Zheng /**
319183f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
319283f64091Sbellard  */
319383f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
319483f64091Sbellard {
319583f64091Sbellard     BlockDriver *drv = bs->drv;
319683f64091Sbellard     if (!drv)
319719cb3738Sbellard         return -ENOMEDIUM;
319851762288SStefan Hajnoczi 
3199b94a2610SKevin Wolf     if (drv->has_variable_length) {
3200b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3201b94a2610SKevin Wolf         if (ret < 0) {
3202b94a2610SKevin Wolf             return ret;
3203fc01f7e7Sbellard         }
320446a4e4e6SStefan Hajnoczi     }
320546a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
320646a4e4e6SStefan Hajnoczi }
3207fc01f7e7Sbellard 
320819cb3738Sbellard /* return 0 as number of sectors if no device present or error */
320996b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3210fc01f7e7Sbellard {
321119cb3738Sbellard     int64_t length;
321219cb3738Sbellard     length = bdrv_getlength(bs);
321319cb3738Sbellard     if (length < 0)
321419cb3738Sbellard         length = 0;
321519cb3738Sbellard     else
32166ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
321719cb3738Sbellard     *nb_sectors_ptr = length;
3218fc01f7e7Sbellard }
3219cf98951bSbellard 
3220ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3221ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3222abd7f68dSMarkus Armbruster {
3223abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3224abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3225abd7f68dSMarkus Armbruster }
3226abd7f68dSMarkus Armbruster 
32271ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3228abd7f68dSMarkus Armbruster {
3229abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3230abd7f68dSMarkus Armbruster }
3231abd7f68dSMarkus Armbruster 
32323e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
32333e1caa5fSPaolo Bonzini {
32343e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
32353e1caa5fSPaolo Bonzini 
32363e1caa5fSPaolo Bonzini     switch (on_err) {
32373e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
32383e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
32393e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
32403e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
32413e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
32423e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
32433e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
32443e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
32453e1caa5fSPaolo Bonzini     default:
32463e1caa5fSPaolo Bonzini         abort();
32473e1caa5fSPaolo Bonzini     }
32483e1caa5fSPaolo Bonzini }
32493e1caa5fSPaolo Bonzini 
32503e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
32513e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
32523e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
32533e1caa5fSPaolo Bonzini  */
32543e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
32553e1caa5fSPaolo Bonzini                        bool is_read, int error)
32563e1caa5fSPaolo Bonzini {
32573e1caa5fSPaolo Bonzini     assert(error >= 0);
325832c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
32593e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
32603e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
32613e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
32623e1caa5fSPaolo Bonzini     }
32633e1caa5fSPaolo Bonzini }
32643e1caa5fSPaolo Bonzini 
3265b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3266b338082bSbellard {
3267b338082bSbellard     return bs->read_only;
3268b338082bSbellard }
3269b338082bSbellard 
3270985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3271985a03b0Sths {
3272985a03b0Sths     return bs->sg;
3273985a03b0Sths }
3274985a03b0Sths 
3275e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3276e900a7b7SChristoph Hellwig {
3277e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3278e900a7b7SChristoph Hellwig }
3279e900a7b7SChristoph Hellwig 
3280425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3281425b0148SPaolo Bonzini {
3282425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
328355b110f2SJeff Cody 
328455b110f2SJeff Cody     /* so a reopen() will preserve wce */
328555b110f2SJeff Cody     if (wce) {
328655b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
328755b110f2SJeff Cody     } else {
328855b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
328955b110f2SJeff Cody     }
3290425b0148SPaolo Bonzini }
3291425b0148SPaolo Bonzini 
3292ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3293ea2384d3Sbellard {
3294ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3295ea2384d3Sbellard         return 1;
3296ea2384d3Sbellard     return bs->encrypted;
3297ea2384d3Sbellard }
3298ea2384d3Sbellard 
3299c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3300c0f4ce77Saliguori {
3301c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3302c0f4ce77Saliguori 
3303c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3304c0f4ce77Saliguori         return 1;
3305c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3306c0f4ce77Saliguori }
3307c0f4ce77Saliguori 
3308ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3309ea2384d3Sbellard {
3310ea2384d3Sbellard     int ret;
3311ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3312ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3313ea2384d3Sbellard         if (ret < 0)
3314ea2384d3Sbellard             return ret;
3315ea2384d3Sbellard         if (!bs->encrypted)
3316ea2384d3Sbellard             return 0;
3317ea2384d3Sbellard     }
3318fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3319fd04a2aeSShahar Havivi         return -EINVAL;
3320fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3321fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3322fd04a2aeSShahar Havivi     }
3323c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3324bb5fc20fSaliguori     if (ret < 0) {
3325bb5fc20fSaliguori         bs->valid_key = 0;
3326bb5fc20fSaliguori     } else if (!bs->valid_key) {
3327bb5fc20fSaliguori         bs->valid_key = 1;
3328bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
33297d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3330bb5fc20fSaliguori     }
3331c0f4ce77Saliguori     return ret;
3332ea2384d3Sbellard }
3333ea2384d3Sbellard 
3334f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3335ea2384d3Sbellard {
3336f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3337ea2384d3Sbellard }
3338ea2384d3Sbellard 
3339ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3340ea2384d3Sbellard                          void *opaque)
3341ea2384d3Sbellard {
3342ea2384d3Sbellard     BlockDriver *drv;
3343ea2384d3Sbellard 
33448a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3345ea2384d3Sbellard         it(opaque, drv->format_name);
3346ea2384d3Sbellard     }
3347ea2384d3Sbellard }
3348ea2384d3Sbellard 
3349dc364f4cSBenoît Canet /* This function is to find block backend bs */
3350b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3351b338082bSbellard {
3352b338082bSbellard     BlockDriverState *bs;
3353b338082bSbellard 
3354dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
33551b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3356b338082bSbellard             return bs;
3357b338082bSbellard         }
33581b7bdbc1SStefan Hajnoczi     }
3359b338082bSbellard     return NULL;
3360b338082bSbellard }
3361b338082bSbellard 
3362dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3363dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3364dc364f4cSBenoît Canet {
3365dc364f4cSBenoît Canet     BlockDriverState *bs;
3366dc364f4cSBenoît Canet 
3367dc364f4cSBenoît Canet     assert(node_name);
3368dc364f4cSBenoît Canet 
3369dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3370dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3371dc364f4cSBenoît Canet             return bs;
3372dc364f4cSBenoît Canet         }
3373dc364f4cSBenoît Canet     }
3374dc364f4cSBenoît Canet     return NULL;
3375dc364f4cSBenoît Canet }
3376dc364f4cSBenoît Canet 
3377c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3378c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3379c13163fbSBenoît Canet {
3380c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3381c13163fbSBenoît Canet     BlockDriverState *bs;
3382c13163fbSBenoît Canet 
3383c13163fbSBenoît Canet     list = NULL;
3384c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3385c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3386c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3387c13163fbSBenoît Canet         entry->next = list;
3388c13163fbSBenoît Canet         list = entry;
3389c13163fbSBenoît Canet     }
3390c13163fbSBenoît Canet 
3391c13163fbSBenoît Canet     return list;
3392c13163fbSBenoît Canet }
3393c13163fbSBenoît Canet 
339412d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
339512d3ba82SBenoît Canet                                  const char *node_name,
339612d3ba82SBenoît Canet                                  Error **errp)
339712d3ba82SBenoît Canet {
339812d3ba82SBenoît Canet     BlockDriverState *bs = NULL;
339912d3ba82SBenoît Canet 
340012d3ba82SBenoît Canet     if ((!device && !node_name) || (device && node_name)) {
340112d3ba82SBenoît Canet         error_setg(errp, "Use either device or node-name but not both");
340212d3ba82SBenoît Canet         return NULL;
340312d3ba82SBenoît Canet     }
340412d3ba82SBenoît Canet 
340512d3ba82SBenoît Canet     if (device) {
340612d3ba82SBenoît Canet         bs = bdrv_find(device);
340712d3ba82SBenoît Canet 
340812d3ba82SBenoît Canet         if (!bs) {
340912d3ba82SBenoît Canet             error_set(errp, QERR_DEVICE_NOT_FOUND, device);
341012d3ba82SBenoît Canet             return NULL;
341112d3ba82SBenoît Canet         }
341212d3ba82SBenoît Canet 
341312d3ba82SBenoît Canet         return bs;
341412d3ba82SBenoît Canet     }
341512d3ba82SBenoît Canet 
341612d3ba82SBenoît Canet     bs = bdrv_find_node(node_name);
341712d3ba82SBenoît Canet 
341812d3ba82SBenoît Canet     if (!bs) {
341912d3ba82SBenoît Canet         error_set(errp, QERR_DEVICE_NOT_FOUND, node_name);
342012d3ba82SBenoît Canet         return NULL;
342112d3ba82SBenoît Canet     }
342212d3ba82SBenoît Canet 
342312d3ba82SBenoît Canet     return bs;
342412d3ba82SBenoît Canet }
342512d3ba82SBenoît Canet 
34262f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
34272f399b0aSMarkus Armbruster {
34282f399b0aSMarkus Armbruster     if (!bs) {
34292f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
34302f399b0aSMarkus Armbruster     }
3431dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
34322f399b0aSMarkus Armbruster }
34332f399b0aSMarkus Armbruster 
343451de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
343581d0912dSbellard {
343681d0912dSbellard     BlockDriverState *bs;
343781d0912dSbellard 
3438dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
343951de9760Saliguori         it(opaque, bs);
344081d0912dSbellard     }
344181d0912dSbellard }
344281d0912dSbellard 
3443ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3444ea2384d3Sbellard {
3445ea2384d3Sbellard     return bs->device_name;
3446ea2384d3Sbellard }
3447ea2384d3Sbellard 
3448c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3449c8433287SMarkus Armbruster {
3450c8433287SMarkus Armbruster     return bs->open_flags;
3451c8433287SMarkus Armbruster }
3452c8433287SMarkus Armbruster 
3453f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3454c6ca28d6Saliguori {
3455c6ca28d6Saliguori     BlockDriverState *bs;
3456f0f0fdfeSKevin Wolf     int result = 0;
3457c6ca28d6Saliguori 
3458dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3459f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3460f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3461f0f0fdfeSKevin Wolf             result = ret;
3462c6ca28d6Saliguori         }
34631b7bdbc1SStefan Hajnoczi     }
3464c6ca28d6Saliguori 
3465f0f0fdfeSKevin Wolf     return result;
3466f0f0fdfeSKevin Wolf }
3467f0f0fdfeSKevin Wolf 
34683ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
34693ac21627SPeter Lieven {
34703ac21627SPeter Lieven     return 1;
34713ac21627SPeter Lieven }
34723ac21627SPeter Lieven 
3473f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3474f2feebbdSKevin Wolf {
3475f2feebbdSKevin Wolf     assert(bs->drv);
3476f2feebbdSKevin Wolf 
347711212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
347811212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
347911212d8fSPaolo Bonzini     if (bs->backing_hd) {
348011212d8fSPaolo Bonzini         return 0;
348111212d8fSPaolo Bonzini     }
3482336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3483336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3484f2feebbdSKevin Wolf     }
3485f2feebbdSKevin Wolf 
34863ac21627SPeter Lieven     /* safe default */
34873ac21627SPeter Lieven     return 0;
3488f2feebbdSKevin Wolf }
3489f2feebbdSKevin Wolf 
34904ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
34914ce78691SPeter Lieven {
34924ce78691SPeter Lieven     BlockDriverInfo bdi;
34934ce78691SPeter Lieven 
34944ce78691SPeter Lieven     if (bs->backing_hd) {
34954ce78691SPeter Lieven         return false;
34964ce78691SPeter Lieven     }
34974ce78691SPeter Lieven 
34984ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
34994ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
35004ce78691SPeter Lieven     }
35014ce78691SPeter Lieven 
35024ce78691SPeter Lieven     return false;
35034ce78691SPeter Lieven }
35044ce78691SPeter Lieven 
35054ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
35064ce78691SPeter Lieven {
35074ce78691SPeter Lieven     BlockDriverInfo bdi;
35084ce78691SPeter Lieven 
35094ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
35104ce78691SPeter Lieven         return false;
35114ce78691SPeter Lieven     }
35124ce78691SPeter Lieven 
35134ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
35144ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
35154ce78691SPeter Lieven     }
35164ce78691SPeter Lieven 
35174ce78691SPeter Lieven     return false;
35184ce78691SPeter Lieven }
35194ce78691SPeter Lieven 
3520b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3521376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3522b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3523376ae3f1SStefan Hajnoczi     int64_t sector_num;
3524376ae3f1SStefan Hajnoczi     int nb_sectors;
3525376ae3f1SStefan Hajnoczi     int *pnum;
3526b6b8a333SPaolo Bonzini     int64_t ret;
3527376ae3f1SStefan Hajnoczi     bool done;
3528b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3529376ae3f1SStefan Hajnoczi 
3530f58c7b35Sths /*
3531f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3532f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3533f58c7b35Sths  * hence all their sectors are reported as allocated.
3534f58c7b35Sths  *
3535bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3536bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3537bd9533e3SStefan Hajnoczi  *
3538f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3539f58c7b35Sths  * the specified sector) that are known to be in the same
3540f58c7b35Sths  * allocated/unallocated state.
3541f58c7b35Sths  *
3542bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3543bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3544f58c7b35Sths  */
3545b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3546bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3547060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3548f58c7b35Sths {
3549617ccb46SPaolo Bonzini     int64_t length;
3550f58c7b35Sths     int64_t n;
35515daa74a6SPaolo Bonzini     int64_t ret, ret2;
3552bd9533e3SStefan Hajnoczi 
3553617ccb46SPaolo Bonzini     length = bdrv_getlength(bs);
3554617ccb46SPaolo Bonzini     if (length < 0) {
3555617ccb46SPaolo Bonzini         return length;
3556617ccb46SPaolo Bonzini     }
3557617ccb46SPaolo Bonzini 
3558617ccb46SPaolo Bonzini     if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
35596aebab14SStefan Hajnoczi         *pnum = 0;
35606aebab14SStefan Hajnoczi         return 0;
35616aebab14SStefan Hajnoczi     }
3562bd9533e3SStefan Hajnoczi 
35636aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3564bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3565bd9533e3SStefan Hajnoczi         nb_sectors = n;
3566bd9533e3SStefan Hajnoczi     }
3567bd9533e3SStefan Hajnoczi 
3568b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3569bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3570918e92d7SPaolo Bonzini         ret = BDRV_BLOCK_DATA;
3571918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3572918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3573918e92d7SPaolo Bonzini         }
3574918e92d7SPaolo Bonzini         return ret;
35756aebab14SStefan Hajnoczi     }
35766aebab14SStefan Hajnoczi 
3577415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3578415b5b01SPaolo Bonzini     if (ret < 0) {
35793e0a233dSPeter Lieven         *pnum = 0;
3580415b5b01SPaolo Bonzini         return ret;
3581415b5b01SPaolo Bonzini     }
3582415b5b01SPaolo Bonzini 
358392bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
358492bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
358592bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
358692bc50a5SPeter Lieven                                      *pnum, pnum);
358792bc50a5SPeter Lieven     }
358892bc50a5SPeter Lieven 
3589c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
3590c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
3591415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
35921f9db224SPeter Lieven         } else if (bs->backing_hd) {
3593f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
3594f0ad5712SPaolo Bonzini             int64_t length2 = bdrv_getlength(bs2);
3595f0ad5712SPaolo Bonzini             if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3596f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3597f0ad5712SPaolo Bonzini             }
3598f0ad5712SPaolo Bonzini         }
3599415b5b01SPaolo Bonzini     }
36005daa74a6SPaolo Bonzini 
36015daa74a6SPaolo Bonzini     if (bs->file &&
36025daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
36035daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
36045daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
36055daa74a6SPaolo Bonzini                                         *pnum, pnum);
36065daa74a6SPaolo Bonzini         if (ret2 >= 0) {
36075daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
36085daa74a6SPaolo Bonzini              * is useful but not necessary.
36095daa74a6SPaolo Bonzini              */
36105daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
36115daa74a6SPaolo Bonzini         }
36125daa74a6SPaolo Bonzini     }
36135daa74a6SPaolo Bonzini 
3614415b5b01SPaolo Bonzini     return ret;
3615060f51c9SStefan Hajnoczi }
3616060f51c9SStefan Hajnoczi 
3617b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3618b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3619060f51c9SStefan Hajnoczi {
3620b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3621060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3622060f51c9SStefan Hajnoczi 
3623b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3624060f51c9SStefan Hajnoczi                                          data->pnum);
3625060f51c9SStefan Hajnoczi     data->done = true;
3626060f51c9SStefan Hajnoczi }
3627060f51c9SStefan Hajnoczi 
3628060f51c9SStefan Hajnoczi /*
3629b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3630060f51c9SStefan Hajnoczi  *
3631b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
3632060f51c9SStefan Hajnoczi  */
3633b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3634b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
3635060f51c9SStefan Hajnoczi {
3636376ae3f1SStefan Hajnoczi     Coroutine *co;
3637b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
3638376ae3f1SStefan Hajnoczi         .bs = bs,
3639376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3640376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3641376ae3f1SStefan Hajnoczi         .pnum = pnum,
3642376ae3f1SStefan Hajnoczi         .done = false,
3643376ae3f1SStefan Hajnoczi     };
3644376ae3f1SStefan Hajnoczi 
3645bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
3646bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
3647b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
3648bdad13b9SPaolo Bonzini     } else {
3649b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
3650376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
3651376ae3f1SStefan Hajnoczi         while (!data.done) {
3652376ae3f1SStefan Hajnoczi             qemu_aio_wait();
3653376ae3f1SStefan Hajnoczi         }
3654bdad13b9SPaolo Bonzini     }
3655376ae3f1SStefan Hajnoczi     return data.ret;
3656376ae3f1SStefan Hajnoczi }
3657f58c7b35Sths 
3658b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
3659b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
3660b6b8a333SPaolo Bonzini {
36614333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
36624333bb71SPaolo Bonzini     if (ret < 0) {
36634333bb71SPaolo Bonzini         return ret;
36644333bb71SPaolo Bonzini     }
36654333bb71SPaolo Bonzini     return
36664333bb71SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) ||
36674333bb71SPaolo Bonzini         ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
3668b6b8a333SPaolo Bonzini }
3669b6b8a333SPaolo Bonzini 
3670188a7bbfSPaolo Bonzini /*
3671188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3672188a7bbfSPaolo Bonzini  *
3673188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3674188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3675188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3676188a7bbfSPaolo Bonzini  *
3677188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3678188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3679188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3680188a7bbfSPaolo Bonzini  *
3681188a7bbfSPaolo Bonzini  */
36824f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
3683188a7bbfSPaolo Bonzini                             BlockDriverState *base,
3684188a7bbfSPaolo Bonzini                             int64_t sector_num,
3685188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
3686188a7bbfSPaolo Bonzini {
3687188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3688188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3689188a7bbfSPaolo Bonzini 
3690188a7bbfSPaolo Bonzini     intermediate = top;
3691188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3692188a7bbfSPaolo Bonzini         int pnum_inter;
3693bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
3694188a7bbfSPaolo Bonzini                                 &pnum_inter);
3695188a7bbfSPaolo Bonzini         if (ret < 0) {
3696188a7bbfSPaolo Bonzini             return ret;
3697188a7bbfSPaolo Bonzini         } else if (ret) {
3698188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3699188a7bbfSPaolo Bonzini             return 1;
3700188a7bbfSPaolo Bonzini         }
3701188a7bbfSPaolo Bonzini 
3702188a7bbfSPaolo Bonzini         /*
3703188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3704188a7bbfSPaolo Bonzini          * might have
3705188a7bbfSPaolo Bonzini          *
3706188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3707188a7bbfSPaolo Bonzini          */
370863ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
370963ba17d3SVishvananda Ishaya             (intermediate == top ||
371063ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3711188a7bbfSPaolo Bonzini             n = pnum_inter;
3712188a7bbfSPaolo Bonzini         }
3713188a7bbfSPaolo Bonzini 
3714188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3715188a7bbfSPaolo Bonzini     }
3716188a7bbfSPaolo Bonzini 
3717188a7bbfSPaolo Bonzini     *pnum = n;
3718188a7bbfSPaolo Bonzini     return 0;
3719188a7bbfSPaolo Bonzini }
3720188a7bbfSPaolo Bonzini 
3721045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3722045df330Saliguori {
3723045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3724045df330Saliguori         return bs->backing_file;
3725045df330Saliguori     else if (bs->encrypted)
3726045df330Saliguori         return bs->filename;
3727045df330Saliguori     else
3728045df330Saliguori         return NULL;
3729045df330Saliguori }
3730045df330Saliguori 
373183f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
373283f64091Sbellard                                char *filename, int filename_size)
373383f64091Sbellard {
373483f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
373583f64091Sbellard }
373683f64091Sbellard 
3737faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3738faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3739faea38e7Sbellard {
3740faea38e7Sbellard     BlockDriver *drv = bs->drv;
3741faea38e7Sbellard     if (!drv)
374219cb3738Sbellard         return -ENOMEDIUM;
3743faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3744faea38e7Sbellard         return -ENOTSUP;
3745fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3746fbb7b4e0SKevin Wolf         return -EIO;
37477cd1e32aSlirans@il.ibm.com 
3748e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
37497cd1e32aSlirans@il.ibm.com 
3750faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3751faea38e7Sbellard }
3752faea38e7Sbellard 
3753faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3754faea38e7Sbellard {
3755faea38e7Sbellard     BlockDriver *drv = bs->drv;
3756faea38e7Sbellard     if (!drv)
375719cb3738Sbellard         return -ENOMEDIUM;
3758faea38e7Sbellard     if (!drv->bdrv_get_info)
3759faea38e7Sbellard         return -ENOTSUP;
3760faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3761faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3762faea38e7Sbellard }
3763faea38e7Sbellard 
3764eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3765eae041feSMax Reitz {
3766eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3767eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3768eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3769eae041feSMax Reitz     }
3770eae041feSMax Reitz     return NULL;
3771eae041feSMax Reitz }
3772eae041feSMax Reitz 
377345566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
377445566e9cSChristoph Hellwig                       int64_t pos, int size)
3775178e08a5Saliguori {
3776cf8074b3SKevin Wolf     QEMUIOVector qiov;
3777cf8074b3SKevin Wolf     struct iovec iov = {
3778cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
3779cf8074b3SKevin Wolf         .iov_len    = size,
3780cf8074b3SKevin Wolf     };
3781cf8074b3SKevin Wolf 
3782cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
3783cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
3784cf8074b3SKevin Wolf }
3785cf8074b3SKevin Wolf 
3786cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3787cf8074b3SKevin Wolf {
3788178e08a5Saliguori     BlockDriver *drv = bs->drv;
3789cf8074b3SKevin Wolf 
3790cf8074b3SKevin Wolf     if (!drv) {
3791178e08a5Saliguori         return -ENOMEDIUM;
3792cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
3793cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
3794cf8074b3SKevin Wolf     } else if (bs->file) {
3795cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
3796cf8074b3SKevin Wolf     }
3797cf8074b3SKevin Wolf 
37987cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3799178e08a5Saliguori }
3800178e08a5Saliguori 
380145566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
380245566e9cSChristoph Hellwig                       int64_t pos, int size)
3803178e08a5Saliguori {
3804178e08a5Saliguori     BlockDriver *drv = bs->drv;
3805178e08a5Saliguori     if (!drv)
3806178e08a5Saliguori         return -ENOMEDIUM;
38077cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
380845566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
38097cdb1f6dSMORITA Kazutaka     if (bs->file)
38107cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
38117cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3812178e08a5Saliguori }
3813178e08a5Saliguori 
38148b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
38158b9b0cc2SKevin Wolf {
3816bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
38178b9b0cc2SKevin Wolf         return;
38188b9b0cc2SKevin Wolf     }
38198b9b0cc2SKevin Wolf 
3820bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
382141c695c7SKevin Wolf }
38228b9b0cc2SKevin Wolf 
382341c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
382441c695c7SKevin Wolf                           const char *tag)
382541c695c7SKevin Wolf {
382641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
382741c695c7SKevin Wolf         bs = bs->file;
382841c695c7SKevin Wolf     }
382941c695c7SKevin Wolf 
383041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
383141c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
383241c695c7SKevin Wolf     }
383341c695c7SKevin Wolf 
383441c695c7SKevin Wolf     return -ENOTSUP;
383541c695c7SKevin Wolf }
383641c695c7SKevin Wolf 
38374cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
38384cc70e93SFam Zheng {
38394cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
38404cc70e93SFam Zheng         bs = bs->file;
38414cc70e93SFam Zheng     }
38424cc70e93SFam Zheng 
38434cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
38444cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
38454cc70e93SFam Zheng     }
38464cc70e93SFam Zheng 
38474cc70e93SFam Zheng     return -ENOTSUP;
38484cc70e93SFam Zheng }
38494cc70e93SFam Zheng 
385041c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
385141c695c7SKevin Wolf {
385241c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
385341c695c7SKevin Wolf         bs = bs->file;
385441c695c7SKevin Wolf     }
385541c695c7SKevin Wolf 
385641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
385741c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
385841c695c7SKevin Wolf     }
385941c695c7SKevin Wolf 
386041c695c7SKevin Wolf     return -ENOTSUP;
386141c695c7SKevin Wolf }
386241c695c7SKevin Wolf 
386341c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
386441c695c7SKevin Wolf {
386541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
386641c695c7SKevin Wolf         bs = bs->file;
386741c695c7SKevin Wolf     }
386841c695c7SKevin Wolf 
386941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
387041c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
387141c695c7SKevin Wolf     }
387241c695c7SKevin Wolf 
387341c695c7SKevin Wolf     return false;
38748b9b0cc2SKevin Wolf }
38758b9b0cc2SKevin Wolf 
3876199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3877199630b6SBlue Swirl {
3878199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3879199630b6SBlue Swirl }
3880199630b6SBlue Swirl 
3881b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3882b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3883b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3884b1b1d783SJeff Cody  * the CWD rather than the chain. */
3885e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3886e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3887e8a6bb9cSMarcelo Tosatti {
3888b1b1d783SJeff Cody     char *filename_full = NULL;
3889b1b1d783SJeff Cody     char *backing_file_full = NULL;
3890b1b1d783SJeff Cody     char *filename_tmp = NULL;
3891b1b1d783SJeff Cody     int is_protocol = 0;
3892b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3893b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3894b1b1d783SJeff Cody 
3895b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3896e8a6bb9cSMarcelo Tosatti         return NULL;
3897e8a6bb9cSMarcelo Tosatti     }
3898e8a6bb9cSMarcelo Tosatti 
3899b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3900b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3901b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3902b1b1d783SJeff Cody 
3903b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3904b1b1d783SJeff Cody 
3905b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3906b1b1d783SJeff Cody 
3907b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3908b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3909b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3910b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3911b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3912b1b1d783SJeff Cody                 break;
3913b1b1d783SJeff Cody             }
3914e8a6bb9cSMarcelo Tosatti         } else {
3915b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3916b1b1d783SJeff Cody              * image's filename path */
3917b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3918b1b1d783SJeff Cody                          backing_file);
3919b1b1d783SJeff Cody 
3920b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3921b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3922b1b1d783SJeff Cody                 continue;
3923b1b1d783SJeff Cody             }
3924b1b1d783SJeff Cody 
3925b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3926b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3927b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3928b1b1d783SJeff Cody                          curr_bs->backing_file);
3929b1b1d783SJeff Cody 
3930b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3931b1b1d783SJeff Cody                 continue;
3932b1b1d783SJeff Cody             }
3933b1b1d783SJeff Cody 
3934b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3935b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3936b1b1d783SJeff Cody                 break;
3937b1b1d783SJeff Cody             }
3938e8a6bb9cSMarcelo Tosatti         }
3939e8a6bb9cSMarcelo Tosatti     }
3940e8a6bb9cSMarcelo Tosatti 
3941b1b1d783SJeff Cody     g_free(filename_full);
3942b1b1d783SJeff Cody     g_free(backing_file_full);
3943b1b1d783SJeff Cody     g_free(filename_tmp);
3944b1b1d783SJeff Cody     return retval;
3945e8a6bb9cSMarcelo Tosatti }
3946e8a6bb9cSMarcelo Tosatti 
3947f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3948f198fd1cSBenoît Canet {
3949f198fd1cSBenoît Canet     if (!bs->drv) {
3950f198fd1cSBenoît Canet         return 0;
3951f198fd1cSBenoît Canet     }
3952f198fd1cSBenoît Canet 
3953f198fd1cSBenoît Canet     if (!bs->backing_hd) {
3954f198fd1cSBenoît Canet         return 0;
3955f198fd1cSBenoît Canet     }
3956f198fd1cSBenoît Canet 
3957f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3958f198fd1cSBenoît Canet }
3959f198fd1cSBenoît Canet 
396079fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
396179fac568SJeff Cody {
396279fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
396379fac568SJeff Cody 
396479fac568SJeff Cody     if (!bs) {
396579fac568SJeff Cody         return NULL;
396679fac568SJeff Cody     }
396779fac568SJeff Cody 
396879fac568SJeff Cody     curr_bs = bs;
396979fac568SJeff Cody 
397079fac568SJeff Cody     while (curr_bs->backing_hd) {
397179fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
397279fac568SJeff Cody     }
397379fac568SJeff Cody     return curr_bs;
397479fac568SJeff Cody }
397579fac568SJeff Cody 
3976ea2384d3Sbellard /**************************************************************/
397783f64091Sbellard /* async I/Os */
3978ea2384d3Sbellard 
39793b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3980f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
398183f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
3982ea2384d3Sbellard {
3983bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3984bbf0a440SStefan Hajnoczi 
3985d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
39868c5873d6SStefan Hajnoczi                                  cb, opaque, false);
398783f64091Sbellard }
398883f64091Sbellard 
3989f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3990f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
399183f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
39927674e7bfSbellard {
3993bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3994bbf0a440SStefan Hajnoczi 
3995d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
39968c5873d6SStefan Hajnoczi                                  cb, opaque, true);
399783f64091Sbellard }
399883f64091Sbellard 
3999d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4000d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4001d5ef94d4SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
4002d5ef94d4SPaolo Bonzini {
4003d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4004d5ef94d4SPaolo Bonzini 
4005d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4006d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4007d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4008d5ef94d4SPaolo Bonzini }
4009d5ef94d4SPaolo Bonzini 
401040b4f539SKevin Wolf 
401140b4f539SKevin Wolf typedef struct MultiwriteCB {
401240b4f539SKevin Wolf     int error;
401340b4f539SKevin Wolf     int num_requests;
401440b4f539SKevin Wolf     int num_callbacks;
401540b4f539SKevin Wolf     struct {
401640b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
401740b4f539SKevin Wolf         void *opaque;
401840b4f539SKevin Wolf         QEMUIOVector *free_qiov;
401940b4f539SKevin Wolf     } callbacks[];
402040b4f539SKevin Wolf } MultiwriteCB;
402140b4f539SKevin Wolf 
402240b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
402340b4f539SKevin Wolf {
402440b4f539SKevin Wolf     int i;
402540b4f539SKevin Wolf 
402640b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
402740b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
40281e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
40291e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
40301e1ea48dSStefan Hajnoczi         }
40317267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
403240b4f539SKevin Wolf     }
403340b4f539SKevin Wolf }
403440b4f539SKevin Wolf 
403540b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
403640b4f539SKevin Wolf {
403740b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
403840b4f539SKevin Wolf 
40396d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
40406d519a5fSStefan Hajnoczi 
4041cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
404240b4f539SKevin Wolf         mcb->error = ret;
404340b4f539SKevin Wolf     }
404440b4f539SKevin Wolf 
404540b4f539SKevin Wolf     mcb->num_requests--;
404640b4f539SKevin Wolf     if (mcb->num_requests == 0) {
404740b4f539SKevin Wolf         multiwrite_user_cb(mcb);
40487267c094SAnthony Liguori         g_free(mcb);
404940b4f539SKevin Wolf     }
405040b4f539SKevin Wolf }
405140b4f539SKevin Wolf 
405240b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
405340b4f539SKevin Wolf {
405477be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
405577be4366SChristoph Hellwig 
405677be4366SChristoph Hellwig     /*
405777be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
405877be4366SChristoph Hellwig      * here as that could overflow the return value.
405977be4366SChristoph Hellwig      */
406077be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
406177be4366SChristoph Hellwig         return 1;
406277be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
406377be4366SChristoph Hellwig         return -1;
406477be4366SChristoph Hellwig     } else {
406577be4366SChristoph Hellwig         return 0;
406677be4366SChristoph Hellwig     }
406740b4f539SKevin Wolf }
406840b4f539SKevin Wolf 
406940b4f539SKevin Wolf /*
407040b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
407140b4f539SKevin Wolf  * requests that remain after merging.
407240b4f539SKevin Wolf  */
407340b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
407440b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
407540b4f539SKevin Wolf {
407640b4f539SKevin Wolf     int i, outidx;
407740b4f539SKevin Wolf 
407840b4f539SKevin Wolf     // Sort requests by start sector
407940b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
408040b4f539SKevin Wolf 
408140b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
408240b4f539SKevin Wolf     // filling up gaps with zero sectors.
408340b4f539SKevin Wolf     outidx = 0;
408440b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
408540b4f539SKevin Wolf         int merge = 0;
408640b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
408740b4f539SKevin Wolf 
4088b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
408940b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
409040b4f539SKevin Wolf             merge = 1;
409140b4f539SKevin Wolf         }
409240b4f539SKevin Wolf 
4093e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4094e2a305fbSChristoph Hellwig             merge = 0;
4095e2a305fbSChristoph Hellwig         }
4096e2a305fbSChristoph Hellwig 
409740b4f539SKevin Wolf         if (merge) {
409840b4f539SKevin Wolf             size_t size;
40997267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
410040b4f539SKevin Wolf             qemu_iovec_init(qiov,
410140b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
410240b4f539SKevin Wolf 
410340b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
410440b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
410540b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
41061b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
410740b4f539SKevin Wolf 
4108b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4109b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
411040b4f539SKevin Wolf 
411140b4f539SKevin Wolf             // Add the second request
41121b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
411340b4f539SKevin Wolf 
4114cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
411540b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
411640b4f539SKevin Wolf 
411740b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
411840b4f539SKevin Wolf         } else {
411940b4f539SKevin Wolf             outidx++;
412040b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
412140b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
412240b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
412340b4f539SKevin Wolf         }
412440b4f539SKevin Wolf     }
412540b4f539SKevin Wolf 
412640b4f539SKevin Wolf     return outidx + 1;
412740b4f539SKevin Wolf }
412840b4f539SKevin Wolf 
412940b4f539SKevin Wolf /*
413040b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
413140b4f539SKevin Wolf  *
413240b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
413340b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
413440b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
413540b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
413640b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
413740b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
413840b4f539SKevin Wolf  *
413940b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
414040b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
414140b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
414240b4f539SKevin Wolf  */
414340b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
414440b4f539SKevin Wolf {
414540b4f539SKevin Wolf     MultiwriteCB *mcb;
414640b4f539SKevin Wolf     int i;
414740b4f539SKevin Wolf 
4148301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4149301db7c2SRyan Harper     if (bs->drv == NULL) {
4150301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4151301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4152301db7c2SRyan Harper         }
4153301db7c2SRyan Harper         return -1;
4154301db7c2SRyan Harper     }
4155301db7c2SRyan Harper 
415640b4f539SKevin Wolf     if (num_reqs == 0) {
415740b4f539SKevin Wolf         return 0;
415840b4f539SKevin Wolf     }
415940b4f539SKevin Wolf 
416040b4f539SKevin Wolf     // Create MultiwriteCB structure
41617267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
416240b4f539SKevin Wolf     mcb->num_requests = 0;
416340b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
416440b4f539SKevin Wolf 
416540b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
416640b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
416740b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
416840b4f539SKevin Wolf     }
416940b4f539SKevin Wolf 
417040b4f539SKevin Wolf     // Check for mergable requests
417140b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
417240b4f539SKevin Wolf 
41736d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
41746d519a5fSStefan Hajnoczi 
4175df9309fbSPaolo Bonzini     /* Run the aio requests. */
4176df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
417740b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4178d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4179d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4180d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4181d20d9b7cSPaolo Bonzini                               true);
418240b4f539SKevin Wolf     }
418340b4f539SKevin Wolf 
418440b4f539SKevin Wolf     return 0;
418540b4f539SKevin Wolf }
418640b4f539SKevin Wolf 
418783f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
418883f64091Sbellard {
4189d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
419083f64091Sbellard }
419183f64091Sbellard 
419283f64091Sbellard /**************************************************************/
419383f64091Sbellard /* async block device emulation */
419483f64091Sbellard 
4195c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4196c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4197c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4198c16b5a2cSChristoph Hellwig     int ret;
4199c16b5a2cSChristoph Hellwig     /* vector translation state */
4200c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4201c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4202c16b5a2cSChristoph Hellwig     int is_write;
4203c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4204c16b5a2cSChristoph Hellwig 
4205c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4206c16b5a2cSChristoph Hellwig {
4207b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
4208b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
42096a7ad299SDor Laor     qemu_bh_delete(acb->bh);
421036afc451SAvi Kivity     acb->bh = NULL;
4211c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
4212c16b5a2cSChristoph Hellwig }
4213c16b5a2cSChristoph Hellwig 
4214d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4215c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4216c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
4217c16b5a2cSChristoph Hellwig };
4218c16b5a2cSChristoph Hellwig 
421983f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4220beac80cdSbellard {
4221ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4222f141eafeSaliguori 
4223f141eafeSaliguori     if (!acb->is_write)
422403396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4225ceb42de8Saliguori     qemu_vfree(acb->bounce);
4226ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
42276a7ad299SDor Laor     qemu_bh_delete(acb->bh);
422836afc451SAvi Kivity     acb->bh = NULL;
4229ce1a14dcSpbrook     qemu_aio_release(acb);
4230beac80cdSbellard }
4231beac80cdSbellard 
4232f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4233f141eafeSaliguori                                             int64_t sector_num,
4234f141eafeSaliguori                                             QEMUIOVector *qiov,
4235f141eafeSaliguori                                             int nb_sectors,
4236f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4237f141eafeSaliguori                                             void *opaque,
4238f141eafeSaliguori                                             int is_write)
4239f141eafeSaliguori 
4240ea2384d3Sbellard {
4241ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
424283f64091Sbellard 
4243d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4244f141eafeSaliguori     acb->is_write = is_write;
4245f141eafeSaliguori     acb->qiov = qiov;
4246e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
4247ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4248f141eafeSaliguori 
4249f141eafeSaliguori     if (is_write) {
4250d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
42511ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4252f141eafeSaliguori     } else {
42531ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4254f141eafeSaliguori     }
4255f141eafeSaliguori 
4256ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4257f141eafeSaliguori 
4258ce1a14dcSpbrook     return &acb->common;
42597a6cba61Spbrook }
42607a6cba61Spbrook 
4261f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4262f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4263ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
426483f64091Sbellard {
4265f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
426683f64091Sbellard }
426783f64091Sbellard 
4268f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4269f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4270f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4271f141eafeSaliguori {
4272f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4273f141eafeSaliguori }
4274f141eafeSaliguori 
427568485420SKevin Wolf 
427668485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
427768485420SKevin Wolf     BlockDriverAIOCB common;
427868485420SKevin Wolf     BlockRequest req;
427968485420SKevin Wolf     bool is_write;
4280d318aea9SKevin Wolf     bool *done;
428168485420SKevin Wolf     QEMUBH* bh;
428268485420SKevin Wolf } BlockDriverAIOCBCoroutine;
428368485420SKevin Wolf 
428468485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
428568485420SKevin Wolf {
4286d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
4287d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4288d318aea9SKevin Wolf     bool done = false;
4289d318aea9SKevin Wolf 
4290d318aea9SKevin Wolf     acb->done = &done;
4291d318aea9SKevin Wolf     while (!done) {
4292d318aea9SKevin Wolf         qemu_aio_wait();
4293d318aea9SKevin Wolf     }
429468485420SKevin Wolf }
429568485420SKevin Wolf 
4296d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
429768485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
429868485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
429968485420SKevin Wolf };
430068485420SKevin Wolf 
430135246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
430268485420SKevin Wolf {
430368485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
430468485420SKevin Wolf 
430568485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4306d318aea9SKevin Wolf 
4307d318aea9SKevin Wolf     if (acb->done) {
4308d318aea9SKevin Wolf         *acb->done = true;
4309d318aea9SKevin Wolf     }
4310d318aea9SKevin Wolf 
431168485420SKevin Wolf     qemu_bh_delete(acb->bh);
431268485420SKevin Wolf     qemu_aio_release(acb);
431368485420SKevin Wolf }
431468485420SKevin Wolf 
4315b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4316b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4317b2a61371SStefan Hajnoczi {
4318b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4319b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4320b2a61371SStefan Hajnoczi 
4321b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4322b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4323d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4324b2a61371SStefan Hajnoczi     } else {
4325b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4326d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4327b2a61371SStefan Hajnoczi     }
4328b2a61371SStefan Hajnoczi 
432935246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4330b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4331b2a61371SStefan Hajnoczi }
4332b2a61371SStefan Hajnoczi 
433368485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
433468485420SKevin Wolf                                                int64_t sector_num,
433568485420SKevin Wolf                                                QEMUIOVector *qiov,
433668485420SKevin Wolf                                                int nb_sectors,
4337d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
433868485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
433968485420SKevin Wolf                                                void *opaque,
43408c5873d6SStefan Hajnoczi                                                bool is_write)
434168485420SKevin Wolf {
434268485420SKevin Wolf     Coroutine *co;
434368485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
434468485420SKevin Wolf 
4345d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
434668485420SKevin Wolf     acb->req.sector = sector_num;
434768485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
434868485420SKevin Wolf     acb->req.qiov = qiov;
4349d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
435068485420SKevin Wolf     acb->is_write = is_write;
4351d318aea9SKevin Wolf     acb->done = NULL;
435268485420SKevin Wolf 
43538c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
435468485420SKevin Wolf     qemu_coroutine_enter(co, acb);
435568485420SKevin Wolf 
435668485420SKevin Wolf     return &acb->common;
435768485420SKevin Wolf }
435868485420SKevin Wolf 
435907f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4360b2e12bc6SChristoph Hellwig {
436107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
436207f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4363b2e12bc6SChristoph Hellwig 
436407f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
436507f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4366b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4367b2e12bc6SChristoph Hellwig }
4368b2e12bc6SChristoph Hellwig 
436907f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4370016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4371016f5cf6SAlexander Graf {
437207f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4373016f5cf6SAlexander Graf 
437407f07615SPaolo Bonzini     Coroutine *co;
437507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4376016f5cf6SAlexander Graf 
4377d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4378d318aea9SKevin Wolf     acb->done = NULL;
4379d318aea9SKevin Wolf 
438007f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
438107f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4382016f5cf6SAlexander Graf 
4383016f5cf6SAlexander Graf     return &acb->common;
4384016f5cf6SAlexander Graf }
4385016f5cf6SAlexander Graf 
43864265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
43874265d620SPaolo Bonzini {
43884265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
43894265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
43904265d620SPaolo Bonzini 
43914265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
43924265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
43934265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
43944265d620SPaolo Bonzini }
43954265d620SPaolo Bonzini 
43964265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
43974265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
43984265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
43994265d620SPaolo Bonzini {
44004265d620SPaolo Bonzini     Coroutine *co;
44014265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
44024265d620SPaolo Bonzini 
44034265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
44044265d620SPaolo Bonzini 
4405d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
44064265d620SPaolo Bonzini     acb->req.sector = sector_num;
44074265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4408d318aea9SKevin Wolf     acb->done = NULL;
44094265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
44104265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
44114265d620SPaolo Bonzini 
44124265d620SPaolo Bonzini     return &acb->common;
44134265d620SPaolo Bonzini }
44144265d620SPaolo Bonzini 
4415ea2384d3Sbellard void bdrv_init(void)
4416ea2384d3Sbellard {
44175efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4418ea2384d3Sbellard }
4419ce1a14dcSpbrook 
4420eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4421eb852011SMarkus Armbruster {
4422eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4423eb852011SMarkus Armbruster     bdrv_init();
4424eb852011SMarkus Armbruster }
4425eb852011SMarkus Armbruster 
4426d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
44276bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
44286bbff9a0Saliguori {
4429ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4430ce1a14dcSpbrook 
4431d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4432d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4433ce1a14dcSpbrook     acb->bs = bs;
4434ce1a14dcSpbrook     acb->cb = cb;
4435ce1a14dcSpbrook     acb->opaque = opaque;
4436ce1a14dcSpbrook     return acb;
4437ce1a14dcSpbrook }
4438ce1a14dcSpbrook 
4439ce1a14dcSpbrook void qemu_aio_release(void *p)
4440ce1a14dcSpbrook {
4441d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4442d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4443ce1a14dcSpbrook }
444419cb3738Sbellard 
444519cb3738Sbellard /**************************************************************/
4446f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4447f9f05dc5SKevin Wolf 
4448f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4449f9f05dc5SKevin Wolf     Coroutine *coroutine;
4450f9f05dc5SKevin Wolf     int ret;
4451f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4452f9f05dc5SKevin Wolf 
4453f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4454f9f05dc5SKevin Wolf {
4455f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4456f9f05dc5SKevin Wolf 
4457f9f05dc5SKevin Wolf     co->ret = ret;
4458f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4459f9f05dc5SKevin Wolf }
4460f9f05dc5SKevin Wolf 
4461f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4462f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4463f9f05dc5SKevin Wolf                                       bool is_write)
4464f9f05dc5SKevin Wolf {
4465f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4466f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4467f9f05dc5SKevin Wolf     };
4468f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4469f9f05dc5SKevin Wolf 
4470f9f05dc5SKevin Wolf     if (is_write) {
4471a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4472f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4473f9f05dc5SKevin Wolf     } else {
4474a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4475f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4476f9f05dc5SKevin Wolf     }
4477f9f05dc5SKevin Wolf 
447859370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4479f9f05dc5SKevin Wolf     if (!acb) {
4480f9f05dc5SKevin Wolf         return -EIO;
4481f9f05dc5SKevin Wolf     }
4482f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4483f9f05dc5SKevin Wolf 
4484f9f05dc5SKevin Wolf     return co.ret;
4485f9f05dc5SKevin Wolf }
4486f9f05dc5SKevin Wolf 
4487f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4488f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4489f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4490f9f05dc5SKevin Wolf {
4491f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4492f9f05dc5SKevin Wolf }
4493f9f05dc5SKevin Wolf 
4494f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4495f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4496f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4497f9f05dc5SKevin Wolf {
4498f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4499f9f05dc5SKevin Wolf }
4500f9f05dc5SKevin Wolf 
450107f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4502e7a8a783SKevin Wolf {
450307f07615SPaolo Bonzini     RwCo *rwco = opaque;
450407f07615SPaolo Bonzini 
450507f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
450607f07615SPaolo Bonzini }
450707f07615SPaolo Bonzini 
450807f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
450907f07615SPaolo Bonzini {
4510eb489bb1SKevin Wolf     int ret;
4511eb489bb1SKevin Wolf 
451229cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
451307f07615SPaolo Bonzini         return 0;
4514eb489bb1SKevin Wolf     }
4515eb489bb1SKevin Wolf 
4516ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4517bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4518eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4519eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4520eb489bb1SKevin Wolf         if (ret < 0) {
4521eb489bb1SKevin Wolf             return ret;
4522eb489bb1SKevin Wolf         }
4523eb489bb1SKevin Wolf     }
4524eb489bb1SKevin Wolf 
4525ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4526ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4527d4c82329SKevin Wolf         goto flush_parent;
4528ca716364SKevin Wolf     }
4529ca716364SKevin Wolf 
4530bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4531eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
453229cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
453307f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
453407f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4535e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4536e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4537e7a8a783SKevin Wolf         };
4538e7a8a783SKevin Wolf 
453907f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
454007f07615SPaolo Bonzini         if (acb == NULL) {
454129cdb251SPaolo Bonzini             ret = -EIO;
454207f07615SPaolo Bonzini         } else {
4543e7a8a783SKevin Wolf             qemu_coroutine_yield();
454429cdb251SPaolo Bonzini             ret = co.ret;
4545e7a8a783SKevin Wolf         }
454607f07615SPaolo Bonzini     } else {
454707f07615SPaolo Bonzini         /*
454807f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
454907f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
455007f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
455107f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
455207f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
455307f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
455407f07615SPaolo Bonzini          * mode.
455507f07615SPaolo Bonzini          *
455607f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
455707f07615SPaolo Bonzini          */
455829cdb251SPaolo Bonzini         ret = 0;
455907f07615SPaolo Bonzini     }
456029cdb251SPaolo Bonzini     if (ret < 0) {
456129cdb251SPaolo Bonzini         return ret;
456229cdb251SPaolo Bonzini     }
456329cdb251SPaolo Bonzini 
456429cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
456529cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
456629cdb251SPaolo Bonzini      */
4567d4c82329SKevin Wolf flush_parent:
456829cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
456907f07615SPaolo Bonzini }
457007f07615SPaolo Bonzini 
45710f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
45720f15423cSAnthony Liguori {
45730f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
45740f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
45750f15423cSAnthony Liguori     }
45760f15423cSAnthony Liguori }
45770f15423cSAnthony Liguori 
45780f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
45790f15423cSAnthony Liguori {
45800f15423cSAnthony Liguori     BlockDriverState *bs;
45810f15423cSAnthony Liguori 
4582dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
45830f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
45840f15423cSAnthony Liguori     }
45850f15423cSAnthony Liguori }
45860f15423cSAnthony Liguori 
458707789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
458807789269SBenoît Canet {
458907789269SBenoît Canet     BlockDriverState *bs;
459007789269SBenoît Canet 
4591dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
459207789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
459307789269SBenoît Canet     }
459407789269SBenoît Canet }
459507789269SBenoît Canet 
459607f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
459707f07615SPaolo Bonzini {
459807f07615SPaolo Bonzini     Coroutine *co;
459907f07615SPaolo Bonzini     RwCo rwco = {
460007f07615SPaolo Bonzini         .bs = bs,
460107f07615SPaolo Bonzini         .ret = NOT_DONE,
460207f07615SPaolo Bonzini     };
460307f07615SPaolo Bonzini 
460407f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
460507f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
460607f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
460707f07615SPaolo Bonzini     } else {
460807f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
460907f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
461007f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
461107f07615SPaolo Bonzini             qemu_aio_wait();
461207f07615SPaolo Bonzini         }
461307f07615SPaolo Bonzini     }
461407f07615SPaolo Bonzini 
461507f07615SPaolo Bonzini     return rwco.ret;
461607f07615SPaolo Bonzini }
4617e7a8a783SKevin Wolf 
46184265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
46194265d620SPaolo Bonzini {
46204265d620SPaolo Bonzini     RwCo *rwco = opaque;
46214265d620SPaolo Bonzini 
46224265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
46234265d620SPaolo Bonzini }
46244265d620SPaolo Bonzini 
46256f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
46266f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
46276f14da52SPeter Lieven  */
46286f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
46296f14da52SPeter Lieven 
46304265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
46314265d620SPaolo Bonzini                                  int nb_sectors)
46324265d620SPaolo Bonzini {
4633d51e9fe5SPaolo Bonzini     int max_discard;
4634d51e9fe5SPaolo Bonzini 
46354265d620SPaolo Bonzini     if (!bs->drv) {
46364265d620SPaolo Bonzini         return -ENOMEDIUM;
46374265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
46384265d620SPaolo Bonzini         return -EIO;
46394265d620SPaolo Bonzini     } else if (bs->read_only) {
46404265d620SPaolo Bonzini         return -EROFS;
4641df702c9bSPaolo Bonzini     }
4642df702c9bSPaolo Bonzini 
46438f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
4644df702c9bSPaolo Bonzini 
46459e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
46469e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
46479e8f1835SPaolo Bonzini         return 0;
46489e8f1835SPaolo Bonzini     }
46499e8f1835SPaolo Bonzini 
4650d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
4651d51e9fe5SPaolo Bonzini         return 0;
4652d51e9fe5SPaolo Bonzini     }
46536f14da52SPeter Lieven 
4654d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
46556f14da52SPeter Lieven     while (nb_sectors > 0) {
46566f14da52SPeter Lieven         int ret;
46576f14da52SPeter Lieven         int num = nb_sectors;
46586f14da52SPeter Lieven 
46596f14da52SPeter Lieven         /* align request */
46606f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
46616f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
46626f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
46636f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
46646f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
46656f14da52SPeter Lieven             }
46666f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
46676f14da52SPeter Lieven         }
46686f14da52SPeter Lieven 
46696f14da52SPeter Lieven         /* limit request size */
46706f14da52SPeter Lieven         if (num > max_discard) {
46716f14da52SPeter Lieven             num = max_discard;
46726f14da52SPeter Lieven         }
46736f14da52SPeter Lieven 
4674d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
46756f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
4676d51e9fe5SPaolo Bonzini         } else {
46774265d620SPaolo Bonzini             BlockDriverAIOCB *acb;
46784265d620SPaolo Bonzini             CoroutineIOCompletion co = {
46794265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
46804265d620SPaolo Bonzini             };
46814265d620SPaolo Bonzini 
46824265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
46834265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
46844265d620SPaolo Bonzini             if (acb == NULL) {
46854265d620SPaolo Bonzini                 return -EIO;
46864265d620SPaolo Bonzini             } else {
46874265d620SPaolo Bonzini                 qemu_coroutine_yield();
4688d51e9fe5SPaolo Bonzini                 ret = co.ret;
46894265d620SPaolo Bonzini             }
4690d51e9fe5SPaolo Bonzini         }
46917ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
4692d51e9fe5SPaolo Bonzini             return ret;
4693d51e9fe5SPaolo Bonzini         }
4694d51e9fe5SPaolo Bonzini 
4695d51e9fe5SPaolo Bonzini         sector_num += num;
4696d51e9fe5SPaolo Bonzini         nb_sectors -= num;
4697d51e9fe5SPaolo Bonzini     }
46984265d620SPaolo Bonzini     return 0;
46994265d620SPaolo Bonzini }
47004265d620SPaolo Bonzini 
47014265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
47024265d620SPaolo Bonzini {
47034265d620SPaolo Bonzini     Coroutine *co;
47044265d620SPaolo Bonzini     RwCo rwco = {
47054265d620SPaolo Bonzini         .bs = bs,
47064265d620SPaolo Bonzini         .sector_num = sector_num,
47074265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
47084265d620SPaolo Bonzini         .ret = NOT_DONE,
47094265d620SPaolo Bonzini     };
47104265d620SPaolo Bonzini 
47114265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
47124265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
47134265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
47144265d620SPaolo Bonzini     } else {
47154265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
47164265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
47174265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
47184265d620SPaolo Bonzini             qemu_aio_wait();
47194265d620SPaolo Bonzini         }
47204265d620SPaolo Bonzini     }
47214265d620SPaolo Bonzini 
47224265d620SPaolo Bonzini     return rwco.ret;
47234265d620SPaolo Bonzini }
47244265d620SPaolo Bonzini 
4725f9f05dc5SKevin Wolf /**************************************************************/
472619cb3738Sbellard /* removable device support */
472719cb3738Sbellard 
472819cb3738Sbellard /**
472919cb3738Sbellard  * Return TRUE if the media is present
473019cb3738Sbellard  */
473119cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
473219cb3738Sbellard {
473319cb3738Sbellard     BlockDriver *drv = bs->drv;
4734a1aff5bfSMarkus Armbruster 
473519cb3738Sbellard     if (!drv)
473619cb3738Sbellard         return 0;
473719cb3738Sbellard     if (!drv->bdrv_is_inserted)
4738a1aff5bfSMarkus Armbruster         return 1;
4739a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
474019cb3738Sbellard }
474119cb3738Sbellard 
474219cb3738Sbellard /**
47438e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
47448e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
474519cb3738Sbellard  */
474619cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
474719cb3738Sbellard {
474819cb3738Sbellard     BlockDriver *drv = bs->drv;
474919cb3738Sbellard 
47508e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
47518e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
47528e49ca46SMarkus Armbruster     }
47538e49ca46SMarkus Armbruster     return -ENOTSUP;
475419cb3738Sbellard }
475519cb3738Sbellard 
475619cb3738Sbellard /**
475719cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
475819cb3738Sbellard  */
4759f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
476019cb3738Sbellard {
476119cb3738Sbellard     BlockDriver *drv = bs->drv;
476219cb3738Sbellard 
4763822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4764822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
476519cb3738Sbellard     }
47666f382ed2SLuiz Capitulino 
47676f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
47686f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
47696f382ed2SLuiz Capitulino     }
477019cb3738Sbellard }
477119cb3738Sbellard 
477219cb3738Sbellard /**
477319cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
477419cb3738Sbellard  * to eject it manually).
477519cb3738Sbellard  */
4776025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
477719cb3738Sbellard {
477819cb3738Sbellard     BlockDriver *drv = bs->drv;
477919cb3738Sbellard 
4780025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4781b8c6d095SStefan Hajnoczi 
4782025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4783025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
478419cb3738Sbellard     }
478519cb3738Sbellard }
4786985a03b0Sths 
4787985a03b0Sths /* needed for generic scsi interface */
4788985a03b0Sths 
4789985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4790985a03b0Sths {
4791985a03b0Sths     BlockDriver *drv = bs->drv;
4792985a03b0Sths 
4793985a03b0Sths     if (drv && drv->bdrv_ioctl)
4794985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4795985a03b0Sths     return -ENOTSUP;
4796985a03b0Sths }
47977d780669Saliguori 
4798221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4799221f715dSaliguori         unsigned long int req, void *buf,
48007d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
48017d780669Saliguori {
4802221f715dSaliguori     BlockDriver *drv = bs->drv;
48037d780669Saliguori 
4804221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4805221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4806221f715dSaliguori     return NULL;
48077d780669Saliguori }
4808e268ca52Saliguori 
48097b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
48107b6f9300SMarkus Armbruster {
48117b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
48127b6f9300SMarkus Armbruster }
48137cd1e32aSlirans@il.ibm.com 
4814e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
4815e268ca52Saliguori {
4816*339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
4817e268ca52Saliguori }
48187cd1e32aSlirans@il.ibm.com 
4819c53b1c51SStefan Hajnoczi /*
4820c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
4821c53b1c51SStefan Hajnoczi  */
4822c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4823c53b1c51SStefan Hajnoczi {
4824c53b1c51SStefan Hajnoczi     int i;
4825*339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
4826c53b1c51SStefan Hajnoczi 
4827c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
4828*339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
4829c53b1c51SStefan Hajnoczi             return false;
4830c53b1c51SStefan Hajnoczi         }
4831*339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
48321ff735bdSKevin Wolf             return false;
48331ff735bdSKevin Wolf         }
4834c53b1c51SStefan Hajnoczi     }
4835c53b1c51SStefan Hajnoczi 
4836c53b1c51SStefan Hajnoczi     return true;
4837c53b1c51SStefan Hajnoczi }
4838c53b1c51SStefan Hajnoczi 
4839e4654d2dSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity)
48407cd1e32aSlirans@il.ibm.com {
48417cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
4842e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
4843a55eb92cSJan Kiszka 
484450717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
484550717e94SPaolo Bonzini 
484650717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
4847e4654d2dSFam Zheng     assert(granularity);
48488f0720ecSPaolo Bonzini     bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
4849e4654d2dSFam Zheng     bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
4850e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
4851e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
4852e4654d2dSFam Zheng     return bitmap;
4853e4654d2dSFam Zheng }
4854e4654d2dSFam Zheng 
4855e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
4856e4654d2dSFam Zheng {
4857e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
4858e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
4859e4654d2dSFam Zheng         if (bm == bitmap) {
4860e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
4861e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
4862e4654d2dSFam Zheng             g_free(bitmap);
4863e4654d2dSFam Zheng             return;
48647cd1e32aSlirans@il.ibm.com         }
48657cd1e32aSlirans@il.ibm.com     }
48667cd1e32aSlirans@il.ibm.com }
48677cd1e32aSlirans@il.ibm.com 
486821b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
486921b56835SFam Zheng {
487021b56835SFam Zheng     BdrvDirtyBitmap *bm;
487121b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
487221b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
487321b56835SFam Zheng 
487421b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
487521b56835SFam Zheng         BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
487621b56835SFam Zheng         BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
487721b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
487821b56835SFam Zheng         info->granularity =
487921b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
488021b56835SFam Zheng         entry->value = info;
488121b56835SFam Zheng         *plist = entry;
488221b56835SFam Zheng         plist = &entry->next;
488321b56835SFam Zheng     }
488421b56835SFam Zheng 
488521b56835SFam Zheng     return list;
488621b56835SFam Zheng }
488721b56835SFam Zheng 
4888e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
48897cd1e32aSlirans@il.ibm.com {
4890e4654d2dSFam Zheng     if (bitmap) {
4891e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
48927cd1e32aSlirans@il.ibm.com     } else {
48937cd1e32aSlirans@il.ibm.com         return 0;
48947cd1e32aSlirans@il.ibm.com     }
48957cd1e32aSlirans@il.ibm.com }
48967cd1e32aSlirans@il.ibm.com 
4897e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
4898e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
48991755da16SPaolo Bonzini {
4900e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
49011755da16SPaolo Bonzini }
49021755da16SPaolo Bonzini 
49031755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
49041755da16SPaolo Bonzini                     int nr_sectors)
49051755da16SPaolo Bonzini {
4906e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
4907e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
4908e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
4909e4654d2dSFam Zheng     }
49101755da16SPaolo Bonzini }
49111755da16SPaolo Bonzini 
4912e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
49137cd1e32aSlirans@il.ibm.com {
4914e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
4915e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
4916e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
4917e4654d2dSFam Zheng     }
49187cd1e32aSlirans@il.ibm.com }
4919aaa0eb75SLiran Schour 
4920e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
4921aaa0eb75SLiran Schour {
4922e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
4923aaa0eb75SLiran Schour }
4924f88e1a42SJes Sorensen 
49259fcb0251SFam Zheng /* Get a reference to bs */
49269fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
49279fcb0251SFam Zheng {
49289fcb0251SFam Zheng     bs->refcnt++;
49299fcb0251SFam Zheng }
49309fcb0251SFam Zheng 
49319fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
49329fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
49339fcb0251SFam Zheng  * deleted. */
49349fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
49359fcb0251SFam Zheng {
49369fcb0251SFam Zheng     assert(bs->refcnt > 0);
49379fcb0251SFam Zheng     if (--bs->refcnt == 0) {
49389fcb0251SFam Zheng         bdrv_delete(bs);
49399fcb0251SFam Zheng     }
49409fcb0251SFam Zheng }
49419fcb0251SFam Zheng 
4942db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4943db593f25SMarcelo Tosatti {
4944db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
4945db593f25SMarcelo Tosatti     bs->in_use = in_use;
4946db593f25SMarcelo Tosatti }
4947db593f25SMarcelo Tosatti 
4948db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
4949db593f25SMarcelo Tosatti {
4950db593f25SMarcelo Tosatti     return bs->in_use;
4951db593f25SMarcelo Tosatti }
4952db593f25SMarcelo Tosatti 
495328a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
495428a7282aSLuiz Capitulino {
4955d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
495658e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
495728a7282aSLuiz Capitulino }
495828a7282aSLuiz Capitulino 
495928a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
496028a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
496128a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
496228a7282aSLuiz Capitulino {
4963d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
496492aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
496592aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
496692aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
496728a7282aSLuiz Capitulino }
496828a7282aSLuiz Capitulino 
496928a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
497028a7282aSLuiz Capitulino {
4971d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
497228a7282aSLuiz Capitulino }
497328a7282aSLuiz Capitulino 
497428a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
497528a7282aSLuiz Capitulino {
497628a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
497758e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
49783bd293c3SPaolo Bonzini         if (bs->job) {
49793bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
49803bd293c3SPaolo Bonzini         }
498128a7282aSLuiz Capitulino     }
498228a7282aSLuiz Capitulino }
498328a7282aSLuiz Capitulino 
498428a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
498528a7282aSLuiz Capitulino {
49863e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
49873e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
498858e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
498958e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
499028a7282aSLuiz Capitulino     }
499128a7282aSLuiz Capitulino }
499228a7282aSLuiz Capitulino 
4993a597e79cSChristoph Hellwig void
4994a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4995a597e79cSChristoph Hellwig         enum BlockAcctType type)
4996a597e79cSChristoph Hellwig {
4997a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4998a597e79cSChristoph Hellwig 
4999a597e79cSChristoph Hellwig     cookie->bytes = bytes;
5000c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
5001a597e79cSChristoph Hellwig     cookie->type = type;
5002a597e79cSChristoph Hellwig }
5003a597e79cSChristoph Hellwig 
5004a597e79cSChristoph Hellwig void
5005a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
5006a597e79cSChristoph Hellwig {
5007a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
5008a597e79cSChristoph Hellwig 
5009a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
5010a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
5011c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
5012a597e79cSChristoph Hellwig }
5013a597e79cSChristoph Hellwig 
5014d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5015f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5016f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5017f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5018f88e1a42SJes Sorensen {
5019f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
5020d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
5021f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
502296df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5023cc84d90fSMax Reitz     Error *local_err = NULL;
5024f88e1a42SJes Sorensen     int ret = 0;
5025f88e1a42SJes Sorensen 
5026f88e1a42SJes Sorensen     /* Find driver and parse its options */
5027f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5028f88e1a42SJes Sorensen     if (!drv) {
502971c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5030d92ada22SLuiz Capitulino         return;
5031f88e1a42SJes Sorensen     }
5032f88e1a42SJes Sorensen 
503398289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5034f88e1a42SJes Sorensen     if (!proto_drv) {
503571c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5036d92ada22SLuiz Capitulino         return;
5037f88e1a42SJes Sorensen     }
5038f88e1a42SJes Sorensen 
5039f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5040f88e1a42SJes Sorensen                                               drv->create_options);
5041f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
5042f88e1a42SJes Sorensen                                               proto_drv->create_options);
5043f88e1a42SJes Sorensen 
5044f88e1a42SJes Sorensen     /* Create parameter list with default values */
5045f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
5046f88e1a42SJes Sorensen 
5047f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
5048f88e1a42SJes Sorensen 
5049f88e1a42SJes Sorensen     /* Parse -o options */
5050f88e1a42SJes Sorensen     if (options) {
5051f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
5052f88e1a42SJes Sorensen         if (param == NULL) {
505371c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
5054f88e1a42SJes Sorensen             goto out;
5055f88e1a42SJes Sorensen         }
5056f88e1a42SJes Sorensen     }
5057f88e1a42SJes Sorensen 
5058f88e1a42SJes Sorensen     if (base_filename) {
5059f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
5060f88e1a42SJes Sorensen                                  base_filename)) {
506171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
506271c79813SLuiz Capitulino                        fmt);
5063f88e1a42SJes Sorensen             goto out;
5064f88e1a42SJes Sorensen         }
5065f88e1a42SJes Sorensen     }
5066f88e1a42SJes Sorensen 
5067f88e1a42SJes Sorensen     if (base_fmt) {
5068f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
506971c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
507071c79813SLuiz Capitulino                              "format '%s'", fmt);
5071f88e1a42SJes Sorensen             goto out;
5072f88e1a42SJes Sorensen         }
5073f88e1a42SJes Sorensen     }
5074f88e1a42SJes Sorensen 
5075792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
5076792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
5077792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
507871c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
507971c79813SLuiz Capitulino                              "same filename as the backing file");
5080792da93aSJes Sorensen             goto out;
5081792da93aSJes Sorensen         }
5082792da93aSJes Sorensen     }
5083792da93aSJes Sorensen 
5084f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
5085f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
508696df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
508796df67d1SStefan Hajnoczi         if (!backing_drv) {
508871c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
508971c79813SLuiz Capitulino                        backing_fmt->value.s);
5090f88e1a42SJes Sorensen             goto out;
5091f88e1a42SJes Sorensen         }
5092f88e1a42SJes Sorensen     }
5093f88e1a42SJes Sorensen 
5094f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5095f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
5096d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
5097d220894eSKevin Wolf     if (size && size->value.n == -1) {
5098f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
509966f6b814SMax Reitz             BlockDriverState *bs;
5100f88e1a42SJes Sorensen             uint64_t size;
5101f88e1a42SJes Sorensen             char buf[32];
510263090dacSPaolo Bonzini             int back_flags;
510363090dacSPaolo Bonzini 
510463090dacSPaolo Bonzini             /* backing files always opened read-only */
510563090dacSPaolo Bonzini             back_flags =
510663090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5107f88e1a42SJes Sorensen 
5108f88e1a42SJes Sorensen             bs = bdrv_new("");
5109f88e1a42SJes Sorensen 
5110de9c0cecSKevin Wolf             ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
5111cc84d90fSMax Reitz                             backing_drv, &local_err);
5112f88e1a42SJes Sorensen             if (ret < 0) {
5113cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
5114cc84d90fSMax Reitz                                  backing_file->value.s,
5115cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5116cc84d90fSMax Reitz                 error_free(local_err);
5117cc84d90fSMax Reitz                 local_err = NULL;
511866f6b814SMax Reitz                 bdrv_unref(bs);
5119f88e1a42SJes Sorensen                 goto out;
5120f88e1a42SJes Sorensen             }
5121f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
5122f88e1a42SJes Sorensen             size *= 512;
5123f88e1a42SJes Sorensen 
5124f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
5125f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
512666f6b814SMax Reitz 
512766f6b814SMax Reitz             bdrv_unref(bs);
5128f88e1a42SJes Sorensen         } else {
512971c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5130f88e1a42SJes Sorensen             goto out;
5131f88e1a42SJes Sorensen         }
5132f88e1a42SJes Sorensen     }
5133f88e1a42SJes Sorensen 
5134f382d43aSMiroslav Rezanina     if (!quiet) {
5135f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
5136f88e1a42SJes Sorensen         print_option_parameters(param);
5137f88e1a42SJes Sorensen         puts("");
5138f382d43aSMiroslav Rezanina     }
5139cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, param, &local_err);
5140cc84d90fSMax Reitz     if (ret == -EFBIG) {
5141cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5142cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5143cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5144f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
5145f3f4d2c0SKevin Wolf         if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
5146f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5147f3f4d2c0SKevin Wolf         }
5148cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5149cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5150cc84d90fSMax Reitz         error_free(local_err);
5151cc84d90fSMax Reitz         local_err = NULL;
5152f88e1a42SJes Sorensen     }
5153f88e1a42SJes Sorensen 
5154f88e1a42SJes Sorensen out:
5155f88e1a42SJes Sorensen     free_option_parameters(create_options);
5156f88e1a42SJes Sorensen     free_option_parameters(param);
5157f88e1a42SJes Sorensen 
5158cc84d90fSMax Reitz     if (error_is_set(&local_err)) {
5159cc84d90fSMax Reitz         error_propagate(errp, local_err);
5160cc84d90fSMax Reitz     }
5161f88e1a42SJes Sorensen }
516285d126f3SStefan Hajnoczi 
516385d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
516485d126f3SStefan Hajnoczi {
516585d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
516685d126f3SStefan Hajnoczi     return qemu_get_aio_context();
516785d126f3SStefan Hajnoczi }
5168d616b224SStefan Hajnoczi 
5169d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5170d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5171d616b224SStefan Hajnoczi {
5172d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5173d616b224SStefan Hajnoczi }
51746f176b48SMax Reitz 
51756f176b48SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
51766f176b48SMax Reitz {
51776f176b48SMax Reitz     if (bs->drv->bdrv_amend_options == NULL) {
51786f176b48SMax Reitz         return -ENOTSUP;
51796f176b48SMax Reitz     }
51806f176b48SMax Reitz     return bs->drv->bdrv_amend_options(bs, options);
51816f176b48SMax Reitz }
5182f6186f49SBenoît Canet 
5183212a5a8fSBenoît Canet /* Used to recurse on single child block filters.
5184212a5a8fSBenoît Canet  * Single child block filter will store their child in bs->file.
5185212a5a8fSBenoît Canet  */
5186212a5a8fSBenoît Canet bool bdrv_generic_is_first_non_filter(BlockDriverState *bs,
5187212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5188f6186f49SBenoît Canet {
5189212a5a8fSBenoît Canet     if (!bs->drv) {
5190212a5a8fSBenoît Canet         return false;
5191f6186f49SBenoît Canet     }
5192f6186f49SBenoît Canet 
5193212a5a8fSBenoît Canet     if (!bs->drv->authorizations[BS_IS_A_FILTER]) {
5194212a5a8fSBenoît Canet         if (bs == candidate) {
5195212a5a8fSBenoît Canet             return true;
5196212a5a8fSBenoît Canet         } else {
5197212a5a8fSBenoît Canet             return false;
5198212a5a8fSBenoît Canet         }
5199f6186f49SBenoît Canet     }
5200f6186f49SBenoît Canet 
5201212a5a8fSBenoît Canet     if (!bs->drv->authorizations[BS_FILTER_PASS_DOWN]) {
5202212a5a8fSBenoît Canet         return false;
5203f6186f49SBenoît Canet     }
5204f6186f49SBenoît Canet 
5205212a5a8fSBenoît Canet     if (!bs->file) {
5206212a5a8fSBenoît Canet         return false;
5207212a5a8fSBenoît Canet     }
5208212a5a8fSBenoît Canet 
5209212a5a8fSBenoît Canet     return bdrv_recurse_is_first_non_filter(bs->file, candidate);
5210212a5a8fSBenoît Canet }
5211212a5a8fSBenoît Canet 
5212212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5213212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5214f6186f49SBenoît Canet {
5215212a5a8fSBenoît Canet     if (bs->drv && bs->drv->bdrv_recurse_is_first_non_filter) {
5216212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5217212a5a8fSBenoît Canet     }
5218212a5a8fSBenoît Canet 
5219212a5a8fSBenoît Canet     return bdrv_generic_is_first_non_filter(bs, candidate);
5220212a5a8fSBenoît Canet }
5221212a5a8fSBenoît Canet 
5222212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5223212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5224212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5225212a5a8fSBenoît Canet  */
5226212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5227212a5a8fSBenoît Canet {
5228212a5a8fSBenoît Canet     BlockDriverState *bs;
5229212a5a8fSBenoît Canet 
5230212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5231212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5232212a5a8fSBenoît Canet         bool perm;
5233212a5a8fSBenoît Canet 
5234212a5a8fSBenoît Canet         if (!bs->file) {
5235212a5a8fSBenoît Canet             continue;
5236212a5a8fSBenoît Canet         }
5237212a5a8fSBenoît Canet 
5238212a5a8fSBenoît Canet         perm = bdrv_recurse_is_first_non_filter(bs->file, candidate);
5239212a5a8fSBenoît Canet 
5240212a5a8fSBenoît Canet         /* candidate is the first non filter */
5241212a5a8fSBenoît Canet         if (perm) {
5242212a5a8fSBenoît Canet             return true;
5243212a5a8fSBenoît Canet         }
5244212a5a8fSBenoît Canet     }
5245212a5a8fSBenoît Canet 
5246212a5a8fSBenoît Canet     return false;
5247f6186f49SBenoît Canet }
5248