xref: /openbmc/qemu/block.c (revision 61ed2684539f7f31304e193d7c0e68d57ce6be88)
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"
35b2023818SLuiz Capitulino #include "qmp-commands.h"
361de7afc9SPaolo Bonzini #include "qemu/timer.h"
37fc01f7e7Sbellard 
3871e72a19SJuan Quintela #ifdef CONFIG_BSD
397674e7bfSbellard #include <sys/types.h>
407674e7bfSbellard #include <sys/stat.h>
417674e7bfSbellard #include <sys/ioctl.h>
4272cf2d4fSBlue Swirl #include <sys/queue.h>
43c5e97233Sblueswir1 #ifndef __DragonFly__
447674e7bfSbellard #include <sys/disk.h>
457674e7bfSbellard #endif
46c5e97233Sblueswir1 #endif
477674e7bfSbellard 
4849dc768dSaliguori #ifdef _WIN32
4949dc768dSaliguori #include <windows.h>
5049dc768dSaliguori #endif
5149dc768dSaliguori 
521c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
531c9805a3SStefan Hajnoczi 
54470c0504SStefan Hajnoczi typedef enum {
55470c0504SStefan Hajnoczi     BDRV_REQ_COPY_ON_READ = 0x1,
56f08f2ddaSStefan Hajnoczi     BDRV_REQ_ZERO_WRITE   = 0x2,
57470c0504SStefan Hajnoczi } BdrvRequestFlags;
58470c0504SStefan Hajnoczi 
597d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
60f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
62c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
63f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
65ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
66f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
68f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
69f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
71f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
72c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
73470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
751c9805a3SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
76f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
78b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79b2a61371SStefan Hajnoczi                                                int64_t sector_num,
80b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
81b2a61371SStefan Hajnoczi                                                int nb_sectors,
82b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
83b2a61371SStefan Hajnoczi                                                void *opaque,
848c5873d6SStefan Hajnoczi                                                bool is_write);
85b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
86621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87621f0589SKevin Wolf     int64_t sector_num, int nb_sectors);
88ec530c81Sbellard 
891b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
901b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
917ee930d0Sblueswir1 
928a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
938a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
94ea2384d3Sbellard 
95eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
96eb852011SMarkus Armbruster static int use_bdrv_whitelist;
97eb852011SMarkus Armbruster 
989e0b22f4SStefan Hajnoczi #ifdef _WIN32
999e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1009e0b22f4SStefan Hajnoczi {
1019e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1029e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1039e0b22f4SStefan Hajnoczi             filename[1] == ':');
1049e0b22f4SStefan Hajnoczi }
1059e0b22f4SStefan Hajnoczi 
1069e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1079e0b22f4SStefan Hajnoczi {
1089e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1099e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1109e0b22f4SStefan Hajnoczi         return 1;
1119e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1129e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1139e0b22f4SStefan Hajnoczi         return 1;
1149e0b22f4SStefan Hajnoczi     return 0;
1159e0b22f4SStefan Hajnoczi }
1169e0b22f4SStefan Hajnoczi #endif
1179e0b22f4SStefan Hajnoczi 
1180563e191SZhi Yong Wu /* throttling disk I/O limits */
119cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs,
120cc0681c4SBenoît Canet                         ThrottleConfig *cfg)
121cc0681c4SBenoît Canet {
122cc0681c4SBenoît Canet     int i;
123cc0681c4SBenoît Canet 
124cc0681c4SBenoît Canet     throttle_config(&bs->throttle_state, cfg);
125cc0681c4SBenoît Canet 
126cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
127cc0681c4SBenoît Canet         qemu_co_enter_next(&bs->throttled_reqs[i]);
128cc0681c4SBenoît Canet     }
129cc0681c4SBenoît Canet }
130cc0681c4SBenoît Canet 
131cc0681c4SBenoît Canet /* this function drain all the throttled IOs */
132cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
133cc0681c4SBenoît Canet {
134cc0681c4SBenoît Canet     bool drained = false;
135cc0681c4SBenoît Canet     bool enabled = bs->io_limits_enabled;
136cc0681c4SBenoît Canet     int i;
137cc0681c4SBenoît Canet 
138cc0681c4SBenoît Canet     bs->io_limits_enabled = false;
139cc0681c4SBenoît Canet 
140cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
141cc0681c4SBenoît Canet         while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
142cc0681c4SBenoît Canet             drained = true;
143cc0681c4SBenoît Canet         }
144cc0681c4SBenoît Canet     }
145cc0681c4SBenoît Canet 
146cc0681c4SBenoît Canet     bs->io_limits_enabled = enabled;
147cc0681c4SBenoît Canet 
148cc0681c4SBenoît Canet     return drained;
149cc0681c4SBenoît Canet }
150cc0681c4SBenoît Canet 
15198f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
15298f90dbaSZhi Yong Wu {
15398f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
15498f90dbaSZhi Yong Wu 
155cc0681c4SBenoît Canet     bdrv_start_throttled_reqs(bs);
15698f90dbaSZhi Yong Wu 
157cc0681c4SBenoît Canet     throttle_destroy(&bs->throttle_state);
15898f90dbaSZhi Yong Wu }
15998f90dbaSZhi Yong Wu 
160cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque)
1610563e191SZhi Yong Wu {
1620563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
163cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[0]);
1640563e191SZhi Yong Wu }
1650563e191SZhi Yong Wu 
166cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque)
167cc0681c4SBenoît Canet {
168cc0681c4SBenoît Canet     BlockDriverState *bs = opaque;
169cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[1]);
170cc0681c4SBenoît Canet }
171cc0681c4SBenoît Canet 
172cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */
1730563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1740563e191SZhi Yong Wu {
175cc0681c4SBenoît Canet     assert(!bs->io_limits_enabled);
176cc0681c4SBenoît Canet     throttle_init(&bs->throttle_state,
177cc0681c4SBenoît Canet                   QEMU_CLOCK_VIRTUAL,
178cc0681c4SBenoît Canet                   bdrv_throttle_read_timer_cb,
179cc0681c4SBenoît Canet                   bdrv_throttle_write_timer_cb,
180cc0681c4SBenoît Canet                   bs);
1810563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1820563e191SZhi Yong Wu }
1830563e191SZhi Yong Wu 
184cc0681c4SBenoît Canet /* This function makes an IO wait if needed
185cc0681c4SBenoît Canet  *
186cc0681c4SBenoît Canet  * @nb_sectors: the number of sectors of the IO
187cc0681c4SBenoît Canet  * @is_write:   is the IO a write
18898f90dbaSZhi Yong Wu  */
189cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs,
190cc0681c4SBenoît Canet                                      int nb_sectors,
191cc0681c4SBenoît Canet                                      bool is_write)
192cc0681c4SBenoît Canet {
193cc0681c4SBenoît Canet     /* does this io must wait */
194cc0681c4SBenoît Canet     bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
19598f90dbaSZhi Yong Wu 
196cc0681c4SBenoît Canet     /* if must wait or any request of this type throttled queue the IO */
197cc0681c4SBenoît Canet     if (must_wait ||
198cc0681c4SBenoît Canet         !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
199cc0681c4SBenoît Canet         qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
20098f90dbaSZhi Yong Wu     }
20198f90dbaSZhi Yong Wu 
202cc0681c4SBenoît Canet     /* the IO will be executed, do the accounting */
203cc0681c4SBenoît Canet     throttle_account(&bs->throttle_state,
204cc0681c4SBenoît Canet                      is_write,
205cc0681c4SBenoît Canet                      nb_sectors * BDRV_SECTOR_SIZE);
206cc0681c4SBenoît Canet 
207cc0681c4SBenoît Canet     /* if the next request must wait -> do nothing */
208cc0681c4SBenoît Canet     if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
209cc0681c4SBenoît Canet         return;
210cc0681c4SBenoît Canet     }
211cc0681c4SBenoît Canet 
212cc0681c4SBenoît Canet     /* else queue next request for execution */
213cc0681c4SBenoît Canet     qemu_co_queue_next(&bs->throttled_reqs[is_write]);
21498f90dbaSZhi Yong Wu }
21598f90dbaSZhi Yong Wu 
2169e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
2179e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2189e0b22f4SStefan Hajnoczi {
219947995c0SPaolo Bonzini     const char *p;
220947995c0SPaolo Bonzini 
2219e0b22f4SStefan Hajnoczi #ifdef _WIN32
2229e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2239e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2249e0b22f4SStefan Hajnoczi         return 0;
2259e0b22f4SStefan Hajnoczi     }
226947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
227947995c0SPaolo Bonzini #else
228947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2299e0b22f4SStefan Hajnoczi #endif
2309e0b22f4SStefan Hajnoczi 
231947995c0SPaolo Bonzini     return *p == ':';
2329e0b22f4SStefan Hajnoczi }
2339e0b22f4SStefan Hajnoczi 
23483f64091Sbellard int path_is_absolute(const char *path)
23583f64091Sbellard {
23621664424Sbellard #ifdef _WIN32
23721664424Sbellard     /* specific case for names like: "\\.\d:" */
238f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
23921664424Sbellard         return 1;
240f53f4da9SPaolo Bonzini     }
241f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2423b9f94e1Sbellard #else
243f53f4da9SPaolo Bonzini     return (*path == '/');
2443b9f94e1Sbellard #endif
24583f64091Sbellard }
24683f64091Sbellard 
24783f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
24883f64091Sbellard    path to it by considering it is relative to base_path. URL are
24983f64091Sbellard    supported. */
25083f64091Sbellard void path_combine(char *dest, int dest_size,
25183f64091Sbellard                   const char *base_path,
25283f64091Sbellard                   const char *filename)
25383f64091Sbellard {
25483f64091Sbellard     const char *p, *p1;
25583f64091Sbellard     int len;
25683f64091Sbellard 
25783f64091Sbellard     if (dest_size <= 0)
25883f64091Sbellard         return;
25983f64091Sbellard     if (path_is_absolute(filename)) {
26083f64091Sbellard         pstrcpy(dest, dest_size, filename);
26183f64091Sbellard     } else {
26283f64091Sbellard         p = strchr(base_path, ':');
26383f64091Sbellard         if (p)
26483f64091Sbellard             p++;
26583f64091Sbellard         else
26683f64091Sbellard             p = base_path;
2673b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2683b9f94e1Sbellard #ifdef _WIN32
2693b9f94e1Sbellard         {
2703b9f94e1Sbellard             const char *p2;
2713b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2723b9f94e1Sbellard             if (!p1 || p2 > p1)
2733b9f94e1Sbellard                 p1 = p2;
2743b9f94e1Sbellard         }
2753b9f94e1Sbellard #endif
27683f64091Sbellard         if (p1)
27783f64091Sbellard             p1++;
27883f64091Sbellard         else
27983f64091Sbellard             p1 = base_path;
28083f64091Sbellard         if (p1 > p)
28183f64091Sbellard             p = p1;
28283f64091Sbellard         len = p - base_path;
28383f64091Sbellard         if (len > dest_size - 1)
28483f64091Sbellard             len = dest_size - 1;
28583f64091Sbellard         memcpy(dest, base_path, len);
28683f64091Sbellard         dest[len] = '\0';
28783f64091Sbellard         pstrcat(dest, dest_size, filename);
28883f64091Sbellard     }
28983f64091Sbellard }
29083f64091Sbellard 
291dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
292dc5a1371SPaolo Bonzini {
293dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
294dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
295dc5a1371SPaolo Bonzini     } else {
296dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
297dc5a1371SPaolo Bonzini     }
298dc5a1371SPaolo Bonzini }
299dc5a1371SPaolo Bonzini 
3005efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
301ea2384d3Sbellard {
3028c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
3038c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
304f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
305f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
306f9f05dc5SKevin Wolf 
307f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
308f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
309f8c35c1dSStefan Hajnoczi          */
310f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
31183f64091Sbellard             /* add AIO emulation layer */
312f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
313f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
31483f64091Sbellard         }
315f9f05dc5SKevin Wolf     }
316b2e12bc6SChristoph Hellwig 
3178a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
318ea2384d3Sbellard }
319b338082bSbellard 
320b338082bSbellard /* create a new block device (by default it is empty) */
321b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
322fc01f7e7Sbellard {
3231b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
324b338082bSbellard 
3257267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
326b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
327ea2384d3Sbellard     if (device_name[0] != '\0') {
3281b7bdbc1SStefan Hajnoczi         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
329ea2384d3Sbellard     }
33028a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
331d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
332d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
333cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
334cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3359fcb0251SFam Zheng     bs->refcnt = 1;
336d7d512f6SPaolo Bonzini 
337b338082bSbellard     return bs;
338b338082bSbellard }
339b338082bSbellard 
340d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
341d7d512f6SPaolo Bonzini {
342d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
343d7d512f6SPaolo Bonzini }
344d7d512f6SPaolo Bonzini 
345ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
346ea2384d3Sbellard {
347ea2384d3Sbellard     BlockDriver *drv1;
3488a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3498a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
350ea2384d3Sbellard             return drv1;
351ea2384d3Sbellard         }
3528a22f02aSStefan Hajnoczi     }
353ea2384d3Sbellard     return NULL;
354ea2384d3Sbellard }
355ea2384d3Sbellard 
356b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
357eb852011SMarkus Armbruster {
358b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
359b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
360b64ec4e4SFam Zheng     };
361b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
362b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
363eb852011SMarkus Armbruster     };
364eb852011SMarkus Armbruster     const char **p;
365eb852011SMarkus Armbruster 
366b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
367eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
368b64ec4e4SFam Zheng     }
369eb852011SMarkus Armbruster 
370b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
371eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
372eb852011SMarkus Armbruster             return 1;
373eb852011SMarkus Armbruster         }
374eb852011SMarkus Armbruster     }
375b64ec4e4SFam Zheng     if (read_only) {
376b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
377b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
378b64ec4e4SFam Zheng                 return 1;
379b64ec4e4SFam Zheng             }
380b64ec4e4SFam Zheng         }
381b64ec4e4SFam Zheng     }
382eb852011SMarkus Armbruster     return 0;
383eb852011SMarkus Armbruster }
384eb852011SMarkus Armbruster 
385b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
386b64ec4e4SFam Zheng                                           bool read_only)
387eb852011SMarkus Armbruster {
388eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
389b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
390eb852011SMarkus Armbruster }
391eb852011SMarkus Armbruster 
3925b7e1542SZhi Yong Wu typedef struct CreateCo {
3935b7e1542SZhi Yong Wu     BlockDriver *drv;
3945b7e1542SZhi Yong Wu     char *filename;
3955b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
3965b7e1542SZhi Yong Wu     int ret;
397cc84d90fSMax Reitz     Error *err;
3985b7e1542SZhi Yong Wu } CreateCo;
3995b7e1542SZhi Yong Wu 
4005b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4015b7e1542SZhi Yong Wu {
402cc84d90fSMax Reitz     Error *local_err = NULL;
403cc84d90fSMax Reitz     int ret;
404cc84d90fSMax Reitz 
4055b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4065b7e1542SZhi Yong Wu     assert(cco->drv);
4075b7e1542SZhi Yong Wu 
408cc84d90fSMax Reitz     ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
409cc84d90fSMax Reitz     if (error_is_set(&local_err)) {
410cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
411cc84d90fSMax Reitz     }
412cc84d90fSMax Reitz     cco->ret = ret;
4135b7e1542SZhi Yong Wu }
4145b7e1542SZhi Yong Wu 
4150e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
416cc84d90fSMax Reitz     QEMUOptionParameter *options, Error **errp)
417ea2384d3Sbellard {
4185b7e1542SZhi Yong Wu     int ret;
4190e7e1989SKevin Wolf 
4205b7e1542SZhi Yong Wu     Coroutine *co;
4215b7e1542SZhi Yong Wu     CreateCo cco = {
4225b7e1542SZhi Yong Wu         .drv = drv,
4235b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
4245b7e1542SZhi Yong Wu         .options = options,
4255b7e1542SZhi Yong Wu         .ret = NOT_DONE,
426cc84d90fSMax Reitz         .err = NULL,
4275b7e1542SZhi Yong Wu     };
4285b7e1542SZhi Yong Wu 
4295b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
430cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
43180168bffSLuiz Capitulino         ret = -ENOTSUP;
43280168bffSLuiz Capitulino         goto out;
4335b7e1542SZhi Yong Wu     }
4345b7e1542SZhi Yong Wu 
4355b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4365b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4375b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4385b7e1542SZhi Yong Wu     } else {
4395b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4405b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4415b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4425b7e1542SZhi Yong Wu             qemu_aio_wait();
4435b7e1542SZhi Yong Wu         }
4445b7e1542SZhi Yong Wu     }
4455b7e1542SZhi Yong Wu 
4465b7e1542SZhi Yong Wu     ret = cco.ret;
447cc84d90fSMax Reitz     if (ret < 0) {
448cc84d90fSMax Reitz         if (error_is_set(&cco.err)) {
449cc84d90fSMax Reitz             error_propagate(errp, cco.err);
450cc84d90fSMax Reitz         } else {
451cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
452cc84d90fSMax Reitz         }
453cc84d90fSMax Reitz     }
4545b7e1542SZhi Yong Wu 
45580168bffSLuiz Capitulino out:
45680168bffSLuiz Capitulino     g_free(cco.filename);
4575b7e1542SZhi Yong Wu     return ret;
458ea2384d3Sbellard }
459ea2384d3Sbellard 
460cc84d90fSMax Reitz int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
461cc84d90fSMax Reitz                      Error **errp)
46284a12e66SChristoph Hellwig {
46384a12e66SChristoph Hellwig     BlockDriver *drv;
464cc84d90fSMax Reitz     Error *local_err = NULL;
465cc84d90fSMax Reitz     int ret;
46684a12e66SChristoph Hellwig 
46798289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
46884a12e66SChristoph Hellwig     if (drv == NULL) {
469cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
47016905d71SStefan Hajnoczi         return -ENOENT;
47184a12e66SChristoph Hellwig     }
47284a12e66SChristoph Hellwig 
473cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, options, &local_err);
474cc84d90fSMax Reitz     if (error_is_set(&local_err)) {
475cc84d90fSMax Reitz         error_propagate(errp, local_err);
476cc84d90fSMax Reitz     }
477cc84d90fSMax Reitz     return ret;
47884a12e66SChristoph Hellwig }
47984a12e66SChristoph Hellwig 
480eba25057SJim Meyering /*
481eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
482eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
483eba25057SJim Meyering  */
484eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
485eba25057SJim Meyering {
486d5249393Sbellard #ifdef _WIN32
4873b9f94e1Sbellard     char temp_dir[MAX_PATH];
488eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
489eba25057SJim Meyering        have length MAX_PATH or greater.  */
490eba25057SJim Meyering     assert(size >= MAX_PATH);
491eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
492eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
493eba25057SJim Meyering             ? 0 : -GetLastError());
494d5249393Sbellard #else
495ea2384d3Sbellard     int fd;
4967ccfb2ebSblueswir1     const char *tmpdir;
4970badc1eeSaurel32     tmpdir = getenv("TMPDIR");
4980badc1eeSaurel32     if (!tmpdir)
4990badc1eeSaurel32         tmpdir = "/tmp";
500eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
501eba25057SJim Meyering         return -EOVERFLOW;
502ea2384d3Sbellard     }
503eba25057SJim Meyering     fd = mkstemp(filename);
504fe235a06SDunrong Huang     if (fd < 0) {
505fe235a06SDunrong Huang         return -errno;
506fe235a06SDunrong Huang     }
507fe235a06SDunrong Huang     if (close(fd) != 0) {
508fe235a06SDunrong Huang         unlink(filename);
509eba25057SJim Meyering         return -errno;
510eba25057SJim Meyering     }
511eba25057SJim Meyering     return 0;
512d5249393Sbellard #endif
513eba25057SJim Meyering }
514ea2384d3Sbellard 
515f3a5d3f8SChristoph Hellwig /*
516f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
517f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
518f3a5d3f8SChristoph Hellwig  */
519f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
520f3a5d3f8SChristoph Hellwig {
521508c7cb3SChristoph Hellwig     int score_max = 0, score;
522508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
523f3a5d3f8SChristoph Hellwig 
5248a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
525508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
526508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
527508c7cb3SChristoph Hellwig             if (score > score_max) {
528508c7cb3SChristoph Hellwig                 score_max = score;
529508c7cb3SChristoph Hellwig                 drv = d;
530f3a5d3f8SChristoph Hellwig             }
531508c7cb3SChristoph Hellwig         }
532f3a5d3f8SChristoph Hellwig     }
533f3a5d3f8SChristoph Hellwig 
534508c7cb3SChristoph Hellwig     return drv;
535f3a5d3f8SChristoph Hellwig }
536f3a5d3f8SChristoph Hellwig 
53798289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
53898289620SKevin Wolf                                 bool allow_protocol_prefix)
53984a12e66SChristoph Hellwig {
54084a12e66SChristoph Hellwig     BlockDriver *drv1;
54184a12e66SChristoph Hellwig     char protocol[128];
54284a12e66SChristoph Hellwig     int len;
54384a12e66SChristoph Hellwig     const char *p;
54484a12e66SChristoph Hellwig 
54566f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
54666f82ceeSKevin Wolf 
54739508e7aSChristoph Hellwig     /*
54839508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
54939508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
55039508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
55139508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
55239508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
55339508e7aSChristoph Hellwig      */
55484a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
55539508e7aSChristoph Hellwig     if (drv1) {
55684a12e66SChristoph Hellwig         return drv1;
55784a12e66SChristoph Hellwig     }
55839508e7aSChristoph Hellwig 
55998289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
56039508e7aSChristoph Hellwig         return bdrv_find_format("file");
56139508e7aSChristoph Hellwig     }
56298289620SKevin Wolf 
5639e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5649e0b22f4SStefan Hajnoczi     assert(p != NULL);
56584a12e66SChristoph Hellwig     len = p - filename;
56684a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
56784a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
56884a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
56984a12e66SChristoph Hellwig     protocol[len] = '\0';
57084a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
57184a12e66SChristoph Hellwig         if (drv1->protocol_name &&
57284a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
57384a12e66SChristoph Hellwig             return drv1;
57484a12e66SChristoph Hellwig         }
57584a12e66SChristoph Hellwig     }
57684a12e66SChristoph Hellwig     return NULL;
57784a12e66SChristoph Hellwig }
57884a12e66SChristoph Hellwig 
579f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
58034b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
581ea2384d3Sbellard {
582f500a6d3SKevin Wolf     int score, score_max;
583ea2384d3Sbellard     BlockDriver *drv1, *drv;
58483f64091Sbellard     uint8_t buf[2048];
585f500a6d3SKevin Wolf     int ret = 0;
586f8ea0b00SNicholas Bellinger 
58708a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5888e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
589c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
590c98ac35dSStefan Weil         if (!drv) {
59134b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
592c98ac35dSStefan Weil             ret = -ENOENT;
593c98ac35dSStefan Weil         }
594c98ac35dSStefan Weil         *pdrv = drv;
595c98ac35dSStefan Weil         return ret;
5961a396859SNicholas A. Bellinger     }
597f8ea0b00SNicholas Bellinger 
59883f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
599ea2384d3Sbellard     if (ret < 0) {
60034b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
60134b5d2c6SMax Reitz                          "format");
602c98ac35dSStefan Weil         *pdrv = NULL;
603c98ac35dSStefan Weil         return ret;
604ea2384d3Sbellard     }
605ea2384d3Sbellard 
606ea2384d3Sbellard     score_max = 0;
60784a12e66SChristoph Hellwig     drv = NULL;
6088a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
60983f64091Sbellard         if (drv1->bdrv_probe) {
610ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
611ea2384d3Sbellard             if (score > score_max) {
612ea2384d3Sbellard                 score_max = score;
613ea2384d3Sbellard                 drv = drv1;
614ea2384d3Sbellard             }
615ea2384d3Sbellard         }
61683f64091Sbellard     }
617c98ac35dSStefan Weil     if (!drv) {
61834b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
61934b5d2c6SMax Reitz                    "driver found");
620c98ac35dSStefan Weil         ret = -ENOENT;
621c98ac35dSStefan Weil     }
622c98ac35dSStefan Weil     *pdrv = drv;
623c98ac35dSStefan Weil     return ret;
624ea2384d3Sbellard }
625ea2384d3Sbellard 
62651762288SStefan Hajnoczi /**
62751762288SStefan Hajnoczi  * Set the current 'total_sectors' value
62851762288SStefan Hajnoczi  */
62951762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
63051762288SStefan Hajnoczi {
63151762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
63251762288SStefan Hajnoczi 
633396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
634396759adSNicholas Bellinger     if (bs->sg)
635396759adSNicholas Bellinger         return 0;
636396759adSNicholas Bellinger 
63751762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
63851762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
63951762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
64051762288SStefan Hajnoczi         if (length < 0) {
64151762288SStefan Hajnoczi             return length;
64251762288SStefan Hajnoczi         }
64351762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
64451762288SStefan Hajnoczi     }
64551762288SStefan Hajnoczi 
64651762288SStefan Hajnoczi     bs->total_sectors = hint;
64751762288SStefan Hajnoczi     return 0;
64851762288SStefan Hajnoczi }
64951762288SStefan Hajnoczi 
650c3993cdcSStefan Hajnoczi /**
6519e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6529e8f1835SPaolo Bonzini  *
6539e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6549e8f1835SPaolo Bonzini  */
6559e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6569e8f1835SPaolo Bonzini {
6579e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6589e8f1835SPaolo Bonzini 
6599e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6609e8f1835SPaolo Bonzini         /* do nothing */
6619e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6629e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6639e8f1835SPaolo Bonzini     } else {
6649e8f1835SPaolo Bonzini         return -1;
6659e8f1835SPaolo Bonzini     }
6669e8f1835SPaolo Bonzini 
6679e8f1835SPaolo Bonzini     return 0;
6689e8f1835SPaolo Bonzini }
6699e8f1835SPaolo Bonzini 
6709e8f1835SPaolo Bonzini /**
671c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
672c3993cdcSStefan Hajnoczi  *
673c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
674c3993cdcSStefan Hajnoczi  */
675c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
676c3993cdcSStefan Hajnoczi {
677c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
678c3993cdcSStefan Hajnoczi 
679c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
680c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
68192196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
68292196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
683c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
684c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
685c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
686c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
687c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
688c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
689c3993cdcSStefan Hajnoczi         /* this is the default */
690c3993cdcSStefan Hajnoczi     } else {
691c3993cdcSStefan Hajnoczi         return -1;
692c3993cdcSStefan Hajnoczi     }
693c3993cdcSStefan Hajnoczi 
694c3993cdcSStefan Hajnoczi     return 0;
695c3993cdcSStefan Hajnoczi }
696c3993cdcSStefan Hajnoczi 
69753fec9d3SStefan Hajnoczi /**
69853fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
69953fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
70053fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
70153fec9d3SStefan Hajnoczi  */
70253fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
70353fec9d3SStefan Hajnoczi {
70453fec9d3SStefan Hajnoczi     bs->copy_on_read++;
70553fec9d3SStefan Hajnoczi }
70653fec9d3SStefan Hajnoczi 
70753fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
70853fec9d3SStefan Hajnoczi {
70953fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
71053fec9d3SStefan Hajnoczi     bs->copy_on_read--;
71153fec9d3SStefan Hajnoczi }
71253fec9d3SStefan Hajnoczi 
7137b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7147b272452SKevin Wolf {
7157b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7167b272452SKevin Wolf 
7177b272452SKevin Wolf     /*
7187b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7197b272452SKevin Wolf      * image.
7207b272452SKevin Wolf      */
7217b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7227b272452SKevin Wolf 
7237b272452SKevin Wolf     /*
7247b272452SKevin Wolf      * Snapshots should be writable.
7257b272452SKevin Wolf      */
7267b272452SKevin Wolf     if (bs->is_temporary) {
7277b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7287b272452SKevin Wolf     }
7297b272452SKevin Wolf 
7307b272452SKevin Wolf     return open_flags;
7317b272452SKevin Wolf }
7327b272452SKevin Wolf 
733b6ce07aaSKevin Wolf /*
73457915332SKevin Wolf  * Common part for opening disk images and files
735b6ad491aSKevin Wolf  *
736b6ad491aSKevin Wolf  * Removes all processed options from *options.
73757915332SKevin Wolf  */
738f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
73934b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
74057915332SKevin Wolf {
74157915332SKevin Wolf     int ret, open_flags;
742035fccdfSKevin Wolf     const char *filename;
74334b5d2c6SMax Reitz     Error *local_err = NULL;
74457915332SKevin Wolf 
74557915332SKevin Wolf     assert(drv != NULL);
7466405875cSPaolo Bonzini     assert(bs->file == NULL);
747707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
74857915332SKevin Wolf 
74945673671SKevin Wolf     if (file != NULL) {
75045673671SKevin Wolf         filename = file->filename;
75145673671SKevin Wolf     } else {
75245673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
75345673671SKevin Wolf     }
75445673671SKevin Wolf 
75545673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
75628dcee10SStefan Hajnoczi 
7575d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
7585d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
7595d186eb0SKevin Wolf      * and return immediately. */
7605d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
7615d186eb0SKevin Wolf         bdrv_swap(file, bs);
7625d186eb0SKevin Wolf         return 0;
7635d186eb0SKevin Wolf     }
7645d186eb0SKevin Wolf 
76557915332SKevin Wolf     bs->open_flags = flags;
76657915332SKevin Wolf     bs->buffer_alignment = 512;
7670d51b4deSAsias He     bs->zero_beyond_eof = true;
768b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
769b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
770b64ec4e4SFam Zheng 
771b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
7728f94a6e4SKevin Wolf         error_setg(errp,
7738f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
7748f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
7758f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
7768f94a6e4SKevin Wolf                    drv->format_name);
777b64ec4e4SFam Zheng         return -ENOTSUP;
778b64ec4e4SFam Zheng     }
77957915332SKevin Wolf 
78053fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
7810ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
7820ebd24e0SKevin Wolf         if (!bs->read_only) {
78353fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
7840ebd24e0SKevin Wolf         } else {
7850ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
7860ebd24e0SKevin Wolf             return -EINVAL;
7870ebd24e0SKevin Wolf         }
78853fec9d3SStefan Hajnoczi     }
78953fec9d3SStefan Hajnoczi 
790c2ad1b0cSKevin Wolf     if (filename != NULL) {
79157915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
792c2ad1b0cSKevin Wolf     } else {
793c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
794c2ad1b0cSKevin Wolf     }
79557915332SKevin Wolf 
79657915332SKevin Wolf     bs->drv = drv;
7977267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
79857915332SKevin Wolf 
79903f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
800e7c63796SStefan Hajnoczi 
80166f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
80266f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
8035d186eb0SKevin Wolf         assert(file == NULL);
804030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
80534b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
806f500a6d3SKevin Wolf     } else {
8072af5ef70SKevin Wolf         if (file == NULL) {
80834b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
80934b5d2c6SMax Reitz                        "protocol level", drv->format_name);
8102af5ef70SKevin Wolf             ret = -EINVAL;
8112af5ef70SKevin Wolf             goto free_and_fail;
8122af5ef70SKevin Wolf         }
813f500a6d3SKevin Wolf         bs->file = file;
81434b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
81566f82ceeSKevin Wolf     }
81666f82ceeSKevin Wolf 
81757915332SKevin Wolf     if (ret < 0) {
81834b5d2c6SMax Reitz         if (error_is_set(&local_err)) {
81934b5d2c6SMax Reitz             error_propagate(errp, local_err);
8202fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
8212fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
82234b5d2c6SMax Reitz         } else {
82334b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
82434b5d2c6SMax Reitz         }
82557915332SKevin Wolf         goto free_and_fail;
82657915332SKevin Wolf     }
82757915332SKevin Wolf 
82851762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
82951762288SStefan Hajnoczi     if (ret < 0) {
83034b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
83151762288SStefan Hajnoczi         goto free_and_fail;
83257915332SKevin Wolf     }
83351762288SStefan Hajnoczi 
83457915332SKevin Wolf #ifndef _WIN32
83557915332SKevin Wolf     if (bs->is_temporary) {
836d4cea8dfSDunrong Huang         assert(bs->filename[0] != '\0');
837d4cea8dfSDunrong Huang         unlink(bs->filename);
83857915332SKevin Wolf     }
83957915332SKevin Wolf #endif
84057915332SKevin Wolf     return 0;
84157915332SKevin Wolf 
84257915332SKevin Wolf free_and_fail:
84366f82ceeSKevin Wolf     bs->file = NULL;
8447267c094SAnthony Liguori     g_free(bs->opaque);
84557915332SKevin Wolf     bs->opaque = NULL;
84657915332SKevin Wolf     bs->drv = NULL;
84757915332SKevin Wolf     return ret;
84857915332SKevin Wolf }
84957915332SKevin Wolf 
85057915332SKevin Wolf /*
851b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
852787e4a85SKevin Wolf  *
853787e4a85SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
854787e4a85SKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
855787e4a85SKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
856787e4a85SKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
857b6ce07aaSKevin Wolf  */
858787e4a85SKevin Wolf int bdrv_file_open(BlockDriverState **pbs, const char *filename,
85934b5d2c6SMax Reitz                    QDict *options, int flags, Error **errp)
860b338082bSbellard {
86183f64091Sbellard     BlockDriverState *bs;
8626db95603SChristoph Hellwig     BlockDriver *drv;
863c2ad1b0cSKevin Wolf     const char *drvname;
86498289620SKevin Wolf     bool allow_protocol_prefix = false;
86534b5d2c6SMax Reitz     Error *local_err = NULL;
86683f64091Sbellard     int ret;
8673b0d4f61Sbellard 
868707ff828SKevin Wolf     /* NULL means an empty set of options */
869707ff828SKevin Wolf     if (options == NULL) {
870707ff828SKevin Wolf         options = qdict_new();
8713b0d4f61Sbellard     }
872707ff828SKevin Wolf 
873707ff828SKevin Wolf     bs = bdrv_new("");
874707ff828SKevin Wolf     bs->options = options;
875707ff828SKevin Wolf     options = qdict_clone_shallow(options);
876707ff828SKevin Wolf 
877035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
878035fccdfSKevin Wolf     if (!filename) {
879035fccdfSKevin Wolf         filename = qdict_get_try_str(options, "filename");
880035fccdfSKevin Wolf     } else if (filename && !qdict_haskey(options, "filename")) {
881035fccdfSKevin Wolf         qdict_put(options, "filename", qstring_from_str(filename));
88298289620SKevin Wolf         allow_protocol_prefix = true;
883035fccdfSKevin Wolf     } else {
88434b5d2c6SMax Reitz         error_setg(errp, "Can't specify 'file' and 'filename' options at the "
88534b5d2c6SMax Reitz                    "same time");
886035fccdfSKevin Wolf         ret = -EINVAL;
887035fccdfSKevin Wolf         goto fail;
888035fccdfSKevin Wolf     }
889035fccdfSKevin Wolf 
890c2ad1b0cSKevin Wolf     /* Find the right block driver */
891c2ad1b0cSKevin Wolf     drvname = qdict_get_try_str(options, "driver");
892c2ad1b0cSKevin Wolf     if (drvname) {
8938f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
89434b5d2c6SMax Reitz         if (!drv) {
89534b5d2c6SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
89634b5d2c6SMax Reitz         }
897c2ad1b0cSKevin Wolf         qdict_del(options, "driver");
898c2ad1b0cSKevin Wolf     } else if (filename) {
89998289620SKevin Wolf         drv = bdrv_find_protocol(filename, allow_protocol_prefix);
90098289620SKevin Wolf         if (!drv) {
90134b5d2c6SMax Reitz             error_setg(errp, "Unknown protocol");
90298289620SKevin Wolf         }
903c2ad1b0cSKevin Wolf     } else {
90434b5d2c6SMax Reitz         error_setg(errp, "Must specify either driver or file");
905c2ad1b0cSKevin Wolf         drv = NULL;
906c2ad1b0cSKevin Wolf     }
907c2ad1b0cSKevin Wolf 
908c2ad1b0cSKevin Wolf     if (!drv) {
90934b5d2c6SMax Reitz         /* errp has been set already */
910c2ad1b0cSKevin Wolf         ret = -ENOENT;
911c2ad1b0cSKevin Wolf         goto fail;
912c2ad1b0cSKevin Wolf     }
913c2ad1b0cSKevin Wolf 
914c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
915c2ad1b0cSKevin Wolf     if (drv->bdrv_parse_filename && filename) {
9166963a30dSKevin Wolf         drv->bdrv_parse_filename(filename, options, &local_err);
9176963a30dSKevin Wolf         if (error_is_set(&local_err)) {
91834b5d2c6SMax Reitz             error_propagate(errp, local_err);
9196963a30dSKevin Wolf             ret = -EINVAL;
9206963a30dSKevin Wolf             goto fail;
9216963a30dSKevin Wolf         }
92256d1b4d2SKevin Wolf         qdict_del(options, "filename");
923030be321SBenoît Canet     } else if (drv->bdrv_needs_filename && !filename) {
92434b5d2c6SMax Reitz         error_setg(errp, "The '%s' block driver requires a file name",
925c2ad1b0cSKevin Wolf                    drv->format_name);
926c2ad1b0cSKevin Wolf         ret = -EINVAL;
927c2ad1b0cSKevin Wolf         goto fail;
9286963a30dSKevin Wolf     }
9296963a30dSKevin Wolf 
93034b5d2c6SMax Reitz     ret = bdrv_open_common(bs, NULL, options, flags, drv, &local_err);
931707ff828SKevin Wolf     if (ret < 0) {
93234b5d2c6SMax Reitz         error_propagate(errp, local_err);
933707ff828SKevin Wolf         goto fail;
934707ff828SKevin Wolf     }
935707ff828SKevin Wolf 
936707ff828SKevin Wolf     /* Check if any unknown options were used */
937707ff828SKevin Wolf     if (qdict_size(options) != 0) {
938707ff828SKevin Wolf         const QDictEntry *entry = qdict_first(options);
93934b5d2c6SMax Reitz         error_setg(errp, "Block protocol '%s' doesn't support the option '%s'",
940707ff828SKevin Wolf                    drv->format_name, entry->key);
941707ff828SKevin Wolf         ret = -EINVAL;
942707ff828SKevin Wolf         goto fail;
943707ff828SKevin Wolf     }
944707ff828SKevin Wolf     QDECREF(options);
945707ff828SKevin Wolf 
94671d0770cSaliguori     bs->growable = 1;
94783f64091Sbellard     *pbs = bs;
94883f64091Sbellard     return 0;
949707ff828SKevin Wolf 
950707ff828SKevin Wolf fail:
951707ff828SKevin Wolf     QDECREF(options);
952707ff828SKevin Wolf     if (!bs->drv) {
953707ff828SKevin Wolf         QDECREF(bs->options);
954707ff828SKevin Wolf     }
9554f6fd349SFam Zheng     bdrv_unref(bs);
956707ff828SKevin Wolf     return ret;
9573b0d4f61Sbellard }
9583b0d4f61Sbellard 
95931ca6d07SKevin Wolf /*
96031ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
96131ca6d07SKevin Wolf  *
96231ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
96331ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
96431ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
96531ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
96631ca6d07SKevin Wolf  */
96734b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
9689156df12SPaolo Bonzini {
9699156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
9709156df12SPaolo Bonzini     int back_flags, ret;
9719156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
97234b5d2c6SMax Reitz     Error *local_err = NULL;
9739156df12SPaolo Bonzini 
9749156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
97531ca6d07SKevin Wolf         QDECREF(options);
9769156df12SPaolo Bonzini         return 0;
9779156df12SPaolo Bonzini     }
9789156df12SPaolo Bonzini 
97931ca6d07SKevin Wolf     /* NULL means an empty set of options */
98031ca6d07SKevin Wolf     if (options == NULL) {
98131ca6d07SKevin Wolf         options = qdict_new();
98231ca6d07SKevin Wolf     }
98331ca6d07SKevin Wolf 
9849156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
9851cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
9861cb6f506SKevin Wolf         backing_filename[0] = '\0';
9871cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
98831ca6d07SKevin Wolf         QDECREF(options);
9899156df12SPaolo Bonzini         return 0;
990dbecebddSFam Zheng     } else {
991dbecebddSFam Zheng         bdrv_get_full_backing_filename(bs, backing_filename,
992dbecebddSFam Zheng                                        sizeof(backing_filename));
9939156df12SPaolo Bonzini     }
9949156df12SPaolo Bonzini 
9959156df12SPaolo Bonzini     bs->backing_hd = bdrv_new("");
9969156df12SPaolo Bonzini 
9979156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
9989156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
9999156df12SPaolo Bonzini     }
10009156df12SPaolo Bonzini 
10019156df12SPaolo Bonzini     /* backing files always opened read-only */
10029156df12SPaolo Bonzini     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
10039156df12SPaolo Bonzini 
100431ca6d07SKevin Wolf     ret = bdrv_open(bs->backing_hd,
100531ca6d07SKevin Wolf                     *backing_filename ? backing_filename : NULL, options,
100634b5d2c6SMax Reitz                     back_flags, back_drv, &local_err);
10079156df12SPaolo Bonzini     if (ret < 0) {
10084f6fd349SFam Zheng         bdrv_unref(bs->backing_hd);
10099156df12SPaolo Bonzini         bs->backing_hd = NULL;
10109156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
101134b5d2c6SMax Reitz         error_propagate(errp, local_err);
10129156df12SPaolo Bonzini         return ret;
10139156df12SPaolo Bonzini     }
1014*61ed2684SMax Reitz     pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1015*61ed2684SMax Reitz             bs->backing_hd->file->filename);
10169156df12SPaolo Bonzini     return 0;
10179156df12SPaolo Bonzini }
10189156df12SPaolo Bonzini 
1019b6ce07aaSKevin Wolf /*
1020b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1021de9c0cecSKevin Wolf  *
1022de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1023de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1024de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1025de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1026b6ce07aaSKevin Wolf  */
1027de9c0cecSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
102834b5d2c6SMax Reitz               int flags, BlockDriver *drv, Error **errp)
1029ea2384d3Sbellard {
1030b6ce07aaSKevin Wolf     int ret;
103189c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
103289c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
1033f500a6d3SKevin Wolf     BlockDriverState *file = NULL;
1034707ff828SKevin Wolf     QDict *file_options = NULL;
103574fe54f2SKevin Wolf     const char *drvname;
103634b5d2c6SMax Reitz     Error *local_err = NULL;
103733e3963eSbellard 
1038de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1039de9c0cecSKevin Wolf     if (options == NULL) {
1040de9c0cecSKevin Wolf         options = qdict_new();
1041de9c0cecSKevin Wolf     }
1042de9c0cecSKevin Wolf 
1043de9c0cecSKevin Wolf     bs->options = options;
1044b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1045de9c0cecSKevin Wolf 
1046de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
104783f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
1048ea2384d3Sbellard         BlockDriverState *bs1;
1049ea2384d3Sbellard         int64_t total_size;
105091a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
105108b392e1SKevin Wolf         QEMUOptionParameter *create_options;
1052b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
105333e3963eSbellard 
1054c2ad1b0cSKevin Wolf         if (qdict_size(options) != 0) {
105534b5d2c6SMax Reitz             error_setg(errp, "Can't use snapshot=on with driver-specific options");
1056c2ad1b0cSKevin Wolf             ret = -EINVAL;
1057c2ad1b0cSKevin Wolf             goto fail;
1058c2ad1b0cSKevin Wolf         }
1059c2ad1b0cSKevin Wolf         assert(filename != NULL);
1060c2ad1b0cSKevin Wolf 
1061ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
1062ea2384d3Sbellard            instead of opening 'filename' directly */
1063ea2384d3Sbellard 
1064ea2384d3Sbellard         /* if there is a backing file, use it */
1065ea2384d3Sbellard         bs1 = bdrv_new("");
106634b5d2c6SMax Reitz         ret = bdrv_open(bs1, filename, NULL, 0, drv, &local_err);
106751d7c00cSaliguori         if (ret < 0) {
10684f6fd349SFam Zheng             bdrv_unref(bs1);
1069de9c0cecSKevin Wolf             goto fail;
1070ea2384d3Sbellard         }
10713e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
10727c96d46eSaliguori 
10734f6fd349SFam Zheng         bdrv_unref(bs1);
1074ea2384d3Sbellard 
1075eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1076eba25057SJim Meyering         if (ret < 0) {
107734b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not get temporary filename");
1078de9c0cecSKevin Wolf             goto fail;
1079eba25057SJim Meyering         }
10807c96d46eSaliguori 
10817c96d46eSaliguori         /* Real path is meaningless for protocols */
10824d70655bSStefan Hajnoczi         if (path_has_protocol(filename)) {
10837c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
10847c96d46eSaliguori                      "%s", filename);
1085de9c0cecSKevin Wolf         } else if (!realpath(filename, backing_filename)) {
108634b5d2c6SMax Reitz             error_setg_errno(errp, errno, "Could not resolve path '%s'", filename);
1087de9c0cecSKevin Wolf             ret = -errno;
1088de9c0cecSKevin Wolf             goto fail;
1089de9c0cecSKevin Wolf         }
10907c96d46eSaliguori 
109191a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
109208b392e1SKevin Wolf         create_options = parse_option_parameters("", bdrv_qcow2->create_options,
109308b392e1SKevin Wolf                                                  NULL);
109491a073a9SKevin Wolf 
109508b392e1SKevin Wolf         set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
109608b392e1SKevin Wolf         set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,
109708b392e1SKevin Wolf                              backing_filename);
109891a073a9SKevin Wolf         if (drv) {
109908b392e1SKevin Wolf             set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
110091a073a9SKevin Wolf                 drv->format_name);
110191a073a9SKevin Wolf         }
110291a073a9SKevin Wolf 
1103cc84d90fSMax Reitz         ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
110408b392e1SKevin Wolf         free_option_parameters(create_options);
110551d7c00cSaliguori         if (ret < 0) {
110634b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not create temporary overlay "
1107cc84d90fSMax Reitz                              "'%s': %s", tmp_filename,
1108cc84d90fSMax Reitz                              error_get_pretty(local_err));
1109cc84d90fSMax Reitz             error_free(local_err);
1110cc84d90fSMax Reitz             local_err = NULL;
1111de9c0cecSKevin Wolf             goto fail;
1112ea2384d3Sbellard         }
111391a073a9SKevin Wolf 
1114ea2384d3Sbellard         filename = tmp_filename;
111591a073a9SKevin Wolf         drv = bdrv_qcow2;
1116ea2384d3Sbellard         bs->is_temporary = 1;
1117ea2384d3Sbellard     }
1118ea2384d3Sbellard 
1119f500a6d3SKevin Wolf     /* Open image file without format layer */
1120be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1121be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1122be028adcSJeff Cody     }
1123be028adcSJeff Cody 
11245726d872SBenoît Canet     qdict_extract_subqdict(options, &file_options, "file.");
1125707ff828SKevin Wolf 
1126707ff828SKevin Wolf     ret = bdrv_file_open(&file, filename, file_options,
112734b5d2c6SMax Reitz                          bdrv_open_flags(bs, flags | BDRV_O_UNMAP), &local_err);
1128f500a6d3SKevin Wolf     if (ret < 0) {
1129de9c0cecSKevin Wolf         goto fail;
1130f500a6d3SKevin Wolf     }
1131f500a6d3SKevin Wolf 
1132f500a6d3SKevin Wolf     /* Find the right image format driver */
113374fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
113474fe54f2SKevin Wolf     if (drvname) {
11358f94a6e4SKevin Wolf         drv = bdrv_find_format(drvname);
113674fe54f2SKevin Wolf         qdict_del(options, "driver");
113774fe54f2SKevin Wolf     }
113874fe54f2SKevin Wolf 
1139f500a6d3SKevin Wolf     if (!drv) {
114034b5d2c6SMax Reitz         ret = find_image_format(file, filename, &drv, &local_err);
1141f500a6d3SKevin Wolf     }
1142f500a6d3SKevin Wolf 
1143f500a6d3SKevin Wolf     if (!drv) {
1144f500a6d3SKevin Wolf         goto unlink_and_fail;
1145f500a6d3SKevin Wolf     }
1146f500a6d3SKevin Wolf 
1147b6ce07aaSKevin Wolf     /* Open the image */
114834b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1149b6ce07aaSKevin Wolf     if (ret < 0) {
11506987307cSChristoph Hellwig         goto unlink_and_fail;
11516987307cSChristoph Hellwig     }
11526987307cSChristoph Hellwig 
1153f500a6d3SKevin Wolf     if (bs->file != file) {
11544f6fd349SFam Zheng         bdrv_unref(file);
1155f500a6d3SKevin Wolf         file = NULL;
1156f500a6d3SKevin Wolf     }
1157f500a6d3SKevin Wolf 
1158b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
11599156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
116031ca6d07SKevin Wolf         QDict *backing_options;
116131ca6d07SKevin Wolf 
11625726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
116334b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1164b6ce07aaSKevin Wolf         if (ret < 0) {
1165b6ad491aSKevin Wolf             goto close_and_fail;
1166b6ce07aaSKevin Wolf         }
1167b6ce07aaSKevin Wolf     }
1168b6ce07aaSKevin Wolf 
1169b6ad491aSKevin Wolf     /* Check if any unknown options were used */
1170b6ad491aSKevin Wolf     if (qdict_size(options) != 0) {
1171b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
117234b5d2c6SMax Reitz         error_setg(errp, "Block format '%s' used by device '%s' doesn't "
117334b5d2c6SMax Reitz                    "support the option '%s'", drv->format_name, bs->device_name,
117434b5d2c6SMax Reitz                    entry->key);
1175b6ad491aSKevin Wolf 
1176b6ad491aSKevin Wolf         ret = -EINVAL;
1177b6ad491aSKevin Wolf         goto close_and_fail;
1178b6ad491aSKevin Wolf     }
1179b6ad491aSKevin Wolf     QDECREF(options);
1180b6ad491aSKevin Wolf 
1181b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
11827d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1183b6ce07aaSKevin Wolf     }
1184b6ce07aaSKevin Wolf 
1185b6ce07aaSKevin Wolf     return 0;
1186b6ce07aaSKevin Wolf 
1187b6ce07aaSKevin Wolf unlink_and_fail:
1188f500a6d3SKevin Wolf     if (file != NULL) {
11894f6fd349SFam Zheng         bdrv_unref(file);
1190f500a6d3SKevin Wolf     }
1191b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1192b6ce07aaSKevin Wolf         unlink(filename);
1193b6ce07aaSKevin Wolf     }
1194de9c0cecSKevin Wolf fail:
1195de9c0cecSKevin Wolf     QDECREF(bs->options);
1196b6ad491aSKevin Wolf     QDECREF(options);
1197de9c0cecSKevin Wolf     bs->options = NULL;
119834b5d2c6SMax Reitz     if (error_is_set(&local_err)) {
119934b5d2c6SMax Reitz         error_propagate(errp, local_err);
120034b5d2c6SMax Reitz     }
1201b6ad491aSKevin Wolf     return ret;
1202de9c0cecSKevin Wolf 
1203b6ad491aSKevin Wolf close_and_fail:
1204b6ad491aSKevin Wolf     bdrv_close(bs);
1205b6ad491aSKevin Wolf     QDECREF(options);
120634b5d2c6SMax Reitz     if (error_is_set(&local_err)) {
120734b5d2c6SMax Reitz         error_propagate(errp, local_err);
120834b5d2c6SMax Reitz     }
1209b6ce07aaSKevin Wolf     return ret;
1210b6ce07aaSKevin Wolf }
1211b6ce07aaSKevin Wolf 
1212e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1213e971aa12SJeff Cody      bool prepared;
1214e971aa12SJeff Cody      BDRVReopenState state;
1215e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1216e971aa12SJeff Cody } BlockReopenQueueEntry;
1217e971aa12SJeff Cody 
1218e971aa12SJeff Cody /*
1219e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1220e971aa12SJeff Cody  * reopen of multiple devices.
1221e971aa12SJeff Cody  *
1222e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1223e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1224e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1225e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1226e971aa12SJeff Cody  * atomic 'set'.
1227e971aa12SJeff Cody  *
1228e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1229e971aa12SJeff Cody  *
1230e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1231e971aa12SJeff Cody  *
1232e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1233e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1234e971aa12SJeff Cody  *
1235e971aa12SJeff Cody  */
1236e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1237e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1238e971aa12SJeff Cody {
1239e971aa12SJeff Cody     assert(bs != NULL);
1240e971aa12SJeff Cody 
1241e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1242e971aa12SJeff Cody     if (bs_queue == NULL) {
1243e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1244e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1245e971aa12SJeff Cody     }
1246e971aa12SJeff Cody 
1247e971aa12SJeff Cody     if (bs->file) {
1248e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1249e971aa12SJeff Cody     }
1250e971aa12SJeff Cody 
1251e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1252e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1253e971aa12SJeff Cody 
1254e971aa12SJeff Cody     bs_entry->state.bs = bs;
1255e971aa12SJeff Cody     bs_entry->state.flags = flags;
1256e971aa12SJeff Cody 
1257e971aa12SJeff Cody     return bs_queue;
1258e971aa12SJeff Cody }
1259e971aa12SJeff Cody 
1260e971aa12SJeff Cody /*
1261e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1262e971aa12SJeff Cody  *
1263e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1264e971aa12SJeff Cody  * via bdrv_reopen_queue().
1265e971aa12SJeff Cody  *
1266e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1267e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1268e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1269e971aa12SJeff Cody  * data cleaned up.
1270e971aa12SJeff Cody  *
1271e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1272e971aa12SJeff Cody  * to all devices.
1273e971aa12SJeff Cody  *
1274e971aa12SJeff Cody  */
1275e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1276e971aa12SJeff Cody {
1277e971aa12SJeff Cody     int ret = -1;
1278e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1279e971aa12SJeff Cody     Error *local_err = NULL;
1280e971aa12SJeff Cody 
1281e971aa12SJeff Cody     assert(bs_queue != NULL);
1282e971aa12SJeff Cody 
1283e971aa12SJeff Cody     bdrv_drain_all();
1284e971aa12SJeff Cody 
1285e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1286e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1287e971aa12SJeff Cody             error_propagate(errp, local_err);
1288e971aa12SJeff Cody             goto cleanup;
1289e971aa12SJeff Cody         }
1290e971aa12SJeff Cody         bs_entry->prepared = true;
1291e971aa12SJeff Cody     }
1292e971aa12SJeff Cody 
1293e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1294e971aa12SJeff Cody      * changes
1295e971aa12SJeff Cody      */
1296e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1297e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1298e971aa12SJeff Cody     }
1299e971aa12SJeff Cody 
1300e971aa12SJeff Cody     ret = 0;
1301e971aa12SJeff Cody 
1302e971aa12SJeff Cody cleanup:
1303e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1304e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1305e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1306e971aa12SJeff Cody         }
1307e971aa12SJeff Cody         g_free(bs_entry);
1308e971aa12SJeff Cody     }
1309e971aa12SJeff Cody     g_free(bs_queue);
1310e971aa12SJeff Cody     return ret;
1311e971aa12SJeff Cody }
1312e971aa12SJeff Cody 
1313e971aa12SJeff Cody 
1314e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1315e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1316e971aa12SJeff Cody {
1317e971aa12SJeff Cody     int ret = -1;
1318e971aa12SJeff Cody     Error *local_err = NULL;
1319e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1320e971aa12SJeff Cody 
1321e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1322e971aa12SJeff Cody     if (local_err != NULL) {
1323e971aa12SJeff Cody         error_propagate(errp, local_err);
1324e971aa12SJeff Cody     }
1325e971aa12SJeff Cody     return ret;
1326e971aa12SJeff Cody }
1327e971aa12SJeff Cody 
1328e971aa12SJeff Cody 
1329e971aa12SJeff Cody /*
1330e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1331e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1332e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1333e971aa12SJeff Cody  *
1334e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1335e971aa12SJeff Cody  * flags are the new open flags
1336e971aa12SJeff Cody  * queue is the reopen queue
1337e971aa12SJeff Cody  *
1338e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1339e971aa12SJeff Cody  * as well.
1340e971aa12SJeff Cody  *
1341e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1342e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1343e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1344e971aa12SJeff Cody  *
1345e971aa12SJeff Cody  */
1346e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1347e971aa12SJeff Cody                         Error **errp)
1348e971aa12SJeff Cody {
1349e971aa12SJeff Cody     int ret = -1;
1350e971aa12SJeff Cody     Error *local_err = NULL;
1351e971aa12SJeff Cody     BlockDriver *drv;
1352e971aa12SJeff Cody 
1353e971aa12SJeff Cody     assert(reopen_state != NULL);
1354e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1355e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1356e971aa12SJeff Cody 
1357e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1358e971aa12SJeff Cody      * to r/w */
1359e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1360e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1361e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1362e971aa12SJeff Cody                   reopen_state->bs->device_name);
1363e971aa12SJeff Cody         goto error;
1364e971aa12SJeff Cody     }
1365e971aa12SJeff Cody 
1366e971aa12SJeff Cody 
1367e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1368e971aa12SJeff Cody     if (ret) {
1369e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1370e971aa12SJeff Cody                   strerror(-ret));
1371e971aa12SJeff Cody         goto error;
1372e971aa12SJeff Cody     }
1373e971aa12SJeff Cody 
1374e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1375e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1376e971aa12SJeff Cody         if (ret) {
1377e971aa12SJeff Cody             if (local_err != NULL) {
1378e971aa12SJeff Cody                 error_propagate(errp, local_err);
1379e971aa12SJeff Cody             } else {
1380d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1381e971aa12SJeff Cody                            reopen_state->bs->filename);
1382e971aa12SJeff Cody             }
1383e971aa12SJeff Cody             goto error;
1384e971aa12SJeff Cody         }
1385e971aa12SJeff Cody     } else {
1386e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1387e971aa12SJeff Cody          * handler for each supported drv. */
1388e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1389e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1390e971aa12SJeff Cody                  "reopening of file");
1391e971aa12SJeff Cody         ret = -1;
1392e971aa12SJeff Cody         goto error;
1393e971aa12SJeff Cody     }
1394e971aa12SJeff Cody 
1395e971aa12SJeff Cody     ret = 0;
1396e971aa12SJeff Cody 
1397e971aa12SJeff Cody error:
1398e971aa12SJeff Cody     return ret;
1399e971aa12SJeff Cody }
1400e971aa12SJeff Cody 
1401e971aa12SJeff Cody /*
1402e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1403e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1404e971aa12SJeff Cody  * the active BlockDriverState contents.
1405e971aa12SJeff Cody  */
1406e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1407e971aa12SJeff Cody {
1408e971aa12SJeff Cody     BlockDriver *drv;
1409e971aa12SJeff Cody 
1410e971aa12SJeff Cody     assert(reopen_state != NULL);
1411e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1412e971aa12SJeff Cody     assert(drv != NULL);
1413e971aa12SJeff Cody 
1414e971aa12SJeff Cody     /* If there are any driver level actions to take */
1415e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1416e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1417e971aa12SJeff Cody     }
1418e971aa12SJeff Cody 
1419e971aa12SJeff Cody     /* set BDS specific flags now */
1420e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1421e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1422e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1423e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1424e971aa12SJeff Cody }
1425e971aa12SJeff Cody 
1426e971aa12SJeff Cody /*
1427e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1428e971aa12SJeff Cody  * reopen_state
1429e971aa12SJeff Cody  */
1430e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1431e971aa12SJeff Cody {
1432e971aa12SJeff Cody     BlockDriver *drv;
1433e971aa12SJeff Cody 
1434e971aa12SJeff Cody     assert(reopen_state != NULL);
1435e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1436e971aa12SJeff Cody     assert(drv != NULL);
1437e971aa12SJeff Cody 
1438e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1439e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1440e971aa12SJeff Cody     }
1441e971aa12SJeff Cody }
1442e971aa12SJeff Cody 
1443e971aa12SJeff Cody 
1444fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1445fc01f7e7Sbellard {
14463e914655SPaolo Bonzini     if (bs->job) {
14473e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
14483e914655SPaolo Bonzini     }
144958fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
145058fda173SStefan Hajnoczi     bdrv_flush(bs);
145158fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1452d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
14537094f12fSKevin Wolf 
14543cbc002cSPaolo Bonzini     if (bs->drv) {
1455557df6acSStefan Hajnoczi         if (bs->backing_hd) {
14564f6fd349SFam Zheng             bdrv_unref(bs->backing_hd);
1457557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1458557df6acSStefan Hajnoczi         }
1459ea2384d3Sbellard         bs->drv->bdrv_close(bs);
14607267c094SAnthony Liguori         g_free(bs->opaque);
1461ea2384d3Sbellard #ifdef _WIN32
1462ea2384d3Sbellard         if (bs->is_temporary) {
1463ea2384d3Sbellard             unlink(bs->filename);
1464ea2384d3Sbellard         }
146567b915a5Sbellard #endif
1466ea2384d3Sbellard         bs->opaque = NULL;
1467ea2384d3Sbellard         bs->drv = NULL;
146853fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1469a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1470a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
14716405875cSPaolo Bonzini         bs->total_sectors = 0;
14726405875cSPaolo Bonzini         bs->encrypted = 0;
14736405875cSPaolo Bonzini         bs->valid_key = 0;
14746405875cSPaolo Bonzini         bs->sg = 0;
14756405875cSPaolo Bonzini         bs->growable = 0;
14760d51b4deSAsias He         bs->zero_beyond_eof = false;
1477de9c0cecSKevin Wolf         QDECREF(bs->options);
1478de9c0cecSKevin Wolf         bs->options = NULL;
1479b338082bSbellard 
148066f82ceeSKevin Wolf         if (bs->file != NULL) {
14814f6fd349SFam Zheng             bdrv_unref(bs->file);
14820ac9377dSPaolo Bonzini             bs->file = NULL;
148366f82ceeSKevin Wolf         }
14849ca11154SPavel Hrdina     }
148566f82ceeSKevin Wolf 
14867d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
148798f90dbaSZhi Yong Wu 
148898f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
148998f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
149098f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
149198f90dbaSZhi Yong Wu     }
1492b338082bSbellard }
1493b338082bSbellard 
14942bc93fedSMORITA Kazutaka void bdrv_close_all(void)
14952bc93fedSMORITA Kazutaka {
14962bc93fedSMORITA Kazutaka     BlockDriverState *bs;
14972bc93fedSMORITA Kazutaka 
14982bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
14992bc93fedSMORITA Kazutaka         bdrv_close(bs);
15002bc93fedSMORITA Kazutaka     }
15012bc93fedSMORITA Kazutaka }
15022bc93fedSMORITA Kazutaka 
150388266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
150488266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
150588266f5aSStefan Hajnoczi {
150688266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
150788266f5aSStefan Hajnoczi         return true;
150888266f5aSStefan Hajnoczi     }
1509cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1510cc0681c4SBenoît Canet         return true;
1511cc0681c4SBenoît Canet     }
1512cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
151388266f5aSStefan Hajnoczi         return true;
151488266f5aSStefan Hajnoczi     }
151588266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
151688266f5aSStefan Hajnoczi         return true;
151788266f5aSStefan Hajnoczi     }
151888266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
151988266f5aSStefan Hajnoczi         return true;
152088266f5aSStefan Hajnoczi     }
152188266f5aSStefan Hajnoczi     return false;
152288266f5aSStefan Hajnoczi }
152388266f5aSStefan Hajnoczi 
152488266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
152588266f5aSStefan Hajnoczi {
152688266f5aSStefan Hajnoczi     BlockDriverState *bs;
152788266f5aSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
152888266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
152988266f5aSStefan Hajnoczi             return true;
153088266f5aSStefan Hajnoczi         }
153188266f5aSStefan Hajnoczi     }
153288266f5aSStefan Hajnoczi     return false;
153388266f5aSStefan Hajnoczi }
153488266f5aSStefan Hajnoczi 
1535922453bcSStefan Hajnoczi /*
1536922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1537922453bcSStefan Hajnoczi  *
1538922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1539922453bcSStefan Hajnoczi  * after calling this function.
15404c355d53SZhi Yong Wu  *
15414c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
15424c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
15434c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
15444c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
15454c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1546922453bcSStefan Hajnoczi  */
1547922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1548922453bcSStefan Hajnoczi {
154988266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
155088266f5aSStefan Hajnoczi     bool busy = true;
1551922453bcSStefan Hajnoczi     BlockDriverState *bs;
1552922453bcSStefan Hajnoczi 
155388266f5aSStefan Hajnoczi     while (busy) {
15544c355d53SZhi Yong Wu         /* FIXME: We do not have timer support here, so this is effectively
15554c355d53SZhi Yong Wu          * a busy wait.
15564c355d53SZhi Yong Wu          */
15574c355d53SZhi Yong Wu         QTAILQ_FOREACH(bs, &bdrv_states, list) {
1558cc0681c4SBenoît Canet             if (bdrv_start_throttled_reqs(bs)) {
15594c355d53SZhi Yong Wu                 busy = true;
15604c355d53SZhi Yong Wu             }
15614c355d53SZhi Yong Wu         }
1562922453bcSStefan Hajnoczi 
156388266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
156488266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1565922453bcSStefan Hajnoczi     }
1566922453bcSStefan Hajnoczi }
1567922453bcSStefan Hajnoczi 
1568d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
1569d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1570d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1571d22b2f41SRyan Harper {
1572d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1573d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
1574d22b2f41SRyan Harper     }
1575d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1576d22b2f41SRyan Harper }
1577d22b2f41SRyan Harper 
1578e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1579e023b2e2SPaolo Bonzini {
1580e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1581e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1582e023b2e2SPaolo Bonzini     }
1583e023b2e2SPaolo Bonzini }
1584e023b2e2SPaolo Bonzini 
15854ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
15864ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
15874ddc07caSPaolo Bonzini {
15884ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
15894ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
15904ddc07caSPaolo Bonzini 
15914ddc07caSPaolo Bonzini     /* dev info */
15924ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
15934ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
15944ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
15954ddc07caSPaolo Bonzini     bs_dest->buffer_alignment   = bs_src->buffer_alignment;
15964ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
15974ddc07caSPaolo Bonzini 
15984ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
15994ddc07caSPaolo Bonzini 
1600cc0681c4SBenoît Canet     /* i/o throttled req */
1601cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1602cc0681c4SBenoît Canet            &bs_src->throttle_state,
1603cc0681c4SBenoît Canet            sizeof(ThrottleState));
1604cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1605cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
16064ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
16074ddc07caSPaolo Bonzini 
16084ddc07caSPaolo Bonzini     /* r/w error */
16094ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
16104ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
16114ddc07caSPaolo Bonzini 
16124ddc07caSPaolo Bonzini     /* i/o status */
16134ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
16144ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
16154ddc07caSPaolo Bonzini 
16164ddc07caSPaolo Bonzini     /* dirty bitmap */
16174ddc07caSPaolo Bonzini     bs_dest->dirty_bitmap       = bs_src->dirty_bitmap;
16184ddc07caSPaolo Bonzini 
16199fcb0251SFam Zheng     /* reference count */
16209fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
16219fcb0251SFam Zheng 
16224ddc07caSPaolo Bonzini     /* job */
16234ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
16244ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
16254ddc07caSPaolo Bonzini 
16264ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
16274ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
16284ddc07caSPaolo Bonzini             bs_src->device_name);
16294ddc07caSPaolo Bonzini     bs_dest->list = bs_src->list;
16304ddc07caSPaolo Bonzini }
16314ddc07caSPaolo Bonzini 
16324ddc07caSPaolo Bonzini /*
16334ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
16344ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
16354ddc07caSPaolo Bonzini  * actually attached to a device.
16364ddc07caSPaolo Bonzini  *
16374ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
16384ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
16394ddc07caSPaolo Bonzini  *
16404ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
16414ddc07caSPaolo Bonzini  *
16424ddc07caSPaolo Bonzini  * This function does not create any image files.
16434ddc07caSPaolo Bonzini  */
16444ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
16454ddc07caSPaolo Bonzini {
16464ddc07caSPaolo Bonzini     BlockDriverState tmp;
16474ddc07caSPaolo Bonzini 
16484ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
16494ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
16504ddc07caSPaolo Bonzini     assert(bs_new->dirty_bitmap == NULL);
16514ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
16524ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
16534ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
16544ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1655cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
16564ddc07caSPaolo Bonzini 
16574ddc07caSPaolo Bonzini     tmp = *bs_new;
16584ddc07caSPaolo Bonzini     *bs_new = *bs_old;
16594ddc07caSPaolo Bonzini     *bs_old = tmp;
16604ddc07caSPaolo Bonzini 
16614ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
16624ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
16634ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
16644ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
16654ddc07caSPaolo Bonzini 
16664ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
16674ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
16684ddc07caSPaolo Bonzini 
16694ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
16704ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
16714ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
16724ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
16734ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1674cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
16754ddc07caSPaolo Bonzini 
16764ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
16774ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
16784ddc07caSPaolo Bonzini }
16794ddc07caSPaolo Bonzini 
16808802d1fdSJeff Cody /*
16818802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
16828802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
16838802d1fdSJeff Cody  *
16848802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
16858802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
16868802d1fdSJeff Cody  *
1687f6801b83SJeff Cody  * bs_new is required to be anonymous.
1688f6801b83SJeff Cody  *
16898802d1fdSJeff Cody  * This function does not create any image files.
16908802d1fdSJeff Cody  */
16918802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
16928802d1fdSJeff Cody {
16934ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
16948802d1fdSJeff Cody 
16958802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
16968802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
16974ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
16984ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
16994ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
17004ddc07caSPaolo Bonzini             bs_new->filename);
17014ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
17024ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
17038802d1fdSJeff Cody }
17048802d1fdSJeff Cody 
17054f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
1706b338082bSbellard {
1707fa879d62SMarkus Armbruster     assert(!bs->dev);
17083e914655SPaolo Bonzini     assert(!bs->job);
17093e914655SPaolo Bonzini     assert(!bs->in_use);
17104f6fd349SFam Zheng     assert(!bs->refcnt);
171118846deeSMarkus Armbruster 
1712e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1713e1b5c52eSStefan Hajnoczi 
17141b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1715d22b2f41SRyan Harper     bdrv_make_anon(bs);
171634c6f050Saurel32 
17177267c094SAnthony Liguori     g_free(bs);
1718fc01f7e7Sbellard }
1719fc01f7e7Sbellard 
1720fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1721fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
172218846deeSMarkus Armbruster {
1723fa879d62SMarkus Armbruster     if (bs->dev) {
172418846deeSMarkus Armbruster         return -EBUSY;
172518846deeSMarkus Armbruster     }
1726fa879d62SMarkus Armbruster     bs->dev = dev;
172728a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
172818846deeSMarkus Armbruster     return 0;
172918846deeSMarkus Armbruster }
173018846deeSMarkus Armbruster 
1731fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1732fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
173318846deeSMarkus Armbruster {
1734fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1735fa879d62SMarkus Armbruster         abort();
1736fa879d62SMarkus Armbruster     }
1737fa879d62SMarkus Armbruster }
1738fa879d62SMarkus Armbruster 
1739fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1740fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1741fa879d62SMarkus Armbruster {
1742fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1743fa879d62SMarkus Armbruster     bs->dev = NULL;
17440e49de52SMarkus Armbruster     bs->dev_ops = NULL;
17450e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
174629e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
174718846deeSMarkus Armbruster }
174818846deeSMarkus Armbruster 
1749fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1750fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
175118846deeSMarkus Armbruster {
1752fa879d62SMarkus Armbruster     return bs->dev;
175318846deeSMarkus Armbruster }
175418846deeSMarkus Armbruster 
17550e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
17560e49de52SMarkus Armbruster                       void *opaque)
17570e49de52SMarkus Armbruster {
17580e49de52SMarkus Armbruster     bs->dev_ops = ops;
17590e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
17600e49de52SMarkus Armbruster }
17610e49de52SMarkus Armbruster 
176232c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
176332c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
17641ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1765329c0a48SLuiz Capitulino {
1766329c0a48SLuiz Capitulino     QObject *data;
1767329c0a48SLuiz Capitulino     const char *action_str;
1768329c0a48SLuiz Capitulino 
1769329c0a48SLuiz Capitulino     switch (action) {
1770329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1771329c0a48SLuiz Capitulino         action_str = "report";
1772329c0a48SLuiz Capitulino         break;
1773329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1774329c0a48SLuiz Capitulino         action_str = "ignore";
1775329c0a48SLuiz Capitulino         break;
1776329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1777329c0a48SLuiz Capitulino         action_str = "stop";
1778329c0a48SLuiz Capitulino         break;
1779329c0a48SLuiz Capitulino     default:
1780329c0a48SLuiz Capitulino         abort();
1781329c0a48SLuiz Capitulino     }
1782329c0a48SLuiz Capitulino 
1783329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1784329c0a48SLuiz Capitulino                               bdrv->device_name,
1785329c0a48SLuiz Capitulino                               action_str,
1786329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
178732c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
1788329c0a48SLuiz Capitulino 
1789329c0a48SLuiz Capitulino     qobject_decref(data);
1790329c0a48SLuiz Capitulino }
1791329c0a48SLuiz Capitulino 
17926f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
17936f382ed2SLuiz Capitulino {
17946f382ed2SLuiz Capitulino     QObject *data;
17956f382ed2SLuiz Capitulino 
17966f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
17976f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
17986f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
17996f382ed2SLuiz Capitulino 
18006f382ed2SLuiz Capitulino     qobject_decref(data);
18016f382ed2SLuiz Capitulino }
18026f382ed2SLuiz Capitulino 
18037d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
18040e49de52SMarkus Armbruster {
1805145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
18066f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
18077d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
18086f382ed2SLuiz Capitulino         if (tray_was_closed) {
18096f382ed2SLuiz Capitulino             /* tray open */
18106f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
18116f382ed2SLuiz Capitulino         }
18126f382ed2SLuiz Capitulino         if (load) {
18136f382ed2SLuiz Capitulino             /* tray close */
18146f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
18156f382ed2SLuiz Capitulino         }
1816145feb17SMarkus Armbruster     }
1817145feb17SMarkus Armbruster }
1818145feb17SMarkus Armbruster 
18192c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
18202c6942faSMarkus Armbruster {
18212c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
18222c6942faSMarkus Armbruster }
18232c6942faSMarkus Armbruster 
1824025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1825025ccaa7SPaolo Bonzini {
1826025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1827025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1828025ccaa7SPaolo Bonzini     }
1829025ccaa7SPaolo Bonzini }
1830025ccaa7SPaolo Bonzini 
1831e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1832e4def80bSMarkus Armbruster {
1833e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1834e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1835e4def80bSMarkus Armbruster     }
1836e4def80bSMarkus Armbruster     return false;
1837e4def80bSMarkus Armbruster }
1838e4def80bSMarkus Armbruster 
1839145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1840145feb17SMarkus Armbruster {
1841145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1842145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
18430e49de52SMarkus Armbruster     }
18440e49de52SMarkus Armbruster }
18450e49de52SMarkus Armbruster 
1846f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1847f107639aSMarkus Armbruster {
1848f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1849f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1850f107639aSMarkus Armbruster     }
1851f107639aSMarkus Armbruster     return false;
1852f107639aSMarkus Armbruster }
1853f107639aSMarkus Armbruster 
1854e97fc193Saliguori /*
1855e97fc193Saliguori  * Run consistency checks on an image
1856e97fc193Saliguori  *
1857e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1858a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1859e076f338SKevin Wolf  * check are stored in res.
1860e97fc193Saliguori  */
18614534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1862e97fc193Saliguori {
1863e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1864e97fc193Saliguori         return -ENOTSUP;
1865e97fc193Saliguori     }
1866e97fc193Saliguori 
1867e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
18684534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
1869e97fc193Saliguori }
1870e97fc193Saliguori 
18718a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
18728a426614SKevin Wolf 
187333e3963eSbellard /* commit COW file into the raw image */
187433e3963eSbellard int bdrv_commit(BlockDriverState *bs)
187533e3963eSbellard {
187619cb3738Sbellard     BlockDriver *drv = bs->drv;
18778a426614SKevin Wolf     int64_t sector, total_sectors;
18788a426614SKevin Wolf     int n, ro, open_flags;
18790bce597dSJeff Cody     int ret = 0;
18808a426614SKevin Wolf     uint8_t *buf;
1881c2cba3d9SJim Meyering     char filename[PATH_MAX];
188233e3963eSbellard 
188319cb3738Sbellard     if (!drv)
188419cb3738Sbellard         return -ENOMEDIUM;
188533e3963eSbellard 
18864dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
18874dca4b63SNaphtali Sprei         return -ENOTSUP;
18884dca4b63SNaphtali Sprei     }
18894dca4b63SNaphtali Sprei 
18902d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
18912d3735d3SStefan Hajnoczi         return -EBUSY;
18922d3735d3SStefan Hajnoczi     }
18932d3735d3SStefan Hajnoczi 
18944dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
1895c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1896c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
18974dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
18984dca4b63SNaphtali Sprei 
18994dca4b63SNaphtali Sprei     if (ro) {
19000bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
19010bce597dSJeff Cody             return -EACCES;
19024dca4b63SNaphtali Sprei         }
1903ea2384d3Sbellard     }
1904ea2384d3Sbellard 
19056ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
19067267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
19078a426614SKevin Wolf 
19088a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
1909d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
1910d663640cSPaolo Bonzini         if (ret < 0) {
1911d663640cSPaolo Bonzini             goto ro_cleanup;
1912d663640cSPaolo Bonzini         }
1913d663640cSPaolo Bonzini         if (ret) {
19148a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
19154dca4b63SNaphtali Sprei                 ret = -EIO;
19164dca4b63SNaphtali Sprei                 goto ro_cleanup;
191733e3963eSbellard             }
191833e3963eSbellard 
19198a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
19204dca4b63SNaphtali Sprei                 ret = -EIO;
19214dca4b63SNaphtali Sprei                 goto ro_cleanup;
192233e3963eSbellard             }
192333e3963eSbellard         }
192433e3963eSbellard     }
192595389c86Sbellard 
19261d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
19271d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
19281d44952fSChristoph Hellwig         bdrv_flush(bs);
19291d44952fSChristoph Hellwig     }
193095389c86Sbellard 
19313f5075aeSChristoph Hellwig     /*
19323f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
19333f5075aeSChristoph Hellwig      * stable on disk.
19343f5075aeSChristoph Hellwig      */
19353f5075aeSChristoph Hellwig     if (bs->backing_hd)
19363f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
19374dca4b63SNaphtali Sprei 
19384dca4b63SNaphtali Sprei ro_cleanup:
19397267c094SAnthony Liguori     g_free(buf);
19404dca4b63SNaphtali Sprei 
19414dca4b63SNaphtali Sprei     if (ro) {
19420bce597dSJeff Cody         /* ignoring error return here */
19430bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
19444dca4b63SNaphtali Sprei     }
19454dca4b63SNaphtali Sprei 
19461d44952fSChristoph Hellwig     return ret;
194733e3963eSbellard }
194833e3963eSbellard 
1949e8877497SStefan Hajnoczi int bdrv_commit_all(void)
19506ab4b5abSMarkus Armbruster {
19516ab4b5abSMarkus Armbruster     BlockDriverState *bs;
19526ab4b5abSMarkus Armbruster 
19536ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1954272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
1955e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
1956e8877497SStefan Hajnoczi             if (ret < 0) {
1957e8877497SStefan Hajnoczi                 return ret;
19586ab4b5abSMarkus Armbruster             }
19596ab4b5abSMarkus Armbruster         }
1960272d2d8eSJeff Cody     }
1961e8877497SStefan Hajnoczi     return 0;
1962e8877497SStefan Hajnoczi }
19636ab4b5abSMarkus Armbruster 
1964dbffbdcfSStefan Hajnoczi /**
1965dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1966dbffbdcfSStefan Hajnoczi  *
1967dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1968dbffbdcfSStefan Hajnoczi  */
1969dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1970dbffbdcfSStefan Hajnoczi {
1971dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1972f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1973dbffbdcfSStefan Hajnoczi }
1974dbffbdcfSStefan Hajnoczi 
1975dbffbdcfSStefan Hajnoczi /**
1976dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1977dbffbdcfSStefan Hajnoczi  */
1978dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1979dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1980dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1981dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1982dbffbdcfSStefan Hajnoczi {
1983dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1984dbffbdcfSStefan Hajnoczi         .bs = bs,
1985dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1986dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1987dbffbdcfSStefan Hajnoczi         .is_write = is_write,
19885f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1989dbffbdcfSStefan Hajnoczi     };
1990dbffbdcfSStefan Hajnoczi 
1991f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1992f4658285SStefan Hajnoczi 
1993dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1994dbffbdcfSStefan Hajnoczi }
1995dbffbdcfSStefan Hajnoczi 
1996d83947acSStefan Hajnoczi /**
1997d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1998d83947acSStefan Hajnoczi  */
1999343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2000d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2001d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2002d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2003d83947acSStefan Hajnoczi {
2004d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2005d83947acSStefan Hajnoczi 
2006d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2007d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2008d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2009d83947acSStefan Hajnoczi     } else {
2010d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2011d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2012d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2013d83947acSStefan Hajnoczi                                             nb_sectors, c);
2014d83947acSStefan Hajnoczi     }
2015d83947acSStefan Hajnoczi }
2016d83947acSStefan Hajnoczi 
2017f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2018f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
2019d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
2020d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
2021d83947acSStefan Hajnoczi         return false;
2022d83947acSStefan Hajnoczi     }
2023d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
2024d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
2025d83947acSStefan Hajnoczi         return false;
2026d83947acSStefan Hajnoczi     }
2027d83947acSStefan Hajnoczi     return true;
2028f4658285SStefan Hajnoczi }
2029f4658285SStefan Hajnoczi 
2030f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
2031f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
2032f4658285SStefan Hajnoczi {
2033f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2034d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
2035d83947acSStefan Hajnoczi     int cluster_nb_sectors;
2036f4658285SStefan Hajnoczi     bool retry;
2037f4658285SStefan Hajnoczi 
2038d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
2039d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
2040d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
2041d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
2042d83947acSStefan Hajnoczi      * interleave between them.
2043d83947acSStefan Hajnoczi      */
2044343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2045d83947acSStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2046d83947acSStefan Hajnoczi 
2047f4658285SStefan Hajnoczi     do {
2048f4658285SStefan Hajnoczi         retry = false;
2049f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
2050d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
2051d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
20525f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
20535f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
20545f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
20555f8b6491SStefan Hajnoczi                  */
20565f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
20575f8b6491SStefan Hajnoczi 
2058f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
2059f4658285SStefan Hajnoczi                 retry = true;
2060f4658285SStefan Hajnoczi                 break;
2061f4658285SStefan Hajnoczi             }
2062f4658285SStefan Hajnoczi         }
2063f4658285SStefan Hajnoczi     } while (retry);
2064f4658285SStefan Hajnoczi }
2065f4658285SStefan Hajnoczi 
2066756e6736SKevin Wolf /*
2067756e6736SKevin Wolf  * Return values:
2068756e6736SKevin Wolf  * 0        - success
2069756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2070756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2071756e6736SKevin Wolf  *            image file header
2072756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2073756e6736SKevin Wolf  */
2074756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2075756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2076756e6736SKevin Wolf {
2077756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2078469ef350SPaolo Bonzini     int ret;
2079756e6736SKevin Wolf 
20805f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
20815f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
20825f377794SPaolo Bonzini         return -EINVAL;
20835f377794SPaolo Bonzini     }
20845f377794SPaolo Bonzini 
2085756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2086469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2087756e6736SKevin Wolf     } else {
2088469ef350SPaolo Bonzini         ret = -ENOTSUP;
2089756e6736SKevin Wolf     }
2090469ef350SPaolo Bonzini 
2091469ef350SPaolo Bonzini     if (ret == 0) {
2092469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2093469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2094469ef350SPaolo Bonzini     }
2095469ef350SPaolo Bonzini     return ret;
2096756e6736SKevin Wolf }
2097756e6736SKevin Wolf 
20986ebdcee2SJeff Cody /*
20996ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
21006ebdcee2SJeff Cody  *
21016ebdcee2SJeff Cody  * active is the current topmost image.
21026ebdcee2SJeff Cody  *
21036ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
21046ebdcee2SJeff Cody  * or if active == bs.
21056ebdcee2SJeff Cody  */
21066ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
21076ebdcee2SJeff Cody                                     BlockDriverState *bs)
21086ebdcee2SJeff Cody {
21096ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
21106ebdcee2SJeff Cody     BlockDriverState *intermediate;
21116ebdcee2SJeff Cody 
21126ebdcee2SJeff Cody     assert(active != NULL);
21136ebdcee2SJeff Cody     assert(bs != NULL);
21146ebdcee2SJeff Cody 
21156ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
21166ebdcee2SJeff Cody      */
21176ebdcee2SJeff Cody     if (active == bs) {
21186ebdcee2SJeff Cody         return NULL;
21196ebdcee2SJeff Cody     }
21206ebdcee2SJeff Cody 
21216ebdcee2SJeff Cody     intermediate = active;
21226ebdcee2SJeff Cody     while (intermediate->backing_hd) {
21236ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
21246ebdcee2SJeff Cody             overlay = intermediate;
21256ebdcee2SJeff Cody             break;
21266ebdcee2SJeff Cody         }
21276ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
21286ebdcee2SJeff Cody     }
21296ebdcee2SJeff Cody 
21306ebdcee2SJeff Cody     return overlay;
21316ebdcee2SJeff Cody }
21326ebdcee2SJeff Cody 
21336ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
21346ebdcee2SJeff Cody     BlockDriverState *bs;
21356ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
21366ebdcee2SJeff Cody } BlkIntermediateStates;
21376ebdcee2SJeff Cody 
21386ebdcee2SJeff Cody 
21396ebdcee2SJeff Cody /*
21406ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
21416ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
21426ebdcee2SJeff Cody  *
21436ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
21446ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
21456ebdcee2SJeff Cody  *
21466ebdcee2SJeff Cody  * E.g., this will convert the following chain:
21476ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
21486ebdcee2SJeff Cody  *
21496ebdcee2SJeff Cody  * to
21506ebdcee2SJeff Cody  *
21516ebdcee2SJeff Cody  * bottom <- base <- active
21526ebdcee2SJeff Cody  *
21536ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
21546ebdcee2SJeff Cody  *
21556ebdcee2SJeff Cody  * base <- intermediate <- top <- active
21566ebdcee2SJeff Cody  *
21576ebdcee2SJeff Cody  * to
21586ebdcee2SJeff Cody  *
21596ebdcee2SJeff Cody  * base <- active
21606ebdcee2SJeff Cody  *
21616ebdcee2SJeff Cody  * Error conditions:
21626ebdcee2SJeff Cody  *  if active == top, that is considered an error
21636ebdcee2SJeff Cody  *
21646ebdcee2SJeff Cody  */
21656ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
21666ebdcee2SJeff Cody                            BlockDriverState *base)
21676ebdcee2SJeff Cody {
21686ebdcee2SJeff Cody     BlockDriverState *intermediate;
21696ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
21706ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
21716ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
21726ebdcee2SJeff Cody     int ret = -EIO;
21736ebdcee2SJeff Cody 
21746ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
21756ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
21766ebdcee2SJeff Cody 
21776ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
21786ebdcee2SJeff Cody         goto exit;
21796ebdcee2SJeff Cody     }
21806ebdcee2SJeff Cody 
21816ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
21826ebdcee2SJeff Cody 
21836ebdcee2SJeff Cody     if (new_top_bs == NULL) {
21846ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
21856ebdcee2SJeff Cody         goto exit;
21866ebdcee2SJeff Cody     }
21876ebdcee2SJeff Cody 
21886ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
21896ebdcee2SJeff Cody      * to do, no intermediate images */
21906ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
21916ebdcee2SJeff Cody         ret = 0;
21926ebdcee2SJeff Cody         goto exit;
21936ebdcee2SJeff Cody     }
21946ebdcee2SJeff Cody 
21956ebdcee2SJeff Cody     intermediate = top;
21966ebdcee2SJeff Cody 
21976ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
21986ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
21996ebdcee2SJeff Cody      */
22006ebdcee2SJeff Cody     while (intermediate) {
22016ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
22026ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
22036ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
22046ebdcee2SJeff Cody 
22056ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
22066ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
22076ebdcee2SJeff Cody             break;
22086ebdcee2SJeff Cody         }
22096ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
22106ebdcee2SJeff Cody     }
22116ebdcee2SJeff Cody     if (base_bs == NULL) {
22126ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
22136ebdcee2SJeff Cody          * unravel everything, and exit with error */
22146ebdcee2SJeff Cody         goto exit;
22156ebdcee2SJeff Cody     }
22166ebdcee2SJeff Cody 
22176ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
22186ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
22196ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
22206ebdcee2SJeff Cody     if (ret) {
22216ebdcee2SJeff Cody         goto exit;
22226ebdcee2SJeff Cody     }
22236ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
22246ebdcee2SJeff Cody 
22256ebdcee2SJeff Cody 
22266ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
22276ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
22286ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
22294f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
22306ebdcee2SJeff Cody     }
22316ebdcee2SJeff Cody     ret = 0;
22326ebdcee2SJeff Cody 
22336ebdcee2SJeff Cody exit:
22346ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
22356ebdcee2SJeff Cody         g_free(intermediate_state);
22366ebdcee2SJeff Cody     }
22376ebdcee2SJeff Cody     return ret;
22386ebdcee2SJeff Cody }
22396ebdcee2SJeff Cody 
22406ebdcee2SJeff Cody 
224171d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
224271d0770cSaliguori                                    size_t size)
224371d0770cSaliguori {
224471d0770cSaliguori     int64_t len;
224571d0770cSaliguori 
224671d0770cSaliguori     if (!bdrv_is_inserted(bs))
224771d0770cSaliguori         return -ENOMEDIUM;
224871d0770cSaliguori 
224971d0770cSaliguori     if (bs->growable)
225071d0770cSaliguori         return 0;
225171d0770cSaliguori 
225271d0770cSaliguori     len = bdrv_getlength(bs);
225371d0770cSaliguori 
2254fbb7b4e0SKevin Wolf     if (offset < 0)
2255fbb7b4e0SKevin Wolf         return -EIO;
2256fbb7b4e0SKevin Wolf 
2257fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
225871d0770cSaliguori         return -EIO;
225971d0770cSaliguori 
226071d0770cSaliguori     return 0;
226171d0770cSaliguori }
226271d0770cSaliguori 
226371d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
226471d0770cSaliguori                               int nb_sectors)
226571d0770cSaliguori {
2266eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2267eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
226871d0770cSaliguori }
226971d0770cSaliguori 
22701c9805a3SStefan Hajnoczi typedef struct RwCo {
22711c9805a3SStefan Hajnoczi     BlockDriverState *bs;
22721c9805a3SStefan Hajnoczi     int64_t sector_num;
22731c9805a3SStefan Hajnoczi     int nb_sectors;
22741c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
22751c9805a3SStefan Hajnoczi     bool is_write;
22761c9805a3SStefan Hajnoczi     int ret;
22774105eaaaSPeter Lieven     BdrvRequestFlags flags;
22781c9805a3SStefan Hajnoczi } RwCo;
22791c9805a3SStefan Hajnoczi 
22801c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2281fc01f7e7Sbellard {
22821c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2283fc01f7e7Sbellard 
22841c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
22851c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
22864105eaaaSPeter Lieven                                      rwco->nb_sectors, rwco->qiov,
22874105eaaaSPeter Lieven                                      rwco->flags);
22881c9805a3SStefan Hajnoczi     } else {
22891c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
22904105eaaaSPeter Lieven                                       rwco->nb_sectors, rwco->qiov,
22914105eaaaSPeter Lieven                                       rwco->flags);
22921c9805a3SStefan Hajnoczi     }
22931c9805a3SStefan Hajnoczi }
2294e7a8a783SKevin Wolf 
22951c9805a3SStefan Hajnoczi /*
22968d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
22971c9805a3SStefan Hajnoczi  */
22988d3b1a2dSKevin Wolf static int bdrv_rwv_co(BlockDriverState *bs, int64_t sector_num,
22994105eaaaSPeter Lieven                        QEMUIOVector *qiov, bool is_write,
23004105eaaaSPeter Lieven                        BdrvRequestFlags flags)
23011c9805a3SStefan Hajnoczi {
23021c9805a3SStefan Hajnoczi     Coroutine *co;
23031c9805a3SStefan Hajnoczi     RwCo rwco = {
23041c9805a3SStefan Hajnoczi         .bs = bs,
23051c9805a3SStefan Hajnoczi         .sector_num = sector_num,
23068d3b1a2dSKevin Wolf         .nb_sectors = qiov->size >> BDRV_SECTOR_BITS,
23078d3b1a2dSKevin Wolf         .qiov = qiov,
23081c9805a3SStefan Hajnoczi         .is_write = is_write,
23091c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
23104105eaaaSPeter Lieven         .flags = flags,
23111c9805a3SStefan Hajnoczi     };
23128d3b1a2dSKevin Wolf     assert((qiov->size & (BDRV_SECTOR_SIZE - 1)) == 0);
23131c9805a3SStefan Hajnoczi 
2314498e386cSZhi Yong Wu     /**
2315498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2316498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2317498e386cSZhi Yong Wu      * if it has been enabled.
2318498e386cSZhi Yong Wu      */
2319498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2320498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2321498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2322498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2323498e386cSZhi Yong Wu     }
2324498e386cSZhi Yong Wu 
23251c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
23261c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
23271c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
23281c9805a3SStefan Hajnoczi     } else {
23291c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
23301c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
23311c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
23321c9805a3SStefan Hajnoczi             qemu_aio_wait();
23331c9805a3SStefan Hajnoczi         }
23341c9805a3SStefan Hajnoczi     }
23351c9805a3SStefan Hajnoczi     return rwco.ret;
2336e7a8a783SKevin Wolf }
2337e7a8a783SKevin Wolf 
23388d3b1a2dSKevin Wolf /*
23398d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
23408d3b1a2dSKevin Wolf  */
23418d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
23424105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
23438d3b1a2dSKevin Wolf {
23448d3b1a2dSKevin Wolf     QEMUIOVector qiov;
23458d3b1a2dSKevin Wolf     struct iovec iov = {
23468d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
23478d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
23488d3b1a2dSKevin Wolf     };
23498d3b1a2dSKevin Wolf 
23508d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
23514105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, &qiov, is_write, flags);
23528d3b1a2dSKevin Wolf }
23538d3b1a2dSKevin Wolf 
23541c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
23551c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
23561c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
23571c9805a3SStefan Hajnoczi {
23584105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
235983f64091Sbellard }
2360fc01f7e7Sbellard 
236107d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
236207d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
236307d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
236407d27a44SMarkus Armbruster {
236507d27a44SMarkus Armbruster     bool enabled;
236607d27a44SMarkus Armbruster     int ret;
236707d27a44SMarkus Armbruster 
236807d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
236907d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
23704e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
237107d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
237207d27a44SMarkus Armbruster     return ret;
237307d27a44SMarkus Armbruster }
237407d27a44SMarkus Armbruster 
237519cb3738Sbellard /* Return < 0 if error. Important errors are:
237619cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
237719cb3738Sbellard   -ENOMEDIUM   No media inserted.
237819cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
237919cb3738Sbellard   -EACCES      Trying to write a read-only device
238019cb3738Sbellard */
2381fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2382fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2383fc01f7e7Sbellard {
23844105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
238583f64091Sbellard }
238683f64091Sbellard 
23878d3b1a2dSKevin Wolf int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
23888d3b1a2dSKevin Wolf {
23894105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, qiov, true, 0);
23904105eaaaSPeter Lieven }
23914105eaaaSPeter Lieven 
23924105eaaaSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
23934105eaaaSPeter Lieven {
23944105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
23954105eaaaSPeter Lieven                       BDRV_REQ_ZERO_WRITE);
23968d3b1a2dSKevin Wolf }
23978d3b1a2dSKevin Wolf 
2398eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2399eda578e5Saliguori                void *buf, int count1)
240083f64091Sbellard {
24016ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
240283f64091Sbellard     int len, nb_sectors, count;
240383f64091Sbellard     int64_t sector_num;
24049a8c4cceSKevin Wolf     int ret;
240583f64091Sbellard 
240683f64091Sbellard     count = count1;
240783f64091Sbellard     /* first read to align to sector start */
24086ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
240983f64091Sbellard     if (len > count)
241083f64091Sbellard         len = count;
24116ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
241283f64091Sbellard     if (len > 0) {
24139a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
24149a8c4cceSKevin Wolf             return ret;
24156ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
241683f64091Sbellard         count -= len;
241783f64091Sbellard         if (count == 0)
241883f64091Sbellard             return count1;
241983f64091Sbellard         sector_num++;
242083f64091Sbellard         buf += len;
242183f64091Sbellard     }
242283f64091Sbellard 
242383f64091Sbellard     /* read the sectors "in place" */
24246ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
242583f64091Sbellard     if (nb_sectors > 0) {
24269a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
24279a8c4cceSKevin Wolf             return ret;
242883f64091Sbellard         sector_num += nb_sectors;
24296ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
243083f64091Sbellard         buf += len;
243183f64091Sbellard         count -= len;
243283f64091Sbellard     }
243383f64091Sbellard 
243483f64091Sbellard     /* add data from the last sector */
243583f64091Sbellard     if (count > 0) {
24369a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
24379a8c4cceSKevin Wolf             return ret;
243883f64091Sbellard         memcpy(buf, tmp_buf, count);
243983f64091Sbellard     }
244083f64091Sbellard     return count1;
244183f64091Sbellard }
244283f64091Sbellard 
24438d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
244483f64091Sbellard {
24456ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
244683f64091Sbellard     int len, nb_sectors, count;
244783f64091Sbellard     int64_t sector_num;
24489a8c4cceSKevin Wolf     int ret;
244983f64091Sbellard 
24508d3b1a2dSKevin Wolf     count = qiov->size;
24518d3b1a2dSKevin Wolf 
245283f64091Sbellard     /* first write to align to sector start */
24536ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
245483f64091Sbellard     if (len > count)
245583f64091Sbellard         len = count;
24566ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
245783f64091Sbellard     if (len > 0) {
24589a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
24599a8c4cceSKevin Wolf             return ret;
24608d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
24618d3b1a2dSKevin Wolf                           len);
24629a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
24639a8c4cceSKevin Wolf             return ret;
246483f64091Sbellard         count -= len;
246583f64091Sbellard         if (count == 0)
24668d3b1a2dSKevin Wolf             return qiov->size;
246783f64091Sbellard         sector_num++;
246883f64091Sbellard     }
246983f64091Sbellard 
247083f64091Sbellard     /* write the sectors "in place" */
24716ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
247283f64091Sbellard     if (nb_sectors > 0) {
24738d3b1a2dSKevin Wolf         QEMUIOVector qiov_inplace;
24748d3b1a2dSKevin Wolf 
24758d3b1a2dSKevin Wolf         qemu_iovec_init(&qiov_inplace, qiov->niov);
24768d3b1a2dSKevin Wolf         qemu_iovec_concat(&qiov_inplace, qiov, len,
24778d3b1a2dSKevin Wolf                           nb_sectors << BDRV_SECTOR_BITS);
24788d3b1a2dSKevin Wolf         ret = bdrv_writev(bs, sector_num, &qiov_inplace);
24798d3b1a2dSKevin Wolf         qemu_iovec_destroy(&qiov_inplace);
24808d3b1a2dSKevin Wolf         if (ret < 0) {
24819a8c4cceSKevin Wolf             return ret;
24828d3b1a2dSKevin Wolf         }
24838d3b1a2dSKevin Wolf 
248483f64091Sbellard         sector_num += nb_sectors;
24856ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
248683f64091Sbellard         count -= len;
248783f64091Sbellard     }
248883f64091Sbellard 
248983f64091Sbellard     /* add data from the last sector */
249083f64091Sbellard     if (count > 0) {
24919a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
24929a8c4cceSKevin Wolf             return ret;
24938d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
24949a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
24959a8c4cceSKevin Wolf             return ret;
249683f64091Sbellard     }
24978d3b1a2dSKevin Wolf     return qiov->size;
24988d3b1a2dSKevin Wolf }
24998d3b1a2dSKevin Wolf 
25008d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
25018d3b1a2dSKevin Wolf                 const void *buf, int count1)
25028d3b1a2dSKevin Wolf {
25038d3b1a2dSKevin Wolf     QEMUIOVector qiov;
25048d3b1a2dSKevin Wolf     struct iovec iov = {
25058d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
25068d3b1a2dSKevin Wolf         .iov_len    = count1,
25078d3b1a2dSKevin Wolf     };
25088d3b1a2dSKevin Wolf 
25098d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
25108d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
251183f64091Sbellard }
251283f64091Sbellard 
2513f08145feSKevin Wolf /*
2514f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2515f08145feSKevin Wolf  * request (acts as a barrier)
2516f08145feSKevin Wolf  *
2517f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2518f08145feSKevin Wolf  */
2519f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2520f08145feSKevin Wolf     const void *buf, int count)
2521f08145feSKevin Wolf {
2522f08145feSKevin Wolf     int ret;
2523f08145feSKevin Wolf 
2524f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2525f08145feSKevin Wolf     if (ret < 0) {
2526f08145feSKevin Wolf         return ret;
2527f08145feSKevin Wolf     }
2528f08145feSKevin Wolf 
2529f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2530f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2531f08145feSKevin Wolf         bdrv_flush(bs);
2532f08145feSKevin Wolf     }
2533f08145feSKevin Wolf 
2534f08145feSKevin Wolf     return 0;
2535f08145feSKevin Wolf }
2536f08145feSKevin Wolf 
2537470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2538ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2539ab185921SStefan Hajnoczi {
2540ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2541ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2542ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2543ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2544ab185921SStefan Hajnoczi      */
2545ab185921SStefan Hajnoczi     void *bounce_buffer;
2546ab185921SStefan Hajnoczi 
254779c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2548ab185921SStefan Hajnoczi     struct iovec iov;
2549ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2550ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2551ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2552ab185921SStefan Hajnoczi     size_t skip_bytes;
2553ab185921SStefan Hajnoczi     int ret;
2554ab185921SStefan Hajnoczi 
2555ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2556ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2557ab185921SStefan Hajnoczi      */
2558343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2559ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2560ab185921SStefan Hajnoczi 
2561470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2562ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2563ab185921SStefan Hajnoczi 
2564ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2565ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2566ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2567ab185921SStefan Hajnoczi 
256879c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2569ab185921SStefan Hajnoczi                              &bounce_qiov);
2570ab185921SStefan Hajnoczi     if (ret < 0) {
2571ab185921SStefan Hajnoczi         goto err;
2572ab185921SStefan Hajnoczi     }
2573ab185921SStefan Hajnoczi 
257479c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
257579c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2576621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
257779c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
257879c053bdSStefan Hajnoczi     } else {
2579f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2580f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2581f05fa4adSPaolo Bonzini          */
258279c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2583ab185921SStefan Hajnoczi                                   &bounce_qiov);
258479c053bdSStefan Hajnoczi     }
258579c053bdSStefan Hajnoczi 
2586ab185921SStefan Hajnoczi     if (ret < 0) {
2587ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2588ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2589ab185921SStefan Hajnoczi          * Simply report it in all cases.
2590ab185921SStefan Hajnoczi          */
2591ab185921SStefan Hajnoczi         goto err;
2592ab185921SStefan Hajnoczi     }
2593ab185921SStefan Hajnoczi 
2594ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
259503396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2596ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2597ab185921SStefan Hajnoczi 
2598ab185921SStefan Hajnoczi err:
2599ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2600ab185921SStefan Hajnoczi     return ret;
2601ab185921SStefan Hajnoczi }
2602ab185921SStefan Hajnoczi 
2603c5fbe571SStefan Hajnoczi /*
2604c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
2605c5fbe571SStefan Hajnoczi  */
2606c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2607470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2608470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
2609da1fa91dSKevin Wolf {
2610da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2611dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
2612dbffbdcfSStefan Hajnoczi     int ret;
2613da1fa91dSKevin Wolf 
2614da1fa91dSKevin Wolf     if (!drv) {
2615da1fa91dSKevin Wolf         return -ENOMEDIUM;
2616da1fa91dSKevin Wolf     }
2617da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2618da1fa91dSKevin Wolf         return -EIO;
2619da1fa91dSKevin Wolf     }
2620da1fa91dSKevin Wolf 
2621f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
2622470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
2623470c0504SStefan Hajnoczi     }
2624470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2625470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
2626470c0504SStefan Hajnoczi     }
2627470c0504SStefan Hajnoczi 
2628470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2629f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2630f4658285SStefan Hajnoczi     }
2631f4658285SStefan Hajnoczi 
2632cc0681c4SBenoît Canet     /* throttling disk I/O */
2633cc0681c4SBenoît Canet     if (bs->io_limits_enabled) {
2634cc0681c4SBenoît Canet         bdrv_io_limits_intercept(bs, nb_sectors, false);
2635cc0681c4SBenoît Canet     }
2636cc0681c4SBenoît Canet 
2637dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2638ab185921SStefan Hajnoczi 
2639470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2640ab185921SStefan Hajnoczi         int pnum;
2641ab185921SStefan Hajnoczi 
2642bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
2643ab185921SStefan Hajnoczi         if (ret < 0) {
2644ab185921SStefan Hajnoczi             goto out;
2645ab185921SStefan Hajnoczi         }
2646ab185921SStefan Hajnoczi 
2647ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2648470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2649ab185921SStefan Hajnoczi             goto out;
2650ab185921SStefan Hajnoczi         }
2651ab185921SStefan Hajnoczi     }
2652ab185921SStefan Hajnoczi 
2653893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2654dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2655893a8f62SMORITA Kazutaka     } else {
2656893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2657893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2658893a8f62SMORITA Kazutaka 
2659893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2660893a8f62SMORITA Kazutaka         if (len < 0) {
2661893a8f62SMORITA Kazutaka             ret = len;
2662893a8f62SMORITA Kazutaka             goto out;
2663893a8f62SMORITA Kazutaka         }
2664893a8f62SMORITA Kazutaka 
2665d055a1feSFam Zheng         total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
2666893a8f62SMORITA Kazutaka         max_nb_sectors = MAX(0, total_sectors - sector_num);
2667893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
2668893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
2669893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
2670893a8f62SMORITA Kazutaka         } else {
2671893a8f62SMORITA Kazutaka             ret = 0;
2672893a8f62SMORITA Kazutaka         }
2673893a8f62SMORITA Kazutaka 
2674893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
2675893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2676893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
2677893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
2678893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
2679893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
2680893a8f62SMORITA Kazutaka         }
2681893a8f62SMORITA Kazutaka     }
2682ab185921SStefan Hajnoczi 
2683ab185921SStefan Hajnoczi out:
2684dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2685470c0504SStefan Hajnoczi 
2686470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2687470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
2688470c0504SStefan Hajnoczi     }
2689470c0504SStefan Hajnoczi 
2690dbffbdcfSStefan Hajnoczi     return ret;
2691da1fa91dSKevin Wolf }
2692da1fa91dSKevin Wolf 
2693c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2694da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
2695da1fa91dSKevin Wolf {
2696c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2697da1fa91dSKevin Wolf 
2698470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2699470c0504SStefan Hajnoczi }
2700470c0504SStefan Hajnoczi 
2701470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2702470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2703470c0504SStefan Hajnoczi {
2704470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2705470c0504SStefan Hajnoczi 
2706470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2707470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
2708c5fbe571SStefan Hajnoczi }
2709c5fbe571SStefan Hajnoczi 
2710f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2711f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
2712f08f2ddaSStefan Hajnoczi {
2713f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2714f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
2715f08f2ddaSStefan Hajnoczi     struct iovec iov;
2716f08f2ddaSStefan Hajnoczi     int ret;
2717f08f2ddaSStefan Hajnoczi 
2718621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
2719621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
2720621f0589SKevin Wolf 
2721f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
2722f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
2723621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2724621f0589SKevin Wolf         if (ret != -ENOTSUP) {
2725621f0589SKevin Wolf             return ret;
2726621f0589SKevin Wolf         }
2727f08f2ddaSStefan Hajnoczi     }
2728f08f2ddaSStefan Hajnoczi 
2729f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
2730f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
2731f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2732f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
2733f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
2734f08f2ddaSStefan Hajnoczi 
2735f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2736f08f2ddaSStefan Hajnoczi 
2737f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
2738f08f2ddaSStefan Hajnoczi     return ret;
2739f08f2ddaSStefan Hajnoczi }
2740f08f2ddaSStefan Hajnoczi 
2741c5fbe571SStefan Hajnoczi /*
2742c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
2743c5fbe571SStefan Hajnoczi  */
2744c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2745f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2746f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
2747c5fbe571SStefan Hajnoczi {
2748c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
2749dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
27506b7cb247SStefan Hajnoczi     int ret;
2751da1fa91dSKevin Wolf 
2752da1fa91dSKevin Wolf     if (!bs->drv) {
2753da1fa91dSKevin Wolf         return -ENOMEDIUM;
2754da1fa91dSKevin Wolf     }
2755da1fa91dSKevin Wolf     if (bs->read_only) {
2756da1fa91dSKevin Wolf         return -EACCES;
2757da1fa91dSKevin Wolf     }
2758da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2759da1fa91dSKevin Wolf         return -EIO;
2760da1fa91dSKevin Wolf     }
2761da1fa91dSKevin Wolf 
2762470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2763f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2764f4658285SStefan Hajnoczi     }
2765f4658285SStefan Hajnoczi 
2766cc0681c4SBenoît Canet     /* throttling disk I/O */
2767cc0681c4SBenoît Canet     if (bs->io_limits_enabled) {
2768cc0681c4SBenoît Canet         bdrv_io_limits_intercept(bs, nb_sectors, true);
2769cc0681c4SBenoît Canet     }
2770cc0681c4SBenoît Canet 
2771dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2772dbffbdcfSStefan Hajnoczi 
2773d616b224SStefan Hajnoczi     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2774d616b224SStefan Hajnoczi 
2775d616b224SStefan Hajnoczi     if (ret < 0) {
2776d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
2777d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
2778f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2779f08f2ddaSStefan Hajnoczi     } else {
27806b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2781f08f2ddaSStefan Hajnoczi     }
27826b7cb247SStefan Hajnoczi 
2783f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
2784f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
2785f05fa4adSPaolo Bonzini     }
2786f05fa4adSPaolo Bonzini 
2787da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
27881755da16SPaolo Bonzini         bdrv_set_dirty(bs, sector_num, nb_sectors);
2789da1fa91dSKevin Wolf     }
2790da1fa91dSKevin Wolf 
2791da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2792da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
2793da1fa91dSKevin Wolf     }
2794df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
2795df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
2796df2a6f29SPaolo Bonzini     }
2797da1fa91dSKevin Wolf 
2798dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2799dbffbdcfSStefan Hajnoczi 
28006b7cb247SStefan Hajnoczi     return ret;
2801da1fa91dSKevin Wolf }
2802da1fa91dSKevin Wolf 
2803c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2804c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
2805c5fbe571SStefan Hajnoczi {
2806c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2807c5fbe571SStefan Hajnoczi 
2808f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2809f08f2ddaSStefan Hajnoczi }
2810f08f2ddaSStefan Hajnoczi 
2811f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2812f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
2813f08f2ddaSStefan Hajnoczi {
2814f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2815f08f2ddaSStefan Hajnoczi 
2816f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2817f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
2818c5fbe571SStefan Hajnoczi }
2819c5fbe571SStefan Hajnoczi 
282083f64091Sbellard /**
282183f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
282283f64091Sbellard  */
282383f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
282483f64091Sbellard {
282583f64091Sbellard     BlockDriver *drv = bs->drv;
282651762288SStefan Hajnoczi     int ret;
282783f64091Sbellard     if (!drv)
282819cb3738Sbellard         return -ENOMEDIUM;
282983f64091Sbellard     if (!drv->bdrv_truncate)
283083f64091Sbellard         return -ENOTSUP;
283159f2689dSNaphtali Sprei     if (bs->read_only)
283259f2689dSNaphtali Sprei         return -EACCES;
28338591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
28348591675fSMarcelo Tosatti         return -EBUSY;
283551762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
283651762288SStefan Hajnoczi     if (ret == 0) {
283751762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2838145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
283951762288SStefan Hajnoczi     }
284051762288SStefan Hajnoczi     return ret;
284183f64091Sbellard }
284283f64091Sbellard 
284383f64091Sbellard /**
28444a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
28454a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
28464a1d5e1fSFam Zheng  */
28474a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
28484a1d5e1fSFam Zheng {
28494a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
28504a1d5e1fSFam Zheng     if (!drv) {
28514a1d5e1fSFam Zheng         return -ENOMEDIUM;
28524a1d5e1fSFam Zheng     }
28534a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
28544a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
28554a1d5e1fSFam Zheng     }
28564a1d5e1fSFam Zheng     if (bs->file) {
28574a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
28584a1d5e1fSFam Zheng     }
28594a1d5e1fSFam Zheng     return -ENOTSUP;
28604a1d5e1fSFam Zheng }
28614a1d5e1fSFam Zheng 
28624a1d5e1fSFam Zheng /**
286383f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
286483f64091Sbellard  */
286583f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
286683f64091Sbellard {
286783f64091Sbellard     BlockDriver *drv = bs->drv;
286883f64091Sbellard     if (!drv)
286919cb3738Sbellard         return -ENOMEDIUM;
287051762288SStefan Hajnoczi 
2871df2a6f29SPaolo Bonzini     if (bdrv_dev_has_removable_media(bs)) {
287246a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
287383f64091Sbellard             return drv->bdrv_getlength(bs);
2874fc01f7e7Sbellard         }
287546a4e4e6SStefan Hajnoczi     }
287646a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
287746a4e4e6SStefan Hajnoczi }
2878fc01f7e7Sbellard 
287919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
288096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2881fc01f7e7Sbellard {
288219cb3738Sbellard     int64_t length;
288319cb3738Sbellard     length = bdrv_getlength(bs);
288419cb3738Sbellard     if (length < 0)
288519cb3738Sbellard         length = 0;
288619cb3738Sbellard     else
28876ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
288819cb3738Sbellard     *nb_sectors_ptr = length;
2889fc01f7e7Sbellard }
2890cf98951bSbellard 
2891ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2892ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2893abd7f68dSMarkus Armbruster {
2894abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2895abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2896abd7f68dSMarkus Armbruster }
2897abd7f68dSMarkus Armbruster 
28981ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2899abd7f68dSMarkus Armbruster {
2900abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2901abd7f68dSMarkus Armbruster }
2902abd7f68dSMarkus Armbruster 
29033e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
29043e1caa5fSPaolo Bonzini {
29053e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
29063e1caa5fSPaolo Bonzini 
29073e1caa5fSPaolo Bonzini     switch (on_err) {
29083e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
29093e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
29103e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
29113e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
29123e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
29133e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
29143e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
29153e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
29163e1caa5fSPaolo Bonzini     default:
29173e1caa5fSPaolo Bonzini         abort();
29183e1caa5fSPaolo Bonzini     }
29193e1caa5fSPaolo Bonzini }
29203e1caa5fSPaolo Bonzini 
29213e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
29223e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
29233e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
29243e1caa5fSPaolo Bonzini  */
29253e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
29263e1caa5fSPaolo Bonzini                        bool is_read, int error)
29273e1caa5fSPaolo Bonzini {
29283e1caa5fSPaolo Bonzini     assert(error >= 0);
292932c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
29303e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
29313e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
29323e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
29333e1caa5fSPaolo Bonzini     }
29343e1caa5fSPaolo Bonzini }
29353e1caa5fSPaolo Bonzini 
2936b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2937b338082bSbellard {
2938b338082bSbellard     return bs->read_only;
2939b338082bSbellard }
2940b338082bSbellard 
2941985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2942985a03b0Sths {
2943985a03b0Sths     return bs->sg;
2944985a03b0Sths }
2945985a03b0Sths 
2946e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2947e900a7b7SChristoph Hellwig {
2948e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2949e900a7b7SChristoph Hellwig }
2950e900a7b7SChristoph Hellwig 
2951425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2952425b0148SPaolo Bonzini {
2953425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
295455b110f2SJeff Cody 
295555b110f2SJeff Cody     /* so a reopen() will preserve wce */
295655b110f2SJeff Cody     if (wce) {
295755b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
295855b110f2SJeff Cody     } else {
295955b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
296055b110f2SJeff Cody     }
2961425b0148SPaolo Bonzini }
2962425b0148SPaolo Bonzini 
2963ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2964ea2384d3Sbellard {
2965ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2966ea2384d3Sbellard         return 1;
2967ea2384d3Sbellard     return bs->encrypted;
2968ea2384d3Sbellard }
2969ea2384d3Sbellard 
2970c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2971c0f4ce77Saliguori {
2972c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2973c0f4ce77Saliguori 
2974c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2975c0f4ce77Saliguori         return 1;
2976c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2977c0f4ce77Saliguori }
2978c0f4ce77Saliguori 
2979ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2980ea2384d3Sbellard {
2981ea2384d3Sbellard     int ret;
2982ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2983ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2984ea2384d3Sbellard         if (ret < 0)
2985ea2384d3Sbellard             return ret;
2986ea2384d3Sbellard         if (!bs->encrypted)
2987ea2384d3Sbellard             return 0;
2988ea2384d3Sbellard     }
2989fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2990fd04a2aeSShahar Havivi         return -EINVAL;
2991fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2992fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2993fd04a2aeSShahar Havivi     }
2994c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2995bb5fc20fSaliguori     if (ret < 0) {
2996bb5fc20fSaliguori         bs->valid_key = 0;
2997bb5fc20fSaliguori     } else if (!bs->valid_key) {
2998bb5fc20fSaliguori         bs->valid_key = 1;
2999bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
30007d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3001bb5fc20fSaliguori     }
3002c0f4ce77Saliguori     return ret;
3003ea2384d3Sbellard }
3004ea2384d3Sbellard 
3005f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3006ea2384d3Sbellard {
3007f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3008ea2384d3Sbellard }
3009ea2384d3Sbellard 
3010ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3011ea2384d3Sbellard                          void *opaque)
3012ea2384d3Sbellard {
3013ea2384d3Sbellard     BlockDriver *drv;
3014ea2384d3Sbellard 
30158a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3016ea2384d3Sbellard         it(opaque, drv->format_name);
3017ea2384d3Sbellard     }
3018ea2384d3Sbellard }
3019ea2384d3Sbellard 
3020b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3021b338082bSbellard {
3022b338082bSbellard     BlockDriverState *bs;
3023b338082bSbellard 
30241b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
30251b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3026b338082bSbellard             return bs;
3027b338082bSbellard         }
30281b7bdbc1SStefan Hajnoczi     }
3029b338082bSbellard     return NULL;
3030b338082bSbellard }
3031b338082bSbellard 
30322f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
30332f399b0aSMarkus Armbruster {
30342f399b0aSMarkus Armbruster     if (!bs) {
30352f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
30362f399b0aSMarkus Armbruster     }
30372f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
30382f399b0aSMarkus Armbruster }
30392f399b0aSMarkus Armbruster 
304051de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
304181d0912dSbellard {
304281d0912dSbellard     BlockDriverState *bs;
304381d0912dSbellard 
30441b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
304551de9760Saliguori         it(opaque, bs);
304681d0912dSbellard     }
304781d0912dSbellard }
304881d0912dSbellard 
3049ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3050ea2384d3Sbellard {
3051ea2384d3Sbellard     return bs->device_name;
3052ea2384d3Sbellard }
3053ea2384d3Sbellard 
3054c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3055c8433287SMarkus Armbruster {
3056c8433287SMarkus Armbruster     return bs->open_flags;
3057c8433287SMarkus Armbruster }
3058c8433287SMarkus Armbruster 
3059f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3060c6ca28d6Saliguori {
3061c6ca28d6Saliguori     BlockDriverState *bs;
3062f0f0fdfeSKevin Wolf     int result = 0;
3063c6ca28d6Saliguori 
30641b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
3065f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3066f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3067f0f0fdfeSKevin Wolf             result = ret;
3068c6ca28d6Saliguori         }
30691b7bdbc1SStefan Hajnoczi     }
3070c6ca28d6Saliguori 
3071f0f0fdfeSKevin Wolf     return result;
3072f0f0fdfeSKevin Wolf }
3073f0f0fdfeSKevin Wolf 
30743ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
30753ac21627SPeter Lieven {
30763ac21627SPeter Lieven     return 1;
30773ac21627SPeter Lieven }
30783ac21627SPeter Lieven 
3079f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3080f2feebbdSKevin Wolf {
3081f2feebbdSKevin Wolf     assert(bs->drv);
3082f2feebbdSKevin Wolf 
308311212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
308411212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
308511212d8fSPaolo Bonzini     if (bs->backing_hd) {
308611212d8fSPaolo Bonzini         return 0;
308711212d8fSPaolo Bonzini     }
3088336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3089336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3090f2feebbdSKevin Wolf     }
3091f2feebbdSKevin Wolf 
30923ac21627SPeter Lieven     /* safe default */
30933ac21627SPeter Lieven     return 0;
3094f2feebbdSKevin Wolf }
3095f2feebbdSKevin Wolf 
3096b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3097376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3098b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3099376ae3f1SStefan Hajnoczi     int64_t sector_num;
3100376ae3f1SStefan Hajnoczi     int nb_sectors;
3101376ae3f1SStefan Hajnoczi     int *pnum;
3102b6b8a333SPaolo Bonzini     int64_t ret;
3103376ae3f1SStefan Hajnoczi     bool done;
3104b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3105376ae3f1SStefan Hajnoczi 
3106f58c7b35Sths /*
3107f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3108f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3109f58c7b35Sths  * hence all their sectors are reported as allocated.
3110f58c7b35Sths  *
3111bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3112bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3113bd9533e3SStefan Hajnoczi  *
3114f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3115f58c7b35Sths  * the specified sector) that are known to be in the same
3116f58c7b35Sths  * allocated/unallocated state.
3117f58c7b35Sths  *
3118bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3119bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3120f58c7b35Sths  */
3121b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
3122bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
3123060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
3124f58c7b35Sths {
3125617ccb46SPaolo Bonzini     int64_t length;
3126f58c7b35Sths     int64_t n;
31275daa74a6SPaolo Bonzini     int64_t ret, ret2;
3128bd9533e3SStefan Hajnoczi 
3129617ccb46SPaolo Bonzini     length = bdrv_getlength(bs);
3130617ccb46SPaolo Bonzini     if (length < 0) {
3131617ccb46SPaolo Bonzini         return length;
3132617ccb46SPaolo Bonzini     }
3133617ccb46SPaolo Bonzini 
3134617ccb46SPaolo Bonzini     if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
31356aebab14SStefan Hajnoczi         *pnum = 0;
31366aebab14SStefan Hajnoczi         return 0;
31376aebab14SStefan Hajnoczi     }
3138bd9533e3SStefan Hajnoczi 
31396aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3140bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3141bd9533e3SStefan Hajnoczi         nb_sectors = n;
3142bd9533e3SStefan Hajnoczi     }
3143bd9533e3SStefan Hajnoczi 
3144b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
3145bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
3146918e92d7SPaolo Bonzini         ret = BDRV_BLOCK_DATA;
3147918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
3148918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
3149918e92d7SPaolo Bonzini         }
3150918e92d7SPaolo Bonzini         return ret;
31516aebab14SStefan Hajnoczi     }
31526aebab14SStefan Hajnoczi 
3153415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
3154415b5b01SPaolo Bonzini     if (ret < 0) {
31553e0a233dSPeter Lieven         *pnum = 0;
3156415b5b01SPaolo Bonzini         return ret;
3157415b5b01SPaolo Bonzini     }
3158415b5b01SPaolo Bonzini 
315992bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
316092bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
316192bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
316292bc50a5SPeter Lieven                                      *pnum, pnum);
316392bc50a5SPeter Lieven     }
316492bc50a5SPeter Lieven 
3165f0ad5712SPaolo Bonzini     if (!(ret & BDRV_BLOCK_DATA)) {
3166f0ad5712SPaolo Bonzini         if (bdrv_has_zero_init(bs)) {
3167415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
31681f9db224SPeter Lieven         } else if (bs->backing_hd) {
3169f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
3170f0ad5712SPaolo Bonzini             int64_t length2 = bdrv_getlength(bs2);
3171f0ad5712SPaolo Bonzini             if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
3172f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
3173f0ad5712SPaolo Bonzini             }
3174f0ad5712SPaolo Bonzini         }
3175415b5b01SPaolo Bonzini     }
31765daa74a6SPaolo Bonzini 
31775daa74a6SPaolo Bonzini     if (bs->file &&
31785daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
31795daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
31805daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
31815daa74a6SPaolo Bonzini                                         *pnum, pnum);
31825daa74a6SPaolo Bonzini         if (ret2 >= 0) {
31835daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
31845daa74a6SPaolo Bonzini              * is useful but not necessary.
31855daa74a6SPaolo Bonzini              */
31865daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
31875daa74a6SPaolo Bonzini         }
31885daa74a6SPaolo Bonzini     }
31895daa74a6SPaolo Bonzini 
3190415b5b01SPaolo Bonzini     return ret;
3191060f51c9SStefan Hajnoczi }
3192060f51c9SStefan Hajnoczi 
3193b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
3194b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
3195060f51c9SStefan Hajnoczi {
3196b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
3197060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3198060f51c9SStefan Hajnoczi 
3199b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
3200060f51c9SStefan Hajnoczi                                          data->pnum);
3201060f51c9SStefan Hajnoczi     data->done = true;
3202060f51c9SStefan Hajnoczi }
3203060f51c9SStefan Hajnoczi 
3204060f51c9SStefan Hajnoczi /*
3205b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
3206060f51c9SStefan Hajnoczi  *
3207b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
3208060f51c9SStefan Hajnoczi  */
3209b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
3210b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
3211060f51c9SStefan Hajnoczi {
3212376ae3f1SStefan Hajnoczi     Coroutine *co;
3213b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
3214376ae3f1SStefan Hajnoczi         .bs = bs,
3215376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3216376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3217376ae3f1SStefan Hajnoczi         .pnum = pnum,
3218376ae3f1SStefan Hajnoczi         .done = false,
3219376ae3f1SStefan Hajnoczi     };
3220376ae3f1SStefan Hajnoczi 
3221bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
3222bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
3223b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
3224bdad13b9SPaolo Bonzini     } else {
3225b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
3226376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
3227376ae3f1SStefan Hajnoczi         while (!data.done) {
3228376ae3f1SStefan Hajnoczi             qemu_aio_wait();
3229376ae3f1SStefan Hajnoczi         }
3230bdad13b9SPaolo Bonzini     }
3231376ae3f1SStefan Hajnoczi     return data.ret;
3232376ae3f1SStefan Hajnoczi }
3233f58c7b35Sths 
3234b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
3235b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
3236b6b8a333SPaolo Bonzini {
32374333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
32384333bb71SPaolo Bonzini     if (ret < 0) {
32394333bb71SPaolo Bonzini         return ret;
32404333bb71SPaolo Bonzini     }
32414333bb71SPaolo Bonzini     return
32424333bb71SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) ||
32434333bb71SPaolo Bonzini         ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
3244b6b8a333SPaolo Bonzini }
3245b6b8a333SPaolo Bonzini 
3246188a7bbfSPaolo Bonzini /*
3247188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3248188a7bbfSPaolo Bonzini  *
3249188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3250188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3251188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3252188a7bbfSPaolo Bonzini  *
3253188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3254188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3255188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3256188a7bbfSPaolo Bonzini  *
3257188a7bbfSPaolo Bonzini  */
32584f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
3259188a7bbfSPaolo Bonzini                             BlockDriverState *base,
3260188a7bbfSPaolo Bonzini                             int64_t sector_num,
3261188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
3262188a7bbfSPaolo Bonzini {
3263188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3264188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3265188a7bbfSPaolo Bonzini 
3266188a7bbfSPaolo Bonzini     intermediate = top;
3267188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3268188a7bbfSPaolo Bonzini         int pnum_inter;
3269bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
3270188a7bbfSPaolo Bonzini                                 &pnum_inter);
3271188a7bbfSPaolo Bonzini         if (ret < 0) {
3272188a7bbfSPaolo Bonzini             return ret;
3273188a7bbfSPaolo Bonzini         } else if (ret) {
3274188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3275188a7bbfSPaolo Bonzini             return 1;
3276188a7bbfSPaolo Bonzini         }
3277188a7bbfSPaolo Bonzini 
3278188a7bbfSPaolo Bonzini         /*
3279188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3280188a7bbfSPaolo Bonzini          * might have
3281188a7bbfSPaolo Bonzini          *
3282188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3283188a7bbfSPaolo Bonzini          */
328463ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
328563ba17d3SVishvananda Ishaya             (intermediate == top ||
328663ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3287188a7bbfSPaolo Bonzini             n = pnum_inter;
3288188a7bbfSPaolo Bonzini         }
3289188a7bbfSPaolo Bonzini 
3290188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3291188a7bbfSPaolo Bonzini     }
3292188a7bbfSPaolo Bonzini 
3293188a7bbfSPaolo Bonzini     *pnum = n;
3294188a7bbfSPaolo Bonzini     return 0;
3295188a7bbfSPaolo Bonzini }
3296188a7bbfSPaolo Bonzini 
3297045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3298045df330Saliguori {
3299045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3300045df330Saliguori         return bs->backing_file;
3301045df330Saliguori     else if (bs->encrypted)
3302045df330Saliguori         return bs->filename;
3303045df330Saliguori     else
3304045df330Saliguori         return NULL;
3305045df330Saliguori }
3306045df330Saliguori 
330783f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
330883f64091Sbellard                                char *filename, int filename_size)
330983f64091Sbellard {
331083f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
331183f64091Sbellard }
331283f64091Sbellard 
3313faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3314faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3315faea38e7Sbellard {
3316faea38e7Sbellard     BlockDriver *drv = bs->drv;
3317faea38e7Sbellard     if (!drv)
331819cb3738Sbellard         return -ENOMEDIUM;
3319faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3320faea38e7Sbellard         return -ENOTSUP;
3321fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3322fbb7b4e0SKevin Wolf         return -EIO;
33237cd1e32aSlirans@il.ibm.com 
33241755da16SPaolo Bonzini     assert(!bs->dirty_bitmap);
33257cd1e32aSlirans@il.ibm.com 
3326faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3327faea38e7Sbellard }
3328faea38e7Sbellard 
3329faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3330faea38e7Sbellard {
3331faea38e7Sbellard     BlockDriver *drv = bs->drv;
3332faea38e7Sbellard     if (!drv)
333319cb3738Sbellard         return -ENOMEDIUM;
3334faea38e7Sbellard     if (!drv->bdrv_get_info)
3335faea38e7Sbellard         return -ENOTSUP;
3336faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3337faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3338faea38e7Sbellard }
3339faea38e7Sbellard 
3340eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3341eae041feSMax Reitz {
3342eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3343eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3344eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3345eae041feSMax Reitz     }
3346eae041feSMax Reitz     return NULL;
3347eae041feSMax Reitz }
3348eae041feSMax Reitz 
334945566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
335045566e9cSChristoph Hellwig                       int64_t pos, int size)
3351178e08a5Saliguori {
3352cf8074b3SKevin Wolf     QEMUIOVector qiov;
3353cf8074b3SKevin Wolf     struct iovec iov = {
3354cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
3355cf8074b3SKevin Wolf         .iov_len    = size,
3356cf8074b3SKevin Wolf     };
3357cf8074b3SKevin Wolf 
3358cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
3359cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
3360cf8074b3SKevin Wolf }
3361cf8074b3SKevin Wolf 
3362cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3363cf8074b3SKevin Wolf {
3364178e08a5Saliguori     BlockDriver *drv = bs->drv;
3365cf8074b3SKevin Wolf 
3366cf8074b3SKevin Wolf     if (!drv) {
3367178e08a5Saliguori         return -ENOMEDIUM;
3368cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
3369cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
3370cf8074b3SKevin Wolf     } else if (bs->file) {
3371cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
3372cf8074b3SKevin Wolf     }
3373cf8074b3SKevin Wolf 
33747cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3375178e08a5Saliguori }
3376178e08a5Saliguori 
337745566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
337845566e9cSChristoph Hellwig                       int64_t pos, int size)
3379178e08a5Saliguori {
3380178e08a5Saliguori     BlockDriver *drv = bs->drv;
3381178e08a5Saliguori     if (!drv)
3382178e08a5Saliguori         return -ENOMEDIUM;
33837cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
338445566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
33857cdb1f6dSMORITA Kazutaka     if (bs->file)
33867cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
33877cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3388178e08a5Saliguori }
3389178e08a5Saliguori 
33908b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
33918b9b0cc2SKevin Wolf {
3392bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
33938b9b0cc2SKevin Wolf         return;
33948b9b0cc2SKevin Wolf     }
33958b9b0cc2SKevin Wolf 
3396bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
339741c695c7SKevin Wolf }
33988b9b0cc2SKevin Wolf 
339941c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
340041c695c7SKevin Wolf                           const char *tag)
340141c695c7SKevin Wolf {
340241c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
340341c695c7SKevin Wolf         bs = bs->file;
340441c695c7SKevin Wolf     }
340541c695c7SKevin Wolf 
340641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
340741c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
340841c695c7SKevin Wolf     }
340941c695c7SKevin Wolf 
341041c695c7SKevin Wolf     return -ENOTSUP;
341141c695c7SKevin Wolf }
341241c695c7SKevin Wolf 
341341c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
341441c695c7SKevin Wolf {
341541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
341641c695c7SKevin Wolf         bs = bs->file;
341741c695c7SKevin Wolf     }
341841c695c7SKevin Wolf 
341941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
342041c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
342141c695c7SKevin Wolf     }
342241c695c7SKevin Wolf 
342341c695c7SKevin Wolf     return -ENOTSUP;
342441c695c7SKevin Wolf }
342541c695c7SKevin Wolf 
342641c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
342741c695c7SKevin Wolf {
342841c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
342941c695c7SKevin Wolf         bs = bs->file;
343041c695c7SKevin Wolf     }
343141c695c7SKevin Wolf 
343241c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
343341c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
343441c695c7SKevin Wolf     }
343541c695c7SKevin Wolf 
343641c695c7SKevin Wolf     return false;
34378b9b0cc2SKevin Wolf }
34388b9b0cc2SKevin Wolf 
3439199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3440199630b6SBlue Swirl {
3441199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3442199630b6SBlue Swirl }
3443199630b6SBlue Swirl 
3444b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3445b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3446b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3447b1b1d783SJeff Cody  * the CWD rather than the chain. */
3448e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3449e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3450e8a6bb9cSMarcelo Tosatti {
3451b1b1d783SJeff Cody     char *filename_full = NULL;
3452b1b1d783SJeff Cody     char *backing_file_full = NULL;
3453b1b1d783SJeff Cody     char *filename_tmp = NULL;
3454b1b1d783SJeff Cody     int is_protocol = 0;
3455b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3456b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3457b1b1d783SJeff Cody 
3458b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3459e8a6bb9cSMarcelo Tosatti         return NULL;
3460e8a6bb9cSMarcelo Tosatti     }
3461e8a6bb9cSMarcelo Tosatti 
3462b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3463b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3464b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3465b1b1d783SJeff Cody 
3466b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3467b1b1d783SJeff Cody 
3468b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3469b1b1d783SJeff Cody 
3470b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3471b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3472b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3473b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3474b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3475b1b1d783SJeff Cody                 break;
3476b1b1d783SJeff Cody             }
3477e8a6bb9cSMarcelo Tosatti         } else {
3478b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3479b1b1d783SJeff Cody              * image's filename path */
3480b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3481b1b1d783SJeff Cody                          backing_file);
3482b1b1d783SJeff Cody 
3483b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3484b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3485b1b1d783SJeff Cody                 continue;
3486b1b1d783SJeff Cody             }
3487b1b1d783SJeff Cody 
3488b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3489b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3490b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3491b1b1d783SJeff Cody                          curr_bs->backing_file);
3492b1b1d783SJeff Cody 
3493b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3494b1b1d783SJeff Cody                 continue;
3495b1b1d783SJeff Cody             }
3496b1b1d783SJeff Cody 
3497b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3498b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3499b1b1d783SJeff Cody                 break;
3500b1b1d783SJeff Cody             }
3501e8a6bb9cSMarcelo Tosatti         }
3502e8a6bb9cSMarcelo Tosatti     }
3503e8a6bb9cSMarcelo Tosatti 
3504b1b1d783SJeff Cody     g_free(filename_full);
3505b1b1d783SJeff Cody     g_free(backing_file_full);
3506b1b1d783SJeff Cody     g_free(filename_tmp);
3507b1b1d783SJeff Cody     return retval;
3508e8a6bb9cSMarcelo Tosatti }
3509e8a6bb9cSMarcelo Tosatti 
3510f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3511f198fd1cSBenoît Canet {
3512f198fd1cSBenoît Canet     if (!bs->drv) {
3513f198fd1cSBenoît Canet         return 0;
3514f198fd1cSBenoît Canet     }
3515f198fd1cSBenoît Canet 
3516f198fd1cSBenoît Canet     if (!bs->backing_hd) {
3517f198fd1cSBenoît Canet         return 0;
3518f198fd1cSBenoît Canet     }
3519f198fd1cSBenoît Canet 
3520f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3521f198fd1cSBenoît Canet }
3522f198fd1cSBenoît Canet 
352379fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
352479fac568SJeff Cody {
352579fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
352679fac568SJeff Cody 
352779fac568SJeff Cody     if (!bs) {
352879fac568SJeff Cody         return NULL;
352979fac568SJeff Cody     }
353079fac568SJeff Cody 
353179fac568SJeff Cody     curr_bs = bs;
353279fac568SJeff Cody 
353379fac568SJeff Cody     while (curr_bs->backing_hd) {
353479fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
353579fac568SJeff Cody     }
353679fac568SJeff Cody     return curr_bs;
353779fac568SJeff Cody }
353879fac568SJeff Cody 
3539ea2384d3Sbellard /**************************************************************/
354083f64091Sbellard /* async I/Os */
3541ea2384d3Sbellard 
35423b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3543f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
354483f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
3545ea2384d3Sbellard {
3546bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3547bbf0a440SStefan Hajnoczi 
3548b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
35498c5873d6SStefan Hajnoczi                                  cb, opaque, false);
355083f64091Sbellard }
355183f64091Sbellard 
3552f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3553f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
355483f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
35557674e7bfSbellard {
3556bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3557bbf0a440SStefan Hajnoczi 
35581a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
35598c5873d6SStefan Hajnoczi                                  cb, opaque, true);
356083f64091Sbellard }
356183f64091Sbellard 
356240b4f539SKevin Wolf 
356340b4f539SKevin Wolf typedef struct MultiwriteCB {
356440b4f539SKevin Wolf     int error;
356540b4f539SKevin Wolf     int num_requests;
356640b4f539SKevin Wolf     int num_callbacks;
356740b4f539SKevin Wolf     struct {
356840b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
356940b4f539SKevin Wolf         void *opaque;
357040b4f539SKevin Wolf         QEMUIOVector *free_qiov;
357140b4f539SKevin Wolf     } callbacks[];
357240b4f539SKevin Wolf } MultiwriteCB;
357340b4f539SKevin Wolf 
357440b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
357540b4f539SKevin Wolf {
357640b4f539SKevin Wolf     int i;
357740b4f539SKevin Wolf 
357840b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
357940b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
35801e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
35811e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
35821e1ea48dSStefan Hajnoczi         }
35837267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
358440b4f539SKevin Wolf     }
358540b4f539SKevin Wolf }
358640b4f539SKevin Wolf 
358740b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
358840b4f539SKevin Wolf {
358940b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
359040b4f539SKevin Wolf 
35916d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
35926d519a5fSStefan Hajnoczi 
3593cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
359440b4f539SKevin Wolf         mcb->error = ret;
359540b4f539SKevin Wolf     }
359640b4f539SKevin Wolf 
359740b4f539SKevin Wolf     mcb->num_requests--;
359840b4f539SKevin Wolf     if (mcb->num_requests == 0) {
359940b4f539SKevin Wolf         multiwrite_user_cb(mcb);
36007267c094SAnthony Liguori         g_free(mcb);
360140b4f539SKevin Wolf     }
360240b4f539SKevin Wolf }
360340b4f539SKevin Wolf 
360440b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
360540b4f539SKevin Wolf {
360677be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
360777be4366SChristoph Hellwig 
360877be4366SChristoph Hellwig     /*
360977be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
361077be4366SChristoph Hellwig      * here as that could overflow the return value.
361177be4366SChristoph Hellwig      */
361277be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
361377be4366SChristoph Hellwig         return 1;
361477be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
361577be4366SChristoph Hellwig         return -1;
361677be4366SChristoph Hellwig     } else {
361777be4366SChristoph Hellwig         return 0;
361877be4366SChristoph Hellwig     }
361940b4f539SKevin Wolf }
362040b4f539SKevin Wolf 
362140b4f539SKevin Wolf /*
362240b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
362340b4f539SKevin Wolf  * requests that remain after merging.
362440b4f539SKevin Wolf  */
362540b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
362640b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
362740b4f539SKevin Wolf {
362840b4f539SKevin Wolf     int i, outidx;
362940b4f539SKevin Wolf 
363040b4f539SKevin Wolf     // Sort requests by start sector
363140b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
363240b4f539SKevin Wolf 
363340b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
363440b4f539SKevin Wolf     // filling up gaps with zero sectors.
363540b4f539SKevin Wolf     outidx = 0;
363640b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
363740b4f539SKevin Wolf         int merge = 0;
363840b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
363940b4f539SKevin Wolf 
3640b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
364140b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
364240b4f539SKevin Wolf             merge = 1;
364340b4f539SKevin Wolf         }
364440b4f539SKevin Wolf 
3645e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3646e2a305fbSChristoph Hellwig             merge = 0;
3647e2a305fbSChristoph Hellwig         }
3648e2a305fbSChristoph Hellwig 
364940b4f539SKevin Wolf         if (merge) {
365040b4f539SKevin Wolf             size_t size;
36517267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
365240b4f539SKevin Wolf             qemu_iovec_init(qiov,
365340b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
365440b4f539SKevin Wolf 
365540b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
365640b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
365740b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
36581b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
365940b4f539SKevin Wolf 
3660b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3661b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
366240b4f539SKevin Wolf 
366340b4f539SKevin Wolf             // Add the second request
36641b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
366540b4f539SKevin Wolf 
3666cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
366740b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
366840b4f539SKevin Wolf 
366940b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
367040b4f539SKevin Wolf         } else {
367140b4f539SKevin Wolf             outidx++;
367240b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
367340b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
367440b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
367540b4f539SKevin Wolf         }
367640b4f539SKevin Wolf     }
367740b4f539SKevin Wolf 
367840b4f539SKevin Wolf     return outidx + 1;
367940b4f539SKevin Wolf }
368040b4f539SKevin Wolf 
368140b4f539SKevin Wolf /*
368240b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
368340b4f539SKevin Wolf  *
368440b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
368540b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
368640b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
368740b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
368840b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
368940b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
369040b4f539SKevin Wolf  *
369140b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
369240b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
369340b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
369440b4f539SKevin Wolf  */
369540b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
369640b4f539SKevin Wolf {
369740b4f539SKevin Wolf     MultiwriteCB *mcb;
369840b4f539SKevin Wolf     int i;
369940b4f539SKevin Wolf 
3700301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3701301db7c2SRyan Harper     if (bs->drv == NULL) {
3702301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3703301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3704301db7c2SRyan Harper         }
3705301db7c2SRyan Harper         return -1;
3706301db7c2SRyan Harper     }
3707301db7c2SRyan Harper 
370840b4f539SKevin Wolf     if (num_reqs == 0) {
370940b4f539SKevin Wolf         return 0;
371040b4f539SKevin Wolf     }
371140b4f539SKevin Wolf 
371240b4f539SKevin Wolf     // Create MultiwriteCB structure
37137267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
371440b4f539SKevin Wolf     mcb->num_requests = 0;
371540b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
371640b4f539SKevin Wolf 
371740b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
371840b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
371940b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
372040b4f539SKevin Wolf     }
372140b4f539SKevin Wolf 
372240b4f539SKevin Wolf     // Check for mergable requests
372340b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
372440b4f539SKevin Wolf 
37256d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
37266d519a5fSStefan Hajnoczi 
3727df9309fbSPaolo Bonzini     /* Run the aio requests. */
3728df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
372940b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3730ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
373140b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
373240b4f539SKevin Wolf     }
373340b4f539SKevin Wolf 
373440b4f539SKevin Wolf     return 0;
373540b4f539SKevin Wolf }
373640b4f539SKevin Wolf 
373783f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
373883f64091Sbellard {
3739d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
374083f64091Sbellard }
374183f64091Sbellard 
374283f64091Sbellard /**************************************************************/
374383f64091Sbellard /* async block device emulation */
374483f64091Sbellard 
3745c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
3746c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
3747c16b5a2cSChristoph Hellwig     QEMUBH *bh;
3748c16b5a2cSChristoph Hellwig     int ret;
3749c16b5a2cSChristoph Hellwig     /* vector translation state */
3750c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
3751c16b5a2cSChristoph Hellwig     uint8_t *bounce;
3752c16b5a2cSChristoph Hellwig     int is_write;
3753c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
3754c16b5a2cSChristoph Hellwig 
3755c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3756c16b5a2cSChristoph Hellwig {
3757b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
3758b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
37596a7ad299SDor Laor     qemu_bh_delete(acb->bh);
376036afc451SAvi Kivity     acb->bh = NULL;
3761c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
3762c16b5a2cSChristoph Hellwig }
3763c16b5a2cSChristoph Hellwig 
3764d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
3765c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
3766c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
3767c16b5a2cSChristoph Hellwig };
3768c16b5a2cSChristoph Hellwig 
376983f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
3770beac80cdSbellard {
3771ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
3772f141eafeSaliguori 
3773f141eafeSaliguori     if (!acb->is_write)
377403396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
3775ceb42de8Saliguori     qemu_vfree(acb->bounce);
3776ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
37776a7ad299SDor Laor     qemu_bh_delete(acb->bh);
377836afc451SAvi Kivity     acb->bh = NULL;
3779ce1a14dcSpbrook     qemu_aio_release(acb);
3780beac80cdSbellard }
3781beac80cdSbellard 
3782f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3783f141eafeSaliguori                                             int64_t sector_num,
3784f141eafeSaliguori                                             QEMUIOVector *qiov,
3785f141eafeSaliguori                                             int nb_sectors,
3786f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
3787f141eafeSaliguori                                             void *opaque,
3788f141eafeSaliguori                                             int is_write)
3789f141eafeSaliguori 
3790ea2384d3Sbellard {
3791ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
379283f64091Sbellard 
3793d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
3794f141eafeSaliguori     acb->is_write = is_write;
3795f141eafeSaliguori     acb->qiov = qiov;
3796e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
3797ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3798f141eafeSaliguori 
3799f141eafeSaliguori     if (is_write) {
3800d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
38011ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3802f141eafeSaliguori     } else {
38031ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3804f141eafeSaliguori     }
3805f141eafeSaliguori 
3806ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
3807f141eafeSaliguori 
3808ce1a14dcSpbrook     return &acb->common;
38097a6cba61Spbrook }
38107a6cba61Spbrook 
3811f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3812f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3813ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
381483f64091Sbellard {
3815f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
381683f64091Sbellard }
381783f64091Sbellard 
3818f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3819f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3820f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
3821f141eafeSaliguori {
3822f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3823f141eafeSaliguori }
3824f141eafeSaliguori 
382568485420SKevin Wolf 
382668485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
382768485420SKevin Wolf     BlockDriverAIOCB common;
382868485420SKevin Wolf     BlockRequest req;
382968485420SKevin Wolf     bool is_write;
3830d318aea9SKevin Wolf     bool *done;
383168485420SKevin Wolf     QEMUBH* bh;
383268485420SKevin Wolf } BlockDriverAIOCBCoroutine;
383368485420SKevin Wolf 
383468485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
383568485420SKevin Wolf {
3836d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
3837d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
3838d318aea9SKevin Wolf     bool done = false;
3839d318aea9SKevin Wolf 
3840d318aea9SKevin Wolf     acb->done = &done;
3841d318aea9SKevin Wolf     while (!done) {
3842d318aea9SKevin Wolf         qemu_aio_wait();
3843d318aea9SKevin Wolf     }
384468485420SKevin Wolf }
384568485420SKevin Wolf 
3846d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
384768485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
384868485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
384968485420SKevin Wolf };
385068485420SKevin Wolf 
385135246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
385268485420SKevin Wolf {
385368485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
385468485420SKevin Wolf 
385568485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
3856d318aea9SKevin Wolf 
3857d318aea9SKevin Wolf     if (acb->done) {
3858d318aea9SKevin Wolf         *acb->done = true;
3859d318aea9SKevin Wolf     }
3860d318aea9SKevin Wolf 
386168485420SKevin Wolf     qemu_bh_delete(acb->bh);
386268485420SKevin Wolf     qemu_aio_release(acb);
386368485420SKevin Wolf }
386468485420SKevin Wolf 
3865b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3866b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
3867b2a61371SStefan Hajnoczi {
3868b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
3869b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
3870b2a61371SStefan Hajnoczi 
3871b2a61371SStefan Hajnoczi     if (!acb->is_write) {
3872b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
3873470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3874b2a61371SStefan Hajnoczi     } else {
3875b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
3876f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3877b2a61371SStefan Hajnoczi     }
3878b2a61371SStefan Hajnoczi 
387935246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3880b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
3881b2a61371SStefan Hajnoczi }
3882b2a61371SStefan Hajnoczi 
388368485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
388468485420SKevin Wolf                                                int64_t sector_num,
388568485420SKevin Wolf                                                QEMUIOVector *qiov,
388668485420SKevin Wolf                                                int nb_sectors,
388768485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
388868485420SKevin Wolf                                                void *opaque,
38898c5873d6SStefan Hajnoczi                                                bool is_write)
389068485420SKevin Wolf {
389168485420SKevin Wolf     Coroutine *co;
389268485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
389368485420SKevin Wolf 
3894d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
389568485420SKevin Wolf     acb->req.sector = sector_num;
389668485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
389768485420SKevin Wolf     acb->req.qiov = qiov;
389868485420SKevin Wolf     acb->is_write = is_write;
3899d318aea9SKevin Wolf     acb->done = NULL;
390068485420SKevin Wolf 
39018c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
390268485420SKevin Wolf     qemu_coroutine_enter(co, acb);
390368485420SKevin Wolf 
390468485420SKevin Wolf     return &acb->common;
390568485420SKevin Wolf }
390668485420SKevin Wolf 
390707f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
3908b2e12bc6SChristoph Hellwig {
390907f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
391007f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
3911b2e12bc6SChristoph Hellwig 
391207f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
391307f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3914b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
3915b2e12bc6SChristoph Hellwig }
3916b2e12bc6SChristoph Hellwig 
391707f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
3918016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
3919016f5cf6SAlexander Graf {
392007f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
3921016f5cf6SAlexander Graf 
392207f07615SPaolo Bonzini     Coroutine *co;
392307f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
3924016f5cf6SAlexander Graf 
3925d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
3926d318aea9SKevin Wolf     acb->done = NULL;
3927d318aea9SKevin Wolf 
392807f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
392907f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
3930016f5cf6SAlexander Graf 
3931016f5cf6SAlexander Graf     return &acb->common;
3932016f5cf6SAlexander Graf }
3933016f5cf6SAlexander Graf 
39344265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
39354265d620SPaolo Bonzini {
39364265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
39374265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
39384265d620SPaolo Bonzini 
39394265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
39404265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
39414265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
39424265d620SPaolo Bonzini }
39434265d620SPaolo Bonzini 
39444265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
39454265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
39464265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
39474265d620SPaolo Bonzini {
39484265d620SPaolo Bonzini     Coroutine *co;
39494265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
39504265d620SPaolo Bonzini 
39514265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
39524265d620SPaolo Bonzini 
3953d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
39544265d620SPaolo Bonzini     acb->req.sector = sector_num;
39554265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
3956d318aea9SKevin Wolf     acb->done = NULL;
39574265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
39584265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
39594265d620SPaolo Bonzini 
39604265d620SPaolo Bonzini     return &acb->common;
39614265d620SPaolo Bonzini }
39624265d620SPaolo Bonzini 
3963ea2384d3Sbellard void bdrv_init(void)
3964ea2384d3Sbellard {
39655efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3966ea2384d3Sbellard }
3967ce1a14dcSpbrook 
3968eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3969eb852011SMarkus Armbruster {
3970eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3971eb852011SMarkus Armbruster     bdrv_init();
3972eb852011SMarkus Armbruster }
3973eb852011SMarkus Armbruster 
3974d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
39756bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
39766bbff9a0Saliguori {
3977ce1a14dcSpbrook     BlockDriverAIOCB *acb;
3978ce1a14dcSpbrook 
3979d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
3980d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
3981ce1a14dcSpbrook     acb->bs = bs;
3982ce1a14dcSpbrook     acb->cb = cb;
3983ce1a14dcSpbrook     acb->opaque = opaque;
3984ce1a14dcSpbrook     return acb;
3985ce1a14dcSpbrook }
3986ce1a14dcSpbrook 
3987ce1a14dcSpbrook void qemu_aio_release(void *p)
3988ce1a14dcSpbrook {
3989d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
3990d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
3991ce1a14dcSpbrook }
399219cb3738Sbellard 
399319cb3738Sbellard /**************************************************************/
3994f9f05dc5SKevin Wolf /* Coroutine block device emulation */
3995f9f05dc5SKevin Wolf 
3996f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
3997f9f05dc5SKevin Wolf     Coroutine *coroutine;
3998f9f05dc5SKevin Wolf     int ret;
3999f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4000f9f05dc5SKevin Wolf 
4001f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4002f9f05dc5SKevin Wolf {
4003f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4004f9f05dc5SKevin Wolf 
4005f9f05dc5SKevin Wolf     co->ret = ret;
4006f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4007f9f05dc5SKevin Wolf }
4008f9f05dc5SKevin Wolf 
4009f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4010f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4011f9f05dc5SKevin Wolf                                       bool is_write)
4012f9f05dc5SKevin Wolf {
4013f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4014f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4015f9f05dc5SKevin Wolf     };
4016f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4017f9f05dc5SKevin Wolf 
4018f9f05dc5SKevin Wolf     if (is_write) {
4019a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4020f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4021f9f05dc5SKevin Wolf     } else {
4022a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4023f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4024f9f05dc5SKevin Wolf     }
4025f9f05dc5SKevin Wolf 
402659370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4027f9f05dc5SKevin Wolf     if (!acb) {
4028f9f05dc5SKevin Wolf         return -EIO;
4029f9f05dc5SKevin Wolf     }
4030f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4031f9f05dc5SKevin Wolf 
4032f9f05dc5SKevin Wolf     return co.ret;
4033f9f05dc5SKevin Wolf }
4034f9f05dc5SKevin Wolf 
4035f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4036f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4037f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4038f9f05dc5SKevin Wolf {
4039f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4040f9f05dc5SKevin Wolf }
4041f9f05dc5SKevin Wolf 
4042f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4043f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4044f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4045f9f05dc5SKevin Wolf {
4046f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4047f9f05dc5SKevin Wolf }
4048f9f05dc5SKevin Wolf 
404907f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4050e7a8a783SKevin Wolf {
405107f07615SPaolo Bonzini     RwCo *rwco = opaque;
405207f07615SPaolo Bonzini 
405307f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
405407f07615SPaolo Bonzini }
405507f07615SPaolo Bonzini 
405607f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
405707f07615SPaolo Bonzini {
4058eb489bb1SKevin Wolf     int ret;
4059eb489bb1SKevin Wolf 
406029cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
406107f07615SPaolo Bonzini         return 0;
4062eb489bb1SKevin Wolf     }
4063eb489bb1SKevin Wolf 
4064ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4065bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4066eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4067eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4068eb489bb1SKevin Wolf         if (ret < 0) {
4069eb489bb1SKevin Wolf             return ret;
4070eb489bb1SKevin Wolf         }
4071eb489bb1SKevin Wolf     }
4072eb489bb1SKevin Wolf 
4073ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4074ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4075d4c82329SKevin Wolf         goto flush_parent;
4076ca716364SKevin Wolf     }
4077ca716364SKevin Wolf 
4078bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4079eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
408029cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
408107f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
408207f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4083e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4084e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4085e7a8a783SKevin Wolf         };
4086e7a8a783SKevin Wolf 
408707f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
408807f07615SPaolo Bonzini         if (acb == NULL) {
408929cdb251SPaolo Bonzini             ret = -EIO;
409007f07615SPaolo Bonzini         } else {
4091e7a8a783SKevin Wolf             qemu_coroutine_yield();
409229cdb251SPaolo Bonzini             ret = co.ret;
4093e7a8a783SKevin Wolf         }
409407f07615SPaolo Bonzini     } else {
409507f07615SPaolo Bonzini         /*
409607f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
409707f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
409807f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
409907f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
410007f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
410107f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
410207f07615SPaolo Bonzini          * mode.
410307f07615SPaolo Bonzini          *
410407f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
410507f07615SPaolo Bonzini          */
410629cdb251SPaolo Bonzini         ret = 0;
410707f07615SPaolo Bonzini     }
410829cdb251SPaolo Bonzini     if (ret < 0) {
410929cdb251SPaolo Bonzini         return ret;
411029cdb251SPaolo Bonzini     }
411129cdb251SPaolo Bonzini 
411229cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
411329cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
411429cdb251SPaolo Bonzini      */
4115d4c82329SKevin Wolf flush_parent:
411629cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
411707f07615SPaolo Bonzini }
411807f07615SPaolo Bonzini 
41190f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
41200f15423cSAnthony Liguori {
41210f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
41220f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
41230f15423cSAnthony Liguori     }
41240f15423cSAnthony Liguori }
41250f15423cSAnthony Liguori 
41260f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
41270f15423cSAnthony Liguori {
41280f15423cSAnthony Liguori     BlockDriverState *bs;
41290f15423cSAnthony Liguori 
41300f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
41310f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
41320f15423cSAnthony Liguori     }
41330f15423cSAnthony Liguori }
41340f15423cSAnthony Liguori 
413507789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
413607789269SBenoît Canet {
413707789269SBenoît Canet     BlockDriverState *bs;
413807789269SBenoît Canet 
413907789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
414007789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
414107789269SBenoît Canet     }
414207789269SBenoît Canet }
414307789269SBenoît Canet 
414407f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
414507f07615SPaolo Bonzini {
414607f07615SPaolo Bonzini     Coroutine *co;
414707f07615SPaolo Bonzini     RwCo rwco = {
414807f07615SPaolo Bonzini         .bs = bs,
414907f07615SPaolo Bonzini         .ret = NOT_DONE,
415007f07615SPaolo Bonzini     };
415107f07615SPaolo Bonzini 
415207f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
415307f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
415407f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
415507f07615SPaolo Bonzini     } else {
415607f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
415707f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
415807f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
415907f07615SPaolo Bonzini             qemu_aio_wait();
416007f07615SPaolo Bonzini         }
416107f07615SPaolo Bonzini     }
416207f07615SPaolo Bonzini 
416307f07615SPaolo Bonzini     return rwco.ret;
416407f07615SPaolo Bonzini }
4165e7a8a783SKevin Wolf 
41664265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
41674265d620SPaolo Bonzini {
41684265d620SPaolo Bonzini     RwCo *rwco = opaque;
41694265d620SPaolo Bonzini 
41704265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
41714265d620SPaolo Bonzini }
41724265d620SPaolo Bonzini 
41734265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
41744265d620SPaolo Bonzini                                  int nb_sectors)
41754265d620SPaolo Bonzini {
41764265d620SPaolo Bonzini     if (!bs->drv) {
41774265d620SPaolo Bonzini         return -ENOMEDIUM;
41784265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
41794265d620SPaolo Bonzini         return -EIO;
41804265d620SPaolo Bonzini     } else if (bs->read_only) {
41814265d620SPaolo Bonzini         return -EROFS;
4182df702c9bSPaolo Bonzini     }
4183df702c9bSPaolo Bonzini 
4184df702c9bSPaolo Bonzini     if (bs->dirty_bitmap) {
41858f0720ecSPaolo Bonzini         bdrv_reset_dirty(bs, sector_num, nb_sectors);
4186df702c9bSPaolo Bonzini     }
4187df702c9bSPaolo Bonzini 
41889e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
41899e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
41909e8f1835SPaolo Bonzini         return 0;
41919e8f1835SPaolo Bonzini     }
41929e8f1835SPaolo Bonzini 
4193df702c9bSPaolo Bonzini     if (bs->drv->bdrv_co_discard) {
41944265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
41954265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
41964265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
41974265d620SPaolo Bonzini         CoroutineIOCompletion co = {
41984265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
41994265d620SPaolo Bonzini         };
42004265d620SPaolo Bonzini 
42014265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
42024265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
42034265d620SPaolo Bonzini         if (acb == NULL) {
42044265d620SPaolo Bonzini             return -EIO;
42054265d620SPaolo Bonzini         } else {
42064265d620SPaolo Bonzini             qemu_coroutine_yield();
42074265d620SPaolo Bonzini             return co.ret;
42084265d620SPaolo Bonzini         }
42094265d620SPaolo Bonzini     } else {
42104265d620SPaolo Bonzini         return 0;
42114265d620SPaolo Bonzini     }
42124265d620SPaolo Bonzini }
42134265d620SPaolo Bonzini 
42144265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
42154265d620SPaolo Bonzini {
42164265d620SPaolo Bonzini     Coroutine *co;
42174265d620SPaolo Bonzini     RwCo rwco = {
42184265d620SPaolo Bonzini         .bs = bs,
42194265d620SPaolo Bonzini         .sector_num = sector_num,
42204265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
42214265d620SPaolo Bonzini         .ret = NOT_DONE,
42224265d620SPaolo Bonzini     };
42234265d620SPaolo Bonzini 
42244265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
42254265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
42264265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
42274265d620SPaolo Bonzini     } else {
42284265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
42294265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
42304265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
42314265d620SPaolo Bonzini             qemu_aio_wait();
42324265d620SPaolo Bonzini         }
42334265d620SPaolo Bonzini     }
42344265d620SPaolo Bonzini 
42354265d620SPaolo Bonzini     return rwco.ret;
42364265d620SPaolo Bonzini }
42374265d620SPaolo Bonzini 
4238f9f05dc5SKevin Wolf /**************************************************************/
423919cb3738Sbellard /* removable device support */
424019cb3738Sbellard 
424119cb3738Sbellard /**
424219cb3738Sbellard  * Return TRUE if the media is present
424319cb3738Sbellard  */
424419cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
424519cb3738Sbellard {
424619cb3738Sbellard     BlockDriver *drv = bs->drv;
4247a1aff5bfSMarkus Armbruster 
424819cb3738Sbellard     if (!drv)
424919cb3738Sbellard         return 0;
425019cb3738Sbellard     if (!drv->bdrv_is_inserted)
4251a1aff5bfSMarkus Armbruster         return 1;
4252a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
425319cb3738Sbellard }
425419cb3738Sbellard 
425519cb3738Sbellard /**
42568e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
42578e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
425819cb3738Sbellard  */
425919cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
426019cb3738Sbellard {
426119cb3738Sbellard     BlockDriver *drv = bs->drv;
426219cb3738Sbellard 
42638e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
42648e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
42658e49ca46SMarkus Armbruster     }
42668e49ca46SMarkus Armbruster     return -ENOTSUP;
426719cb3738Sbellard }
426819cb3738Sbellard 
426919cb3738Sbellard /**
427019cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
427119cb3738Sbellard  */
4272f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
427319cb3738Sbellard {
427419cb3738Sbellard     BlockDriver *drv = bs->drv;
427519cb3738Sbellard 
4276822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4277822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
427819cb3738Sbellard     }
42796f382ed2SLuiz Capitulino 
42806f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
42816f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
42826f382ed2SLuiz Capitulino     }
428319cb3738Sbellard }
428419cb3738Sbellard 
428519cb3738Sbellard /**
428619cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
428719cb3738Sbellard  * to eject it manually).
428819cb3738Sbellard  */
4289025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
429019cb3738Sbellard {
429119cb3738Sbellard     BlockDriver *drv = bs->drv;
429219cb3738Sbellard 
4293025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4294b8c6d095SStefan Hajnoczi 
4295025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4296025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
429719cb3738Sbellard     }
429819cb3738Sbellard }
4299985a03b0Sths 
4300985a03b0Sths /* needed for generic scsi interface */
4301985a03b0Sths 
4302985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4303985a03b0Sths {
4304985a03b0Sths     BlockDriver *drv = bs->drv;
4305985a03b0Sths 
4306985a03b0Sths     if (drv && drv->bdrv_ioctl)
4307985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4308985a03b0Sths     return -ENOTSUP;
4309985a03b0Sths }
43107d780669Saliguori 
4311221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4312221f715dSaliguori         unsigned long int req, void *buf,
43137d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
43147d780669Saliguori {
4315221f715dSaliguori     BlockDriver *drv = bs->drv;
43167d780669Saliguori 
4317221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4318221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4319221f715dSaliguori     return NULL;
43207d780669Saliguori }
4321e268ca52Saliguori 
43227b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
43237b6f9300SMarkus Armbruster {
43247b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
43257b6f9300SMarkus Armbruster }
43267cd1e32aSlirans@il.ibm.com 
4327e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
4328e268ca52Saliguori {
4329e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4330e268ca52Saliguori }
43317cd1e32aSlirans@il.ibm.com 
4332c53b1c51SStefan Hajnoczi /*
4333c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
4334c53b1c51SStefan Hajnoczi  */
4335c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4336c53b1c51SStefan Hajnoczi {
4337c53b1c51SStefan Hajnoczi     int i;
4338c53b1c51SStefan Hajnoczi 
4339c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
4340c53b1c51SStefan Hajnoczi         if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4341c53b1c51SStefan Hajnoczi             return false;
4342c53b1c51SStefan Hajnoczi         }
4343c53b1c51SStefan Hajnoczi     }
4344c53b1c51SStefan Hajnoczi 
4345c53b1c51SStefan Hajnoczi     return true;
4346c53b1c51SStefan Hajnoczi }
4347c53b1c51SStefan Hajnoczi 
434850717e94SPaolo Bonzini void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
43497cd1e32aSlirans@il.ibm.com {
43507cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
4351a55eb92cSJan Kiszka 
435250717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
435350717e94SPaolo Bonzini 
435450717e94SPaolo Bonzini     if (granularity) {
435550717e94SPaolo Bonzini         granularity >>= BDRV_SECTOR_BITS;
435650717e94SPaolo Bonzini         assert(!bs->dirty_bitmap);
43578f0720ecSPaolo Bonzini         bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
435850717e94SPaolo Bonzini         bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
43597cd1e32aSlirans@il.ibm.com     } else {
4360c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
43618f0720ecSPaolo Bonzini             hbitmap_free(bs->dirty_bitmap);
4362c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
43637cd1e32aSlirans@il.ibm.com         }
43647cd1e32aSlirans@il.ibm.com     }
43657cd1e32aSlirans@il.ibm.com }
43667cd1e32aSlirans@il.ibm.com 
43677cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
43687cd1e32aSlirans@il.ibm.com {
43698f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
43708f0720ecSPaolo Bonzini         return hbitmap_get(bs->dirty_bitmap, sector);
43717cd1e32aSlirans@il.ibm.com     } else {
43727cd1e32aSlirans@il.ibm.com         return 0;
43737cd1e32aSlirans@il.ibm.com     }
43747cd1e32aSlirans@il.ibm.com }
43757cd1e32aSlirans@il.ibm.com 
43768f0720ecSPaolo Bonzini void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
43771755da16SPaolo Bonzini {
43788f0720ecSPaolo Bonzini     hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
43791755da16SPaolo Bonzini }
43801755da16SPaolo Bonzini 
43811755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
43821755da16SPaolo Bonzini                     int nr_sectors)
43831755da16SPaolo Bonzini {
43848f0720ecSPaolo Bonzini     hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
43851755da16SPaolo Bonzini }
43861755da16SPaolo Bonzini 
43877cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
43887cd1e32aSlirans@il.ibm.com                       int nr_sectors)
43897cd1e32aSlirans@il.ibm.com {
43908f0720ecSPaolo Bonzini     hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
43917cd1e32aSlirans@il.ibm.com }
4392aaa0eb75SLiran Schour 
4393aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4394aaa0eb75SLiran Schour {
43958f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
4396acc906c6SPaolo Bonzini         return hbitmap_count(bs->dirty_bitmap);
43978f0720ecSPaolo Bonzini     } else {
43988f0720ecSPaolo Bonzini         return 0;
43998f0720ecSPaolo Bonzini     }
4400aaa0eb75SLiran Schour }
4401f88e1a42SJes Sorensen 
44029fcb0251SFam Zheng /* Get a reference to bs */
44039fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
44049fcb0251SFam Zheng {
44059fcb0251SFam Zheng     bs->refcnt++;
44069fcb0251SFam Zheng }
44079fcb0251SFam Zheng 
44089fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
44099fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
44109fcb0251SFam Zheng  * deleted. */
44119fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
44129fcb0251SFam Zheng {
44139fcb0251SFam Zheng     assert(bs->refcnt > 0);
44149fcb0251SFam Zheng     if (--bs->refcnt == 0) {
44159fcb0251SFam Zheng         bdrv_delete(bs);
44169fcb0251SFam Zheng     }
44179fcb0251SFam Zheng }
44189fcb0251SFam Zheng 
4419db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4420db593f25SMarcelo Tosatti {
4421db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
4422db593f25SMarcelo Tosatti     bs->in_use = in_use;
4423db593f25SMarcelo Tosatti }
4424db593f25SMarcelo Tosatti 
4425db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
4426db593f25SMarcelo Tosatti {
4427db593f25SMarcelo Tosatti     return bs->in_use;
4428db593f25SMarcelo Tosatti }
4429db593f25SMarcelo Tosatti 
443028a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
443128a7282aSLuiz Capitulino {
4432d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
443358e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
443428a7282aSLuiz Capitulino }
443528a7282aSLuiz Capitulino 
443628a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
443728a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
443828a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
443928a7282aSLuiz Capitulino {
4440d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
444192aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
444292aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
444392aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
444428a7282aSLuiz Capitulino }
444528a7282aSLuiz Capitulino 
444628a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
444728a7282aSLuiz Capitulino {
4448d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
444928a7282aSLuiz Capitulino }
445028a7282aSLuiz Capitulino 
445128a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
445228a7282aSLuiz Capitulino {
445328a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
445458e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
44553bd293c3SPaolo Bonzini         if (bs->job) {
44563bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
44573bd293c3SPaolo Bonzini         }
445828a7282aSLuiz Capitulino     }
445928a7282aSLuiz Capitulino }
446028a7282aSLuiz Capitulino 
446128a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
446228a7282aSLuiz Capitulino {
44633e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
44643e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
446558e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
446658e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
446728a7282aSLuiz Capitulino     }
446828a7282aSLuiz Capitulino }
446928a7282aSLuiz Capitulino 
4470a597e79cSChristoph Hellwig void
4471a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4472a597e79cSChristoph Hellwig         enum BlockAcctType type)
4473a597e79cSChristoph Hellwig {
4474a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4475a597e79cSChristoph Hellwig 
4476a597e79cSChristoph Hellwig     cookie->bytes = bytes;
4477c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
4478a597e79cSChristoph Hellwig     cookie->type = type;
4479a597e79cSChristoph Hellwig }
4480a597e79cSChristoph Hellwig 
4481a597e79cSChristoph Hellwig void
4482a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4483a597e79cSChristoph Hellwig {
4484a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
4485a597e79cSChristoph Hellwig 
4486a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
4487a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
4488c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4489a597e79cSChristoph Hellwig }
4490a597e79cSChristoph Hellwig 
4491d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
4492f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
4493f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
4494f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
4495f88e1a42SJes Sorensen {
4496f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
4497d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
4498f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
4499f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
450096df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
4501cc84d90fSMax Reitz     Error *local_err = NULL;
4502f88e1a42SJes Sorensen     int ret = 0;
4503f88e1a42SJes Sorensen 
4504f88e1a42SJes Sorensen     /* Find driver and parse its options */
4505f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
4506f88e1a42SJes Sorensen     if (!drv) {
450771c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
4508d92ada22SLuiz Capitulino         return;
4509f88e1a42SJes Sorensen     }
4510f88e1a42SJes Sorensen 
451198289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
4512f88e1a42SJes Sorensen     if (!proto_drv) {
451371c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
4514d92ada22SLuiz Capitulino         return;
4515f88e1a42SJes Sorensen     }
4516f88e1a42SJes Sorensen 
4517f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4518f88e1a42SJes Sorensen                                               drv->create_options);
4519f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4520f88e1a42SJes Sorensen                                               proto_drv->create_options);
4521f88e1a42SJes Sorensen 
4522f88e1a42SJes Sorensen     /* Create parameter list with default values */
4523f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
4524f88e1a42SJes Sorensen 
4525f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4526f88e1a42SJes Sorensen 
4527f88e1a42SJes Sorensen     /* Parse -o options */
4528f88e1a42SJes Sorensen     if (options) {
4529f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
4530f88e1a42SJes Sorensen         if (param == NULL) {
453171c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
4532f88e1a42SJes Sorensen             goto out;
4533f88e1a42SJes Sorensen         }
4534f88e1a42SJes Sorensen     }
4535f88e1a42SJes Sorensen 
4536f88e1a42SJes Sorensen     if (base_filename) {
4537f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4538f88e1a42SJes Sorensen                                  base_filename)) {
453971c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
454071c79813SLuiz Capitulino                        fmt);
4541f88e1a42SJes Sorensen             goto out;
4542f88e1a42SJes Sorensen         }
4543f88e1a42SJes Sorensen     }
4544f88e1a42SJes Sorensen 
4545f88e1a42SJes Sorensen     if (base_fmt) {
4546f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
454771c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
454871c79813SLuiz Capitulino                              "format '%s'", fmt);
4549f88e1a42SJes Sorensen             goto out;
4550f88e1a42SJes Sorensen         }
4551f88e1a42SJes Sorensen     }
4552f88e1a42SJes Sorensen 
4553792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4554792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4555792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
455671c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
455771c79813SLuiz Capitulino                              "same filename as the backing file");
4558792da93aSJes Sorensen             goto out;
4559792da93aSJes Sorensen         }
4560792da93aSJes Sorensen     }
4561792da93aSJes Sorensen 
4562f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4563f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
456496df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
456596df67d1SStefan Hajnoczi         if (!backing_drv) {
456671c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
456771c79813SLuiz Capitulino                        backing_fmt->value.s);
4568f88e1a42SJes Sorensen             goto out;
4569f88e1a42SJes Sorensen         }
4570f88e1a42SJes Sorensen     }
4571f88e1a42SJes Sorensen 
4572f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4573f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4574d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4575d220894eSKevin Wolf     if (size && size->value.n == -1) {
4576f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4577f88e1a42SJes Sorensen             uint64_t size;
4578f88e1a42SJes Sorensen             char buf[32];
457963090dacSPaolo Bonzini             int back_flags;
458063090dacSPaolo Bonzini 
458163090dacSPaolo Bonzini             /* backing files always opened read-only */
458263090dacSPaolo Bonzini             back_flags =
458363090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4584f88e1a42SJes Sorensen 
4585f88e1a42SJes Sorensen             bs = bdrv_new("");
4586f88e1a42SJes Sorensen 
4587de9c0cecSKevin Wolf             ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4588cc84d90fSMax Reitz                             backing_drv, &local_err);
4589f88e1a42SJes Sorensen             if (ret < 0) {
4590cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
4591cc84d90fSMax Reitz                                  backing_file->value.s,
4592cc84d90fSMax Reitz                                  error_get_pretty(local_err));
4593cc84d90fSMax Reitz                 error_free(local_err);
4594cc84d90fSMax Reitz                 local_err = NULL;
4595f88e1a42SJes Sorensen                 goto out;
4596f88e1a42SJes Sorensen             }
4597f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4598f88e1a42SJes Sorensen             size *= 512;
4599f88e1a42SJes Sorensen 
4600f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4601f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4602f88e1a42SJes Sorensen         } else {
460371c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
4604f88e1a42SJes Sorensen             goto out;
4605f88e1a42SJes Sorensen         }
4606f88e1a42SJes Sorensen     }
4607f88e1a42SJes Sorensen 
4608f382d43aSMiroslav Rezanina     if (!quiet) {
4609f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
4610f88e1a42SJes Sorensen         print_option_parameters(param);
4611f88e1a42SJes Sorensen         puts("");
4612f382d43aSMiroslav Rezanina     }
4613cc84d90fSMax Reitz     ret = bdrv_create(drv, filename, param, &local_err);
4614cc84d90fSMax Reitz     if (ret == -EFBIG) {
4615cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
4616cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
4617cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
4618f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
4619f3f4d2c0SKevin Wolf         if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
4620f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
4621f3f4d2c0SKevin Wolf         }
4622cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
4623cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
4624cc84d90fSMax Reitz         error_free(local_err);
4625cc84d90fSMax Reitz         local_err = NULL;
4626f88e1a42SJes Sorensen     }
4627f88e1a42SJes Sorensen 
4628f88e1a42SJes Sorensen out:
4629f88e1a42SJes Sorensen     free_option_parameters(create_options);
4630f88e1a42SJes Sorensen     free_option_parameters(param);
4631f88e1a42SJes Sorensen 
4632f88e1a42SJes Sorensen     if (bs) {
46334f6fd349SFam Zheng         bdrv_unref(bs);
4634f88e1a42SJes Sorensen     }
4635cc84d90fSMax Reitz     if (error_is_set(&local_err)) {
4636cc84d90fSMax Reitz         error_propagate(errp, local_err);
4637cc84d90fSMax Reitz     }
4638f88e1a42SJes Sorensen }
463985d126f3SStefan Hajnoczi 
464085d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
464185d126f3SStefan Hajnoczi {
464285d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
464385d126f3SStefan Hajnoczi     return qemu_get_aio_context();
464485d126f3SStefan Hajnoczi }
4645d616b224SStefan Hajnoczi 
4646d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
4647d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
4648d616b224SStefan Hajnoczi {
4649d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
4650d616b224SStefan Hajnoczi }
46516f176b48SMax Reitz 
46526f176b48SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
46536f176b48SMax Reitz {
46546f176b48SMax Reitz     if (bs->drv->bdrv_amend_options == NULL) {
46556f176b48SMax Reitz         return -ENOTSUP;
46566f176b48SMax Reitz     }
46576f176b48SMax Reitz     return bs->drv->bdrv_amend_options(bs, options);
46586f176b48SMax Reitz }
4659f6186f49SBenoît Canet 
4660f6186f49SBenoît Canet ExtSnapshotPerm bdrv_check_ext_snapshot(BlockDriverState *bs)
4661f6186f49SBenoît Canet {
4662f6186f49SBenoît Canet     if (bs->drv->bdrv_check_ext_snapshot) {
4663f6186f49SBenoît Canet         return bs->drv->bdrv_check_ext_snapshot(bs);
4664f6186f49SBenoît Canet     }
4665f6186f49SBenoît Canet 
4666f6186f49SBenoît Canet     if (bs->file && bs->file->drv && bs->file->drv->bdrv_check_ext_snapshot) {
4667f6186f49SBenoît Canet         return bs->file->drv->bdrv_check_ext_snapshot(bs);
4668f6186f49SBenoît Canet     }
4669f6186f49SBenoît Canet 
4670f6186f49SBenoît Canet     /* external snapshots are allowed by default */
4671f6186f49SBenoît Canet     return EXT_SNAPSHOT_ALLOWED;
4672f6186f49SBenoît Canet }
4673f6186f49SBenoît Canet 
4674f6186f49SBenoît Canet ExtSnapshotPerm bdrv_check_ext_snapshot_forbidden(BlockDriverState *bs)
4675f6186f49SBenoît Canet {
4676f6186f49SBenoît Canet     return EXT_SNAPSHOT_FORBIDDEN;
4677f6186f49SBenoît Canet }
4678