xref: /openbmc/qemu/block.c (revision 9fcb025146676ab376e6159b58f5a5ddb67bf03c)
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]);
335*9fcb0251SFam 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;
3975b7e1542SZhi Yong Wu } CreateCo;
3985b7e1542SZhi Yong Wu 
3995b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4005b7e1542SZhi Yong Wu {
4015b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4025b7e1542SZhi Yong Wu     assert(cco->drv);
4035b7e1542SZhi Yong Wu 
4045b7e1542SZhi Yong Wu     cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
4055b7e1542SZhi Yong Wu }
4065b7e1542SZhi Yong Wu 
4070e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
4080e7e1989SKevin Wolf     QEMUOptionParameter *options)
409ea2384d3Sbellard {
4105b7e1542SZhi Yong Wu     int ret;
4110e7e1989SKevin Wolf 
4125b7e1542SZhi Yong Wu     Coroutine *co;
4135b7e1542SZhi Yong Wu     CreateCo cco = {
4145b7e1542SZhi Yong Wu         .drv = drv,
4155b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
4165b7e1542SZhi Yong Wu         .options = options,
4175b7e1542SZhi Yong Wu         .ret = NOT_DONE,
4185b7e1542SZhi Yong Wu     };
4195b7e1542SZhi Yong Wu 
4205b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
42180168bffSLuiz Capitulino         ret = -ENOTSUP;
42280168bffSLuiz Capitulino         goto out;
4235b7e1542SZhi Yong Wu     }
4245b7e1542SZhi Yong Wu 
4255b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4265b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4275b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4285b7e1542SZhi Yong Wu     } else {
4295b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4305b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4315b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4325b7e1542SZhi Yong Wu             qemu_aio_wait();
4335b7e1542SZhi Yong Wu         }
4345b7e1542SZhi Yong Wu     }
4355b7e1542SZhi Yong Wu 
4365b7e1542SZhi Yong Wu     ret = cco.ret;
4375b7e1542SZhi Yong Wu 
43880168bffSLuiz Capitulino out:
43980168bffSLuiz Capitulino     g_free(cco.filename);
4405b7e1542SZhi Yong Wu     return ret;
441ea2384d3Sbellard }
442ea2384d3Sbellard 
44384a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
44484a12e66SChristoph Hellwig {
44584a12e66SChristoph Hellwig     BlockDriver *drv;
44684a12e66SChristoph Hellwig 
44798289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
44884a12e66SChristoph Hellwig     if (drv == NULL) {
44916905d71SStefan Hajnoczi         return -ENOENT;
45084a12e66SChristoph Hellwig     }
45184a12e66SChristoph Hellwig 
45284a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
45384a12e66SChristoph Hellwig }
45484a12e66SChristoph Hellwig 
455eba25057SJim Meyering /*
456eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
457eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
458eba25057SJim Meyering  */
459eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
460eba25057SJim Meyering {
461d5249393Sbellard #ifdef _WIN32
4623b9f94e1Sbellard     char temp_dir[MAX_PATH];
463eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
464eba25057SJim Meyering        have length MAX_PATH or greater.  */
465eba25057SJim Meyering     assert(size >= MAX_PATH);
466eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
467eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
468eba25057SJim Meyering             ? 0 : -GetLastError());
469d5249393Sbellard #else
470ea2384d3Sbellard     int fd;
4717ccfb2ebSblueswir1     const char *tmpdir;
4720badc1eeSaurel32     tmpdir = getenv("TMPDIR");
4730badc1eeSaurel32     if (!tmpdir)
4740badc1eeSaurel32         tmpdir = "/tmp";
475eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
476eba25057SJim Meyering         return -EOVERFLOW;
477ea2384d3Sbellard     }
478eba25057SJim Meyering     fd = mkstemp(filename);
479fe235a06SDunrong Huang     if (fd < 0) {
480fe235a06SDunrong Huang         return -errno;
481fe235a06SDunrong Huang     }
482fe235a06SDunrong Huang     if (close(fd) != 0) {
483fe235a06SDunrong Huang         unlink(filename);
484eba25057SJim Meyering         return -errno;
485eba25057SJim Meyering     }
486eba25057SJim Meyering     return 0;
487d5249393Sbellard #endif
488eba25057SJim Meyering }
489ea2384d3Sbellard 
490f3a5d3f8SChristoph Hellwig /*
491f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
492f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
493f3a5d3f8SChristoph Hellwig  */
494f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
495f3a5d3f8SChristoph Hellwig {
496508c7cb3SChristoph Hellwig     int score_max = 0, score;
497508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
498f3a5d3f8SChristoph Hellwig 
4998a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
500508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
501508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
502508c7cb3SChristoph Hellwig             if (score > score_max) {
503508c7cb3SChristoph Hellwig                 score_max = score;
504508c7cb3SChristoph Hellwig                 drv = d;
505f3a5d3f8SChristoph Hellwig             }
506508c7cb3SChristoph Hellwig         }
507f3a5d3f8SChristoph Hellwig     }
508f3a5d3f8SChristoph Hellwig 
509508c7cb3SChristoph Hellwig     return drv;
510f3a5d3f8SChristoph Hellwig }
511f3a5d3f8SChristoph Hellwig 
51298289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
51398289620SKevin Wolf                                 bool allow_protocol_prefix)
51484a12e66SChristoph Hellwig {
51584a12e66SChristoph Hellwig     BlockDriver *drv1;
51684a12e66SChristoph Hellwig     char protocol[128];
51784a12e66SChristoph Hellwig     int len;
51884a12e66SChristoph Hellwig     const char *p;
51984a12e66SChristoph Hellwig 
52066f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
52166f82ceeSKevin Wolf 
52239508e7aSChristoph Hellwig     /*
52339508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
52439508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
52539508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
52639508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
52739508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
52839508e7aSChristoph Hellwig      */
52984a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
53039508e7aSChristoph Hellwig     if (drv1) {
53184a12e66SChristoph Hellwig         return drv1;
53284a12e66SChristoph Hellwig     }
53339508e7aSChristoph Hellwig 
53498289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
53539508e7aSChristoph Hellwig         return bdrv_find_format("file");
53639508e7aSChristoph Hellwig     }
53798289620SKevin Wolf 
5389e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5399e0b22f4SStefan Hajnoczi     assert(p != NULL);
54084a12e66SChristoph Hellwig     len = p - filename;
54184a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
54284a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
54384a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
54484a12e66SChristoph Hellwig     protocol[len] = '\0';
54584a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
54684a12e66SChristoph Hellwig         if (drv1->protocol_name &&
54784a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
54884a12e66SChristoph Hellwig             return drv1;
54984a12e66SChristoph Hellwig         }
55084a12e66SChristoph Hellwig     }
55184a12e66SChristoph Hellwig     return NULL;
55284a12e66SChristoph Hellwig }
55384a12e66SChristoph Hellwig 
554f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
555f500a6d3SKevin Wolf                              BlockDriver **pdrv)
556ea2384d3Sbellard {
557f500a6d3SKevin Wolf     int score, score_max;
558ea2384d3Sbellard     BlockDriver *drv1, *drv;
55983f64091Sbellard     uint8_t buf[2048];
560f500a6d3SKevin Wolf     int ret = 0;
561f8ea0b00SNicholas Bellinger 
56208a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5638e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
564c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
565c98ac35dSStefan Weil         if (!drv) {
566c98ac35dSStefan Weil             ret = -ENOENT;
567c98ac35dSStefan Weil         }
568c98ac35dSStefan Weil         *pdrv = drv;
569c98ac35dSStefan Weil         return ret;
5701a396859SNicholas A. Bellinger     }
571f8ea0b00SNicholas Bellinger 
57283f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
573ea2384d3Sbellard     if (ret < 0) {
574c98ac35dSStefan Weil         *pdrv = NULL;
575c98ac35dSStefan Weil         return ret;
576ea2384d3Sbellard     }
577ea2384d3Sbellard 
578ea2384d3Sbellard     score_max = 0;
57984a12e66SChristoph Hellwig     drv = NULL;
5808a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
58183f64091Sbellard         if (drv1->bdrv_probe) {
582ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
583ea2384d3Sbellard             if (score > score_max) {
584ea2384d3Sbellard                 score_max = score;
585ea2384d3Sbellard                 drv = drv1;
586ea2384d3Sbellard             }
587ea2384d3Sbellard         }
58883f64091Sbellard     }
589c98ac35dSStefan Weil     if (!drv) {
590c98ac35dSStefan Weil         ret = -ENOENT;
591c98ac35dSStefan Weil     }
592c98ac35dSStefan Weil     *pdrv = drv;
593c98ac35dSStefan Weil     return ret;
594ea2384d3Sbellard }
595ea2384d3Sbellard 
59651762288SStefan Hajnoczi /**
59751762288SStefan Hajnoczi  * Set the current 'total_sectors' value
59851762288SStefan Hajnoczi  */
59951762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
60051762288SStefan Hajnoczi {
60151762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
60251762288SStefan Hajnoczi 
603396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
604396759adSNicholas Bellinger     if (bs->sg)
605396759adSNicholas Bellinger         return 0;
606396759adSNicholas Bellinger 
60751762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
60851762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
60951762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
61051762288SStefan Hajnoczi         if (length < 0) {
61151762288SStefan Hajnoczi             return length;
61251762288SStefan Hajnoczi         }
61351762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
61451762288SStefan Hajnoczi     }
61551762288SStefan Hajnoczi 
61651762288SStefan Hajnoczi     bs->total_sectors = hint;
61751762288SStefan Hajnoczi     return 0;
61851762288SStefan Hajnoczi }
61951762288SStefan Hajnoczi 
620c3993cdcSStefan Hajnoczi /**
6219e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6229e8f1835SPaolo Bonzini  *
6239e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6249e8f1835SPaolo Bonzini  */
6259e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6269e8f1835SPaolo Bonzini {
6279e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6289e8f1835SPaolo Bonzini 
6299e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6309e8f1835SPaolo Bonzini         /* do nothing */
6319e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6329e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6339e8f1835SPaolo Bonzini     } else {
6349e8f1835SPaolo Bonzini         return -1;
6359e8f1835SPaolo Bonzini     }
6369e8f1835SPaolo Bonzini 
6379e8f1835SPaolo Bonzini     return 0;
6389e8f1835SPaolo Bonzini }
6399e8f1835SPaolo Bonzini 
6409e8f1835SPaolo Bonzini /**
641c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
642c3993cdcSStefan Hajnoczi  *
643c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
644c3993cdcSStefan Hajnoczi  */
645c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
646c3993cdcSStefan Hajnoczi {
647c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
648c3993cdcSStefan Hajnoczi 
649c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
650c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
65192196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
65292196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
653c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
654c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
655c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
656c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
657c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
658c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
659c3993cdcSStefan Hajnoczi         /* this is the default */
660c3993cdcSStefan Hajnoczi     } else {
661c3993cdcSStefan Hajnoczi         return -1;
662c3993cdcSStefan Hajnoczi     }
663c3993cdcSStefan Hajnoczi 
664c3993cdcSStefan Hajnoczi     return 0;
665c3993cdcSStefan Hajnoczi }
666c3993cdcSStefan Hajnoczi 
66753fec9d3SStefan Hajnoczi /**
66853fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
66953fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
67053fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
67153fec9d3SStefan Hajnoczi  */
67253fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
67353fec9d3SStefan Hajnoczi {
67453fec9d3SStefan Hajnoczi     bs->copy_on_read++;
67553fec9d3SStefan Hajnoczi }
67653fec9d3SStefan Hajnoczi 
67753fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
67853fec9d3SStefan Hajnoczi {
67953fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
68053fec9d3SStefan Hajnoczi     bs->copy_on_read--;
68153fec9d3SStefan Hajnoczi }
68253fec9d3SStefan Hajnoczi 
6837b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
6847b272452SKevin Wolf {
6857b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
6867b272452SKevin Wolf 
6877b272452SKevin Wolf     /*
6887b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
6897b272452SKevin Wolf      * image.
6907b272452SKevin Wolf      */
6917b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6927b272452SKevin Wolf 
6937b272452SKevin Wolf     /*
6947b272452SKevin Wolf      * Snapshots should be writable.
6957b272452SKevin Wolf      */
6967b272452SKevin Wolf     if (bs->is_temporary) {
6977b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
6987b272452SKevin Wolf     }
6997b272452SKevin Wolf 
7007b272452SKevin Wolf     return open_flags;
7017b272452SKevin Wolf }
7027b272452SKevin Wolf 
703b6ce07aaSKevin Wolf /*
70457915332SKevin Wolf  * Common part for opening disk images and files
705b6ad491aSKevin Wolf  *
706b6ad491aSKevin Wolf  * Removes all processed options from *options.
70757915332SKevin Wolf  */
708f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
709035fccdfSKevin Wolf     QDict *options, int flags, BlockDriver *drv)
71057915332SKevin Wolf {
71157915332SKevin Wolf     int ret, open_flags;
712035fccdfSKevin Wolf     const char *filename;
71357915332SKevin Wolf 
71457915332SKevin Wolf     assert(drv != NULL);
7156405875cSPaolo Bonzini     assert(bs->file == NULL);
716707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
71757915332SKevin Wolf 
71845673671SKevin Wolf     if (file != NULL) {
71945673671SKevin Wolf         filename = file->filename;
72045673671SKevin Wolf     } else {
72145673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
72245673671SKevin Wolf     }
72345673671SKevin Wolf 
72445673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
72528dcee10SStefan Hajnoczi 
7265d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
7275d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
7285d186eb0SKevin Wolf      * and return immediately. */
7295d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
7305d186eb0SKevin Wolf         bdrv_swap(file, bs);
7315d186eb0SKevin Wolf         return 0;
7325d186eb0SKevin Wolf     }
7335d186eb0SKevin Wolf 
73457915332SKevin Wolf     bs->open_flags = flags;
73557915332SKevin Wolf     bs->buffer_alignment = 512;
7360d51b4deSAsias He     bs->zero_beyond_eof = true;
737b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
738b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
739b64ec4e4SFam Zheng 
740b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
741b64ec4e4SFam Zheng         return -ENOTSUP;
742b64ec4e4SFam Zheng     }
74357915332SKevin Wolf 
74453fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
745b64ec4e4SFam Zheng     if (!bs->read_only && (flags & BDRV_O_COPY_ON_READ)) {
74653fec9d3SStefan Hajnoczi         bdrv_enable_copy_on_read(bs);
74753fec9d3SStefan Hajnoczi     }
74853fec9d3SStefan Hajnoczi 
749c2ad1b0cSKevin Wolf     if (filename != NULL) {
75057915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
751c2ad1b0cSKevin Wolf     } else {
752c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
753c2ad1b0cSKevin Wolf     }
75457915332SKevin Wolf 
75557915332SKevin Wolf     bs->drv = drv;
7567267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
75757915332SKevin Wolf 
75803f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
759e7c63796SStefan Hajnoczi 
76066f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
76166f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
7625d186eb0SKevin Wolf         assert(file == NULL);
763c2ad1b0cSKevin Wolf         assert(drv->bdrv_parse_filename || filename != NULL);
76456d1b4d2SKevin Wolf         ret = drv->bdrv_file_open(bs, options, open_flags);
765f500a6d3SKevin Wolf     } else {
7662af5ef70SKevin Wolf         if (file == NULL) {
7672af5ef70SKevin Wolf             qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't use '%s' as a "
7682af5ef70SKevin Wolf                           "block driver for the protocol level",
7692af5ef70SKevin Wolf                           drv->format_name);
7702af5ef70SKevin Wolf             ret = -EINVAL;
7712af5ef70SKevin Wolf             goto free_and_fail;
7722af5ef70SKevin Wolf         }
773f500a6d3SKevin Wolf         bs->file = file;
774b6ad491aSKevin Wolf         ret = drv->bdrv_open(bs, options, open_flags);
77566f82ceeSKevin Wolf     }
77666f82ceeSKevin Wolf 
77757915332SKevin Wolf     if (ret < 0) {
77857915332SKevin Wolf         goto free_and_fail;
77957915332SKevin Wolf     }
78057915332SKevin Wolf 
78151762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
78251762288SStefan Hajnoczi     if (ret < 0) {
78351762288SStefan Hajnoczi         goto free_and_fail;
78457915332SKevin Wolf     }
78551762288SStefan Hajnoczi 
78657915332SKevin Wolf #ifndef _WIN32
78757915332SKevin Wolf     if (bs->is_temporary) {
788c2ad1b0cSKevin Wolf         assert(filename != NULL);
78957915332SKevin Wolf         unlink(filename);
79057915332SKevin Wolf     }
79157915332SKevin Wolf #endif
79257915332SKevin Wolf     return 0;
79357915332SKevin Wolf 
79457915332SKevin Wolf free_and_fail:
79566f82ceeSKevin Wolf     bs->file = NULL;
7967267c094SAnthony Liguori     g_free(bs->opaque);
79757915332SKevin Wolf     bs->opaque = NULL;
79857915332SKevin Wolf     bs->drv = NULL;
79957915332SKevin Wolf     return ret;
80057915332SKevin Wolf }
80157915332SKevin Wolf 
80257915332SKevin Wolf /*
803b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
804787e4a85SKevin Wolf  *
805787e4a85SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
806787e4a85SKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
807787e4a85SKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
808787e4a85SKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
809b6ce07aaSKevin Wolf  */
810787e4a85SKevin Wolf int bdrv_file_open(BlockDriverState **pbs, const char *filename,
811787e4a85SKevin Wolf                    QDict *options, int flags)
812b338082bSbellard {
81383f64091Sbellard     BlockDriverState *bs;
8146db95603SChristoph Hellwig     BlockDriver *drv;
815c2ad1b0cSKevin Wolf     const char *drvname;
81698289620SKevin Wolf     bool allow_protocol_prefix = false;
81783f64091Sbellard     int ret;
8183b0d4f61Sbellard 
819707ff828SKevin Wolf     /* NULL means an empty set of options */
820707ff828SKevin Wolf     if (options == NULL) {
821707ff828SKevin Wolf         options = qdict_new();
8223b0d4f61Sbellard     }
823707ff828SKevin Wolf 
824707ff828SKevin Wolf     bs = bdrv_new("");
825707ff828SKevin Wolf     bs->options = options;
826707ff828SKevin Wolf     options = qdict_clone_shallow(options);
827707ff828SKevin Wolf 
828035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
829035fccdfSKevin Wolf     if (!filename) {
830035fccdfSKevin Wolf         filename = qdict_get_try_str(options, "filename");
831035fccdfSKevin Wolf     } else if (filename && !qdict_haskey(options, "filename")) {
832035fccdfSKevin Wolf         qdict_put(options, "filename", qstring_from_str(filename));
83398289620SKevin Wolf         allow_protocol_prefix = true;
834035fccdfSKevin Wolf     } else {
835035fccdfSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't specify 'file' and "
836035fccdfSKevin Wolf                       "'filename' options at the same time");
837035fccdfSKevin Wolf         ret = -EINVAL;
838035fccdfSKevin Wolf         goto fail;
839035fccdfSKevin Wolf     }
840035fccdfSKevin Wolf 
841c2ad1b0cSKevin Wolf     /* Find the right block driver */
842c2ad1b0cSKevin Wolf     drvname = qdict_get_try_str(options, "driver");
843c2ad1b0cSKevin Wolf     if (drvname) {
844b64ec4e4SFam Zheng         drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));
845c2ad1b0cSKevin Wolf         qdict_del(options, "driver");
846c2ad1b0cSKevin Wolf     } else if (filename) {
84798289620SKevin Wolf         drv = bdrv_find_protocol(filename, allow_protocol_prefix);
84898289620SKevin Wolf         if (!drv) {
84998289620SKevin Wolf             qerror_report(ERROR_CLASS_GENERIC_ERROR, "Unknown protocol");
85098289620SKevin Wolf         }
851c2ad1b0cSKevin Wolf     } else {
852c2ad1b0cSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR,
853c2ad1b0cSKevin Wolf                       "Must specify either driver or file");
854c2ad1b0cSKevin Wolf         drv = NULL;
855c2ad1b0cSKevin Wolf     }
856c2ad1b0cSKevin Wolf 
857c2ad1b0cSKevin Wolf     if (!drv) {
858c2ad1b0cSKevin Wolf         ret = -ENOENT;
859c2ad1b0cSKevin Wolf         goto fail;
860c2ad1b0cSKevin Wolf     }
861c2ad1b0cSKevin Wolf 
862c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
863c2ad1b0cSKevin Wolf     if (drv->bdrv_parse_filename && filename) {
8646963a30dSKevin Wolf         Error *local_err = NULL;
8656963a30dSKevin Wolf         drv->bdrv_parse_filename(filename, options, &local_err);
8666963a30dSKevin Wolf         if (error_is_set(&local_err)) {
8676963a30dSKevin Wolf             qerror_report_err(local_err);
8686963a30dSKevin Wolf             error_free(local_err);
8696963a30dSKevin Wolf             ret = -EINVAL;
8706963a30dSKevin Wolf             goto fail;
8716963a30dSKevin Wolf         }
87256d1b4d2SKevin Wolf         qdict_del(options, "filename");
873c2ad1b0cSKevin Wolf     } else if (!drv->bdrv_parse_filename && !filename) {
874c2ad1b0cSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR,
875c2ad1b0cSKevin Wolf                       "The '%s' block driver requires a file name",
876c2ad1b0cSKevin Wolf                       drv->format_name);
877c2ad1b0cSKevin Wolf         ret = -EINVAL;
878c2ad1b0cSKevin Wolf         goto fail;
8796963a30dSKevin Wolf     }
8806963a30dSKevin Wolf 
881035fccdfSKevin Wolf     ret = bdrv_open_common(bs, NULL, options, flags, drv);
882707ff828SKevin Wolf     if (ret < 0) {
883707ff828SKevin Wolf         goto fail;
884707ff828SKevin Wolf     }
885707ff828SKevin Wolf 
886707ff828SKevin Wolf     /* Check if any unknown options were used */
887707ff828SKevin Wolf     if (qdict_size(options) != 0) {
888707ff828SKevin Wolf         const QDictEntry *entry = qdict_first(options);
889707ff828SKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block protocol '%s' doesn't "
890707ff828SKevin Wolf                       "support the option '%s'",
891707ff828SKevin Wolf                       drv->format_name, entry->key);
892707ff828SKevin Wolf         ret = -EINVAL;
893707ff828SKevin Wolf         goto fail;
894707ff828SKevin Wolf     }
895707ff828SKevin Wolf     QDECREF(options);
896707ff828SKevin Wolf 
89771d0770cSaliguori     bs->growable = 1;
89883f64091Sbellard     *pbs = bs;
89983f64091Sbellard     return 0;
900707ff828SKevin Wolf 
901707ff828SKevin Wolf fail:
902707ff828SKevin Wolf     QDECREF(options);
903707ff828SKevin Wolf     if (!bs->drv) {
904707ff828SKevin Wolf         QDECREF(bs->options);
905707ff828SKevin Wolf     }
906707ff828SKevin Wolf     bdrv_delete(bs);
907707ff828SKevin Wolf     return ret;
9083b0d4f61Sbellard }
9093b0d4f61Sbellard 
91031ca6d07SKevin Wolf /*
91131ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
91231ca6d07SKevin Wolf  *
91331ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
91431ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
91531ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
91631ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
91731ca6d07SKevin Wolf  */
91831ca6d07SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *options)
9199156df12SPaolo Bonzini {
9209156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
9219156df12SPaolo Bonzini     int back_flags, ret;
9229156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
9239156df12SPaolo Bonzini 
9249156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
92531ca6d07SKevin Wolf         QDECREF(options);
9269156df12SPaolo Bonzini         return 0;
9279156df12SPaolo Bonzini     }
9289156df12SPaolo Bonzini 
92931ca6d07SKevin Wolf     /* NULL means an empty set of options */
93031ca6d07SKevin Wolf     if (options == NULL) {
93131ca6d07SKevin Wolf         options = qdict_new();
93231ca6d07SKevin Wolf     }
93331ca6d07SKevin Wolf 
9349156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
9351cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
9361cb6f506SKevin Wolf         backing_filename[0] = '\0';
9371cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
93831ca6d07SKevin Wolf         QDECREF(options);
9399156df12SPaolo Bonzini         return 0;
9409156df12SPaolo Bonzini     }
9419156df12SPaolo Bonzini 
9429156df12SPaolo Bonzini     bs->backing_hd = bdrv_new("");
9439156df12SPaolo Bonzini     bdrv_get_full_backing_filename(bs, backing_filename,
9449156df12SPaolo Bonzini                                    sizeof(backing_filename));
9459156df12SPaolo Bonzini 
9469156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
9479156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
9489156df12SPaolo Bonzini     }
9499156df12SPaolo Bonzini 
9509156df12SPaolo Bonzini     /* backing files always opened read-only */
9519156df12SPaolo Bonzini     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
9529156df12SPaolo Bonzini 
95331ca6d07SKevin Wolf     ret = bdrv_open(bs->backing_hd,
95431ca6d07SKevin Wolf                     *backing_filename ? backing_filename : NULL, options,
955de9c0cecSKevin Wolf                     back_flags, back_drv);
9569156df12SPaolo Bonzini     if (ret < 0) {
9579156df12SPaolo Bonzini         bdrv_delete(bs->backing_hd);
9589156df12SPaolo Bonzini         bs->backing_hd = NULL;
9599156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
9609156df12SPaolo Bonzini         return ret;
9619156df12SPaolo Bonzini     }
9629156df12SPaolo Bonzini     return 0;
9639156df12SPaolo Bonzini }
9649156df12SPaolo Bonzini 
965707ff828SKevin Wolf static void extract_subqdict(QDict *src, QDict **dst, const char *start)
966707ff828SKevin Wolf {
967707ff828SKevin Wolf     const QDictEntry *entry, *next;
968707ff828SKevin Wolf     const char *p;
969707ff828SKevin Wolf 
970707ff828SKevin Wolf     *dst = qdict_new();
971707ff828SKevin Wolf     entry = qdict_first(src);
972707ff828SKevin Wolf 
973707ff828SKevin Wolf     while (entry != NULL) {
974707ff828SKevin Wolf         next = qdict_next(src, entry);
975707ff828SKevin Wolf         if (strstart(entry->key, start, &p)) {
976707ff828SKevin Wolf             qobject_incref(entry->value);
977707ff828SKevin Wolf             qdict_put_obj(*dst, p, entry->value);
978707ff828SKevin Wolf             qdict_del(src, entry->key);
979707ff828SKevin Wolf         }
980707ff828SKevin Wolf         entry = next;
981707ff828SKevin Wolf     }
982707ff828SKevin Wolf }
983707ff828SKevin Wolf 
984b6ce07aaSKevin Wolf /*
985b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
986de9c0cecSKevin Wolf  *
987de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
988de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
989de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
990de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
991b6ce07aaSKevin Wolf  */
992de9c0cecSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
993de9c0cecSKevin Wolf               int flags, BlockDriver *drv)
994ea2384d3Sbellard {
995b6ce07aaSKevin Wolf     int ret;
99689c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
99789c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
998f500a6d3SKevin Wolf     BlockDriverState *file = NULL;
999707ff828SKevin Wolf     QDict *file_options = NULL;
100074fe54f2SKevin Wolf     const char *drvname;
100133e3963eSbellard 
1002de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1003de9c0cecSKevin Wolf     if (options == NULL) {
1004de9c0cecSKevin Wolf         options = qdict_new();
1005de9c0cecSKevin Wolf     }
1006de9c0cecSKevin Wolf 
1007de9c0cecSKevin Wolf     bs->options = options;
1008b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1009de9c0cecSKevin Wolf 
1010de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
101183f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
1012ea2384d3Sbellard         BlockDriverState *bs1;
1013ea2384d3Sbellard         int64_t total_size;
101491a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
101508b392e1SKevin Wolf         QEMUOptionParameter *create_options;
1016b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
101733e3963eSbellard 
1018c2ad1b0cSKevin Wolf         if (qdict_size(options) != 0) {
1019c2ad1b0cSKevin Wolf             error_report("Can't use snapshot=on with driver-specific options");
1020c2ad1b0cSKevin Wolf             ret = -EINVAL;
1021c2ad1b0cSKevin Wolf             goto fail;
1022c2ad1b0cSKevin Wolf         }
1023c2ad1b0cSKevin Wolf         assert(filename != NULL);
1024c2ad1b0cSKevin Wolf 
1025ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
1026ea2384d3Sbellard            instead of opening 'filename' directly */
1027ea2384d3Sbellard 
1028ea2384d3Sbellard         /* if there is a backing file, use it */
1029ea2384d3Sbellard         bs1 = bdrv_new("");
1030de9c0cecSKevin Wolf         ret = bdrv_open(bs1, filename, NULL, 0, drv);
103151d7c00cSaliguori         if (ret < 0) {
1032ea2384d3Sbellard             bdrv_delete(bs1);
1033de9c0cecSKevin Wolf             goto fail;
1034ea2384d3Sbellard         }
10353e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
10367c96d46eSaliguori 
1037ea2384d3Sbellard         bdrv_delete(bs1);
1038ea2384d3Sbellard 
1039eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1040eba25057SJim Meyering         if (ret < 0) {
1041de9c0cecSKevin Wolf             goto fail;
1042eba25057SJim Meyering         }
10437c96d46eSaliguori 
10447c96d46eSaliguori         /* Real path is meaningless for protocols */
10454d70655bSStefan Hajnoczi         if (path_has_protocol(filename)) {
10467c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
10477c96d46eSaliguori                      "%s", filename);
1048de9c0cecSKevin Wolf         } else if (!realpath(filename, backing_filename)) {
1049de9c0cecSKevin Wolf             ret = -errno;
1050de9c0cecSKevin Wolf             goto fail;
1051de9c0cecSKevin Wolf         }
10527c96d46eSaliguori 
105391a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
105408b392e1SKevin Wolf         create_options = parse_option_parameters("", bdrv_qcow2->create_options,
105508b392e1SKevin Wolf                                                  NULL);
105691a073a9SKevin Wolf 
105708b392e1SKevin Wolf         set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
105808b392e1SKevin Wolf         set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,
105908b392e1SKevin Wolf                              backing_filename);
106091a073a9SKevin Wolf         if (drv) {
106108b392e1SKevin Wolf             set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
106291a073a9SKevin Wolf                 drv->format_name);
106391a073a9SKevin Wolf         }
106491a073a9SKevin Wolf 
106508b392e1SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);
106608b392e1SKevin Wolf         free_option_parameters(create_options);
106751d7c00cSaliguori         if (ret < 0) {
1068de9c0cecSKevin Wolf             goto fail;
1069ea2384d3Sbellard         }
107091a073a9SKevin Wolf 
1071ea2384d3Sbellard         filename = tmp_filename;
107291a073a9SKevin Wolf         drv = bdrv_qcow2;
1073ea2384d3Sbellard         bs->is_temporary = 1;
1074ea2384d3Sbellard     }
1075ea2384d3Sbellard 
1076f500a6d3SKevin Wolf     /* Open image file without format layer */
1077be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1078be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1079be028adcSJeff Cody     }
1080be028adcSJeff Cody 
1081707ff828SKevin Wolf     extract_subqdict(options, &file_options, "file.");
1082707ff828SKevin Wolf 
1083707ff828SKevin Wolf     ret = bdrv_file_open(&file, filename, file_options,
108450b05b6fSKevin Wolf                          bdrv_open_flags(bs, flags | BDRV_O_UNMAP));
1085f500a6d3SKevin Wolf     if (ret < 0) {
1086de9c0cecSKevin Wolf         goto fail;
1087f500a6d3SKevin Wolf     }
1088f500a6d3SKevin Wolf 
1089f500a6d3SKevin Wolf     /* Find the right image format driver */
109074fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
109174fe54f2SKevin Wolf     if (drvname) {
109274fe54f2SKevin Wolf         drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));
109374fe54f2SKevin Wolf         qdict_del(options, "driver");
109474fe54f2SKevin Wolf     }
109574fe54f2SKevin Wolf 
1096f500a6d3SKevin Wolf     if (!drv) {
1097f500a6d3SKevin Wolf         ret = find_image_format(file, filename, &drv);
1098f500a6d3SKevin Wolf     }
1099f500a6d3SKevin Wolf 
1100f500a6d3SKevin Wolf     if (!drv) {
1101f500a6d3SKevin Wolf         goto unlink_and_fail;
1102f500a6d3SKevin Wolf     }
1103f500a6d3SKevin Wolf 
1104b6ce07aaSKevin Wolf     /* Open the image */
1105035fccdfSKevin Wolf     ret = bdrv_open_common(bs, file, options, flags, drv);
1106b6ce07aaSKevin Wolf     if (ret < 0) {
11076987307cSChristoph Hellwig         goto unlink_and_fail;
11086987307cSChristoph Hellwig     }
11096987307cSChristoph Hellwig 
1110f500a6d3SKevin Wolf     if (bs->file != file) {
1111f500a6d3SKevin Wolf         bdrv_delete(file);
1112f500a6d3SKevin Wolf         file = NULL;
1113f500a6d3SKevin Wolf     }
1114f500a6d3SKevin Wolf 
1115b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
11169156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
111731ca6d07SKevin Wolf         QDict *backing_options;
111831ca6d07SKevin Wolf 
111931ca6d07SKevin Wolf         extract_subqdict(options, &backing_options, "backing.");
112031ca6d07SKevin Wolf         ret = bdrv_open_backing_file(bs, backing_options);
1121b6ce07aaSKevin Wolf         if (ret < 0) {
1122b6ad491aSKevin Wolf             goto close_and_fail;
1123b6ce07aaSKevin Wolf         }
1124b6ce07aaSKevin Wolf     }
1125b6ce07aaSKevin Wolf 
1126b6ad491aSKevin Wolf     /* Check if any unknown options were used */
1127b6ad491aSKevin Wolf     if (qdict_size(options) != 0) {
1128b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
1129b6ad491aSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "
1130b6ad491aSKevin Wolf             "device '%s' doesn't support the option '%s'",
1131b6ad491aSKevin Wolf             drv->format_name, bs->device_name, entry->key);
1132b6ad491aSKevin Wolf 
1133b6ad491aSKevin Wolf         ret = -EINVAL;
1134b6ad491aSKevin Wolf         goto close_and_fail;
1135b6ad491aSKevin Wolf     }
1136b6ad491aSKevin Wolf     QDECREF(options);
1137b6ad491aSKevin Wolf 
1138b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
11397d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1140b6ce07aaSKevin Wolf     }
1141b6ce07aaSKevin Wolf 
1142b6ce07aaSKevin Wolf     return 0;
1143b6ce07aaSKevin Wolf 
1144b6ce07aaSKevin Wolf unlink_and_fail:
1145f500a6d3SKevin Wolf     if (file != NULL) {
1146f500a6d3SKevin Wolf         bdrv_delete(file);
1147f500a6d3SKevin Wolf     }
1148b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1149b6ce07aaSKevin Wolf         unlink(filename);
1150b6ce07aaSKevin Wolf     }
1151de9c0cecSKevin Wolf fail:
1152de9c0cecSKevin Wolf     QDECREF(bs->options);
1153b6ad491aSKevin Wolf     QDECREF(options);
1154de9c0cecSKevin Wolf     bs->options = NULL;
1155b6ad491aSKevin Wolf     return ret;
1156de9c0cecSKevin Wolf 
1157b6ad491aSKevin Wolf close_and_fail:
1158b6ad491aSKevin Wolf     bdrv_close(bs);
1159b6ad491aSKevin Wolf     QDECREF(options);
1160b6ce07aaSKevin Wolf     return ret;
1161b6ce07aaSKevin Wolf }
1162b6ce07aaSKevin Wolf 
1163e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1164e971aa12SJeff Cody      bool prepared;
1165e971aa12SJeff Cody      BDRVReopenState state;
1166e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1167e971aa12SJeff Cody } BlockReopenQueueEntry;
1168e971aa12SJeff Cody 
1169e971aa12SJeff Cody /*
1170e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1171e971aa12SJeff Cody  * reopen of multiple devices.
1172e971aa12SJeff Cody  *
1173e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1174e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1175e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1176e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1177e971aa12SJeff Cody  * atomic 'set'.
1178e971aa12SJeff Cody  *
1179e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1180e971aa12SJeff Cody  *
1181e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1182e971aa12SJeff Cody  *
1183e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1184e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1185e971aa12SJeff Cody  *
1186e971aa12SJeff Cody  */
1187e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1188e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1189e971aa12SJeff Cody {
1190e971aa12SJeff Cody     assert(bs != NULL);
1191e971aa12SJeff Cody 
1192e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1193e971aa12SJeff Cody     if (bs_queue == NULL) {
1194e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1195e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1196e971aa12SJeff Cody     }
1197e971aa12SJeff Cody 
1198e971aa12SJeff Cody     if (bs->file) {
1199e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1200e971aa12SJeff Cody     }
1201e971aa12SJeff Cody 
1202e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1203e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1204e971aa12SJeff Cody 
1205e971aa12SJeff Cody     bs_entry->state.bs = bs;
1206e971aa12SJeff Cody     bs_entry->state.flags = flags;
1207e971aa12SJeff Cody 
1208e971aa12SJeff Cody     return bs_queue;
1209e971aa12SJeff Cody }
1210e971aa12SJeff Cody 
1211e971aa12SJeff Cody /*
1212e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1213e971aa12SJeff Cody  *
1214e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1215e971aa12SJeff Cody  * via bdrv_reopen_queue().
1216e971aa12SJeff Cody  *
1217e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1218e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1219e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1220e971aa12SJeff Cody  * data cleaned up.
1221e971aa12SJeff Cody  *
1222e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1223e971aa12SJeff Cody  * to all devices.
1224e971aa12SJeff Cody  *
1225e971aa12SJeff Cody  */
1226e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1227e971aa12SJeff Cody {
1228e971aa12SJeff Cody     int ret = -1;
1229e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1230e971aa12SJeff Cody     Error *local_err = NULL;
1231e971aa12SJeff Cody 
1232e971aa12SJeff Cody     assert(bs_queue != NULL);
1233e971aa12SJeff Cody 
1234e971aa12SJeff Cody     bdrv_drain_all();
1235e971aa12SJeff Cody 
1236e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1237e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1238e971aa12SJeff Cody             error_propagate(errp, local_err);
1239e971aa12SJeff Cody             goto cleanup;
1240e971aa12SJeff Cody         }
1241e971aa12SJeff Cody         bs_entry->prepared = true;
1242e971aa12SJeff Cody     }
1243e971aa12SJeff Cody 
1244e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1245e971aa12SJeff Cody      * changes
1246e971aa12SJeff Cody      */
1247e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1248e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1249e971aa12SJeff Cody     }
1250e971aa12SJeff Cody 
1251e971aa12SJeff Cody     ret = 0;
1252e971aa12SJeff Cody 
1253e971aa12SJeff Cody cleanup:
1254e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1255e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1256e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1257e971aa12SJeff Cody         }
1258e971aa12SJeff Cody         g_free(bs_entry);
1259e971aa12SJeff Cody     }
1260e971aa12SJeff Cody     g_free(bs_queue);
1261e971aa12SJeff Cody     return ret;
1262e971aa12SJeff Cody }
1263e971aa12SJeff Cody 
1264e971aa12SJeff Cody 
1265e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1266e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1267e971aa12SJeff Cody {
1268e971aa12SJeff Cody     int ret = -1;
1269e971aa12SJeff Cody     Error *local_err = NULL;
1270e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1271e971aa12SJeff Cody 
1272e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1273e971aa12SJeff Cody     if (local_err != NULL) {
1274e971aa12SJeff Cody         error_propagate(errp, local_err);
1275e971aa12SJeff Cody     }
1276e971aa12SJeff Cody     return ret;
1277e971aa12SJeff Cody }
1278e971aa12SJeff Cody 
1279e971aa12SJeff Cody 
1280e971aa12SJeff Cody /*
1281e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1282e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1283e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1284e971aa12SJeff Cody  *
1285e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1286e971aa12SJeff Cody  * flags are the new open flags
1287e971aa12SJeff Cody  * queue is the reopen queue
1288e971aa12SJeff Cody  *
1289e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1290e971aa12SJeff Cody  * as well.
1291e971aa12SJeff Cody  *
1292e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1293e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1294e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1295e971aa12SJeff Cody  *
1296e971aa12SJeff Cody  */
1297e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1298e971aa12SJeff Cody                         Error **errp)
1299e971aa12SJeff Cody {
1300e971aa12SJeff Cody     int ret = -1;
1301e971aa12SJeff Cody     Error *local_err = NULL;
1302e971aa12SJeff Cody     BlockDriver *drv;
1303e971aa12SJeff Cody 
1304e971aa12SJeff Cody     assert(reopen_state != NULL);
1305e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1306e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1307e971aa12SJeff Cody 
1308e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1309e971aa12SJeff Cody      * to r/w */
1310e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1311e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1312e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1313e971aa12SJeff Cody                   reopen_state->bs->device_name);
1314e971aa12SJeff Cody         goto error;
1315e971aa12SJeff Cody     }
1316e971aa12SJeff Cody 
1317e971aa12SJeff Cody 
1318e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1319e971aa12SJeff Cody     if (ret) {
1320e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1321e971aa12SJeff Cody                   strerror(-ret));
1322e971aa12SJeff Cody         goto error;
1323e971aa12SJeff Cody     }
1324e971aa12SJeff Cody 
1325e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1326e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1327e971aa12SJeff Cody         if (ret) {
1328e971aa12SJeff Cody             if (local_err != NULL) {
1329e971aa12SJeff Cody                 error_propagate(errp, local_err);
1330e971aa12SJeff Cody             } else {
1331d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1332e971aa12SJeff Cody                            reopen_state->bs->filename);
1333e971aa12SJeff Cody             }
1334e971aa12SJeff Cody             goto error;
1335e971aa12SJeff Cody         }
1336e971aa12SJeff Cody     } else {
1337e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1338e971aa12SJeff Cody          * handler for each supported drv. */
1339e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1340e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1341e971aa12SJeff Cody                  "reopening of file");
1342e971aa12SJeff Cody         ret = -1;
1343e971aa12SJeff Cody         goto error;
1344e971aa12SJeff Cody     }
1345e971aa12SJeff Cody 
1346e971aa12SJeff Cody     ret = 0;
1347e971aa12SJeff Cody 
1348e971aa12SJeff Cody error:
1349e971aa12SJeff Cody     return ret;
1350e971aa12SJeff Cody }
1351e971aa12SJeff Cody 
1352e971aa12SJeff Cody /*
1353e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1354e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1355e971aa12SJeff Cody  * the active BlockDriverState contents.
1356e971aa12SJeff Cody  */
1357e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1358e971aa12SJeff Cody {
1359e971aa12SJeff Cody     BlockDriver *drv;
1360e971aa12SJeff Cody 
1361e971aa12SJeff Cody     assert(reopen_state != NULL);
1362e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1363e971aa12SJeff Cody     assert(drv != NULL);
1364e971aa12SJeff Cody 
1365e971aa12SJeff Cody     /* If there are any driver level actions to take */
1366e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1367e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1368e971aa12SJeff Cody     }
1369e971aa12SJeff Cody 
1370e971aa12SJeff Cody     /* set BDS specific flags now */
1371e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1372e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1373e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1374e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1375e971aa12SJeff Cody }
1376e971aa12SJeff Cody 
1377e971aa12SJeff Cody /*
1378e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1379e971aa12SJeff Cody  * reopen_state
1380e971aa12SJeff Cody  */
1381e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1382e971aa12SJeff Cody {
1383e971aa12SJeff Cody     BlockDriver *drv;
1384e971aa12SJeff Cody 
1385e971aa12SJeff Cody     assert(reopen_state != NULL);
1386e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1387e971aa12SJeff Cody     assert(drv != NULL);
1388e971aa12SJeff Cody 
1389e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1390e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1391e971aa12SJeff Cody     }
1392e971aa12SJeff Cody }
1393e971aa12SJeff Cody 
1394e971aa12SJeff Cody 
1395fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1396fc01f7e7Sbellard {
13973e914655SPaolo Bonzini     if (bs->job) {
13983e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
13993e914655SPaolo Bonzini     }
140058fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
140158fda173SStefan Hajnoczi     bdrv_flush(bs);
140258fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1403d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
14047094f12fSKevin Wolf 
14053cbc002cSPaolo Bonzini     if (bs->drv) {
1406557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1407ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
1408557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1409557df6acSStefan Hajnoczi         }
1410ea2384d3Sbellard         bs->drv->bdrv_close(bs);
14117267c094SAnthony Liguori         g_free(bs->opaque);
1412ea2384d3Sbellard #ifdef _WIN32
1413ea2384d3Sbellard         if (bs->is_temporary) {
1414ea2384d3Sbellard             unlink(bs->filename);
1415ea2384d3Sbellard         }
141667b915a5Sbellard #endif
1417ea2384d3Sbellard         bs->opaque = NULL;
1418ea2384d3Sbellard         bs->drv = NULL;
141953fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1420a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1421a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
14226405875cSPaolo Bonzini         bs->total_sectors = 0;
14236405875cSPaolo Bonzini         bs->encrypted = 0;
14246405875cSPaolo Bonzini         bs->valid_key = 0;
14256405875cSPaolo Bonzini         bs->sg = 0;
14266405875cSPaolo Bonzini         bs->growable = 0;
14270d51b4deSAsias He         bs->zero_beyond_eof = false;
1428de9c0cecSKevin Wolf         QDECREF(bs->options);
1429de9c0cecSKevin Wolf         bs->options = NULL;
1430b338082bSbellard 
143166f82ceeSKevin Wolf         if (bs->file != NULL) {
14320ac9377dSPaolo Bonzini             bdrv_delete(bs->file);
14330ac9377dSPaolo Bonzini             bs->file = NULL;
143466f82ceeSKevin Wolf         }
14359ca11154SPavel Hrdina     }
143666f82ceeSKevin Wolf 
14377d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
143898f90dbaSZhi Yong Wu 
143998f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
144098f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
144198f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
144298f90dbaSZhi Yong Wu     }
1443b338082bSbellard }
1444b338082bSbellard 
14452bc93fedSMORITA Kazutaka void bdrv_close_all(void)
14462bc93fedSMORITA Kazutaka {
14472bc93fedSMORITA Kazutaka     BlockDriverState *bs;
14482bc93fedSMORITA Kazutaka 
14492bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
14502bc93fedSMORITA Kazutaka         bdrv_close(bs);
14512bc93fedSMORITA Kazutaka     }
14522bc93fedSMORITA Kazutaka }
14532bc93fedSMORITA Kazutaka 
145488266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
145588266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
145688266f5aSStefan Hajnoczi {
145788266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
145888266f5aSStefan Hajnoczi         return true;
145988266f5aSStefan Hajnoczi     }
1460cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1461cc0681c4SBenoît Canet         return true;
1462cc0681c4SBenoît Canet     }
1463cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
146488266f5aSStefan Hajnoczi         return true;
146588266f5aSStefan Hajnoczi     }
146688266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
146788266f5aSStefan Hajnoczi         return true;
146888266f5aSStefan Hajnoczi     }
146988266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
147088266f5aSStefan Hajnoczi         return true;
147188266f5aSStefan Hajnoczi     }
147288266f5aSStefan Hajnoczi     return false;
147388266f5aSStefan Hajnoczi }
147488266f5aSStefan Hajnoczi 
147588266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
147688266f5aSStefan Hajnoczi {
147788266f5aSStefan Hajnoczi     BlockDriverState *bs;
147888266f5aSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
147988266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
148088266f5aSStefan Hajnoczi             return true;
148188266f5aSStefan Hajnoczi         }
148288266f5aSStefan Hajnoczi     }
148388266f5aSStefan Hajnoczi     return false;
148488266f5aSStefan Hajnoczi }
148588266f5aSStefan Hajnoczi 
1486922453bcSStefan Hajnoczi /*
1487922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1488922453bcSStefan Hajnoczi  *
1489922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1490922453bcSStefan Hajnoczi  * after calling this function.
14914c355d53SZhi Yong Wu  *
14924c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
14934c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
14944c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
14954c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
14964c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1497922453bcSStefan Hajnoczi  */
1498922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1499922453bcSStefan Hajnoczi {
150088266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
150188266f5aSStefan Hajnoczi     bool busy = true;
1502922453bcSStefan Hajnoczi     BlockDriverState *bs;
1503922453bcSStefan Hajnoczi 
150488266f5aSStefan Hajnoczi     while (busy) {
15054c355d53SZhi Yong Wu         /* FIXME: We do not have timer support here, so this is effectively
15064c355d53SZhi Yong Wu          * a busy wait.
15074c355d53SZhi Yong Wu          */
15084c355d53SZhi Yong Wu         QTAILQ_FOREACH(bs, &bdrv_states, list) {
1509cc0681c4SBenoît Canet             if (bdrv_start_throttled_reqs(bs)) {
15104c355d53SZhi Yong Wu                 busy = true;
15114c355d53SZhi Yong Wu             }
15124c355d53SZhi Yong Wu         }
1513922453bcSStefan Hajnoczi 
151488266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
151588266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1516922453bcSStefan Hajnoczi     }
1517922453bcSStefan Hajnoczi }
1518922453bcSStefan Hajnoczi 
1519d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
1520d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1521d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1522d22b2f41SRyan Harper {
1523d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1524d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
1525d22b2f41SRyan Harper     }
1526d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1527d22b2f41SRyan Harper }
1528d22b2f41SRyan Harper 
1529e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1530e023b2e2SPaolo Bonzini {
1531e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1532e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1533e023b2e2SPaolo Bonzini     }
1534e023b2e2SPaolo Bonzini }
1535e023b2e2SPaolo Bonzini 
15364ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
15374ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
15384ddc07caSPaolo Bonzini {
15394ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
15404ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
15414ddc07caSPaolo Bonzini 
15424ddc07caSPaolo Bonzini     /* dev info */
15434ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
15444ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
15454ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
15464ddc07caSPaolo Bonzini     bs_dest->buffer_alignment   = bs_src->buffer_alignment;
15474ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
15484ddc07caSPaolo Bonzini 
15494ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
15504ddc07caSPaolo Bonzini 
1551cc0681c4SBenoît Canet     /* i/o throttled req */
1552cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1553cc0681c4SBenoît Canet            &bs_src->throttle_state,
1554cc0681c4SBenoît Canet            sizeof(ThrottleState));
1555cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1556cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
15574ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
15584ddc07caSPaolo Bonzini 
15594ddc07caSPaolo Bonzini     /* r/w error */
15604ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
15614ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
15624ddc07caSPaolo Bonzini 
15634ddc07caSPaolo Bonzini     /* i/o status */
15644ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
15654ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
15664ddc07caSPaolo Bonzini 
15674ddc07caSPaolo Bonzini     /* dirty bitmap */
15684ddc07caSPaolo Bonzini     bs_dest->dirty_bitmap       = bs_src->dirty_bitmap;
15694ddc07caSPaolo Bonzini 
1570*9fcb0251SFam Zheng     /* reference count */
1571*9fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
1572*9fcb0251SFam Zheng 
15734ddc07caSPaolo Bonzini     /* job */
15744ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
15754ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
15764ddc07caSPaolo Bonzini 
15774ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
15784ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
15794ddc07caSPaolo Bonzini             bs_src->device_name);
15804ddc07caSPaolo Bonzini     bs_dest->list = bs_src->list;
15814ddc07caSPaolo Bonzini }
15824ddc07caSPaolo Bonzini 
15834ddc07caSPaolo Bonzini /*
15844ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
15854ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
15864ddc07caSPaolo Bonzini  * actually attached to a device.
15874ddc07caSPaolo Bonzini  *
15884ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
15894ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
15904ddc07caSPaolo Bonzini  *
15914ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
15924ddc07caSPaolo Bonzini  *
15934ddc07caSPaolo Bonzini  * This function does not create any image files.
15944ddc07caSPaolo Bonzini  */
15954ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
15964ddc07caSPaolo Bonzini {
15974ddc07caSPaolo Bonzini     BlockDriverState tmp;
15984ddc07caSPaolo Bonzini 
15994ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
16004ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
16014ddc07caSPaolo Bonzini     assert(bs_new->dirty_bitmap == NULL);
16024ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
16034ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
16044ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
16054ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1606cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
16074ddc07caSPaolo Bonzini 
16084ddc07caSPaolo Bonzini     tmp = *bs_new;
16094ddc07caSPaolo Bonzini     *bs_new = *bs_old;
16104ddc07caSPaolo Bonzini     *bs_old = tmp;
16114ddc07caSPaolo Bonzini 
16124ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
16134ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
16144ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
16154ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
16164ddc07caSPaolo Bonzini 
16174ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
16184ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
16194ddc07caSPaolo Bonzini 
16204ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
16214ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
16224ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
16234ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
16244ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
1625cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
16264ddc07caSPaolo Bonzini 
16274ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
16284ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
16294ddc07caSPaolo Bonzini }
16304ddc07caSPaolo Bonzini 
16318802d1fdSJeff Cody /*
16328802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
16338802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
16348802d1fdSJeff Cody  *
16358802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
16368802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
16378802d1fdSJeff Cody  *
1638f6801b83SJeff Cody  * bs_new is required to be anonymous.
1639f6801b83SJeff Cody  *
16408802d1fdSJeff Cody  * This function does not create any image files.
16418802d1fdSJeff Cody  */
16428802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
16438802d1fdSJeff Cody {
16444ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
16458802d1fdSJeff Cody 
16468802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
16478802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
16484ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
16494ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
16504ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
16514ddc07caSPaolo Bonzini             bs_new->filename);
16524ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
16534ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
16548802d1fdSJeff Cody }
16558802d1fdSJeff Cody 
1656b338082bSbellard void bdrv_delete(BlockDriverState *bs)
1657b338082bSbellard {
1658fa879d62SMarkus Armbruster     assert(!bs->dev);
16593e914655SPaolo Bonzini     assert(!bs->job);
16603e914655SPaolo Bonzini     assert(!bs->in_use);
166118846deeSMarkus Armbruster 
1662e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1663e1b5c52eSStefan Hajnoczi 
16641b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1665d22b2f41SRyan Harper     bdrv_make_anon(bs);
166634c6f050Saurel32 
16677267c094SAnthony Liguori     g_free(bs);
1668fc01f7e7Sbellard }
1669fc01f7e7Sbellard 
1670fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1671fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
167218846deeSMarkus Armbruster {
1673fa879d62SMarkus Armbruster     if (bs->dev) {
167418846deeSMarkus Armbruster         return -EBUSY;
167518846deeSMarkus Armbruster     }
1676fa879d62SMarkus Armbruster     bs->dev = dev;
167728a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
167818846deeSMarkus Armbruster     return 0;
167918846deeSMarkus Armbruster }
168018846deeSMarkus Armbruster 
1681fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1682fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
168318846deeSMarkus Armbruster {
1684fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1685fa879d62SMarkus Armbruster         abort();
1686fa879d62SMarkus Armbruster     }
1687fa879d62SMarkus Armbruster }
1688fa879d62SMarkus Armbruster 
1689fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1690fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1691fa879d62SMarkus Armbruster {
1692fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1693fa879d62SMarkus Armbruster     bs->dev = NULL;
16940e49de52SMarkus Armbruster     bs->dev_ops = NULL;
16950e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
169629e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
169718846deeSMarkus Armbruster }
169818846deeSMarkus Armbruster 
1699fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1700fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
170118846deeSMarkus Armbruster {
1702fa879d62SMarkus Armbruster     return bs->dev;
170318846deeSMarkus Armbruster }
170418846deeSMarkus Armbruster 
17050e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
17060e49de52SMarkus Armbruster                       void *opaque)
17070e49de52SMarkus Armbruster {
17080e49de52SMarkus Armbruster     bs->dev_ops = ops;
17090e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
17100e49de52SMarkus Armbruster }
17110e49de52SMarkus Armbruster 
171232c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
171332c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
17141ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1715329c0a48SLuiz Capitulino {
1716329c0a48SLuiz Capitulino     QObject *data;
1717329c0a48SLuiz Capitulino     const char *action_str;
1718329c0a48SLuiz Capitulino 
1719329c0a48SLuiz Capitulino     switch (action) {
1720329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1721329c0a48SLuiz Capitulino         action_str = "report";
1722329c0a48SLuiz Capitulino         break;
1723329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1724329c0a48SLuiz Capitulino         action_str = "ignore";
1725329c0a48SLuiz Capitulino         break;
1726329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1727329c0a48SLuiz Capitulino         action_str = "stop";
1728329c0a48SLuiz Capitulino         break;
1729329c0a48SLuiz Capitulino     default:
1730329c0a48SLuiz Capitulino         abort();
1731329c0a48SLuiz Capitulino     }
1732329c0a48SLuiz Capitulino 
1733329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1734329c0a48SLuiz Capitulino                               bdrv->device_name,
1735329c0a48SLuiz Capitulino                               action_str,
1736329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
173732c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
1738329c0a48SLuiz Capitulino 
1739329c0a48SLuiz Capitulino     qobject_decref(data);
1740329c0a48SLuiz Capitulino }
1741329c0a48SLuiz Capitulino 
17426f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
17436f382ed2SLuiz Capitulino {
17446f382ed2SLuiz Capitulino     QObject *data;
17456f382ed2SLuiz Capitulino 
17466f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
17476f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
17486f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
17496f382ed2SLuiz Capitulino 
17506f382ed2SLuiz Capitulino     qobject_decref(data);
17516f382ed2SLuiz Capitulino }
17526f382ed2SLuiz Capitulino 
17537d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
17540e49de52SMarkus Armbruster {
1755145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
17566f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
17577d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
17586f382ed2SLuiz Capitulino         if (tray_was_closed) {
17596f382ed2SLuiz Capitulino             /* tray open */
17606f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
17616f382ed2SLuiz Capitulino         }
17626f382ed2SLuiz Capitulino         if (load) {
17636f382ed2SLuiz Capitulino             /* tray close */
17646f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
17656f382ed2SLuiz Capitulino         }
1766145feb17SMarkus Armbruster     }
1767145feb17SMarkus Armbruster }
1768145feb17SMarkus Armbruster 
17692c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
17702c6942faSMarkus Armbruster {
17712c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
17722c6942faSMarkus Armbruster }
17732c6942faSMarkus Armbruster 
1774025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1775025ccaa7SPaolo Bonzini {
1776025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1777025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1778025ccaa7SPaolo Bonzini     }
1779025ccaa7SPaolo Bonzini }
1780025ccaa7SPaolo Bonzini 
1781e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1782e4def80bSMarkus Armbruster {
1783e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1784e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1785e4def80bSMarkus Armbruster     }
1786e4def80bSMarkus Armbruster     return false;
1787e4def80bSMarkus Armbruster }
1788e4def80bSMarkus Armbruster 
1789145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1790145feb17SMarkus Armbruster {
1791145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1792145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
17930e49de52SMarkus Armbruster     }
17940e49de52SMarkus Armbruster }
17950e49de52SMarkus Armbruster 
1796f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1797f107639aSMarkus Armbruster {
1798f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1799f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1800f107639aSMarkus Armbruster     }
1801f107639aSMarkus Armbruster     return false;
1802f107639aSMarkus Armbruster }
1803f107639aSMarkus Armbruster 
1804e97fc193Saliguori /*
1805e97fc193Saliguori  * Run consistency checks on an image
1806e97fc193Saliguori  *
1807e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1808a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1809e076f338SKevin Wolf  * check are stored in res.
1810e97fc193Saliguori  */
18114534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1812e97fc193Saliguori {
1813e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1814e97fc193Saliguori         return -ENOTSUP;
1815e97fc193Saliguori     }
1816e97fc193Saliguori 
1817e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
18184534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
1819e97fc193Saliguori }
1820e97fc193Saliguori 
18218a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
18228a426614SKevin Wolf 
182333e3963eSbellard /* commit COW file into the raw image */
182433e3963eSbellard int bdrv_commit(BlockDriverState *bs)
182533e3963eSbellard {
182619cb3738Sbellard     BlockDriver *drv = bs->drv;
18278a426614SKevin Wolf     int64_t sector, total_sectors;
18288a426614SKevin Wolf     int n, ro, open_flags;
18290bce597dSJeff Cody     int ret = 0;
18308a426614SKevin Wolf     uint8_t *buf;
1831c2cba3d9SJim Meyering     char filename[PATH_MAX];
183233e3963eSbellard 
183319cb3738Sbellard     if (!drv)
183419cb3738Sbellard         return -ENOMEDIUM;
183533e3963eSbellard 
18364dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
18374dca4b63SNaphtali Sprei         return -ENOTSUP;
18384dca4b63SNaphtali Sprei     }
18394dca4b63SNaphtali Sprei 
18402d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
18412d3735d3SStefan Hajnoczi         return -EBUSY;
18422d3735d3SStefan Hajnoczi     }
18432d3735d3SStefan Hajnoczi 
18444dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
1845c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1846c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
18474dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
18484dca4b63SNaphtali Sprei 
18494dca4b63SNaphtali Sprei     if (ro) {
18500bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
18510bce597dSJeff Cody             return -EACCES;
18524dca4b63SNaphtali Sprei         }
1853ea2384d3Sbellard     }
1854ea2384d3Sbellard 
18556ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
18567267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
18578a426614SKevin Wolf 
18588a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
185905c4af54SStefan Hajnoczi         if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
18608a426614SKevin Wolf 
18618a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
18624dca4b63SNaphtali Sprei                 ret = -EIO;
18634dca4b63SNaphtali Sprei                 goto ro_cleanup;
186433e3963eSbellard             }
186533e3963eSbellard 
18668a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
18674dca4b63SNaphtali Sprei                 ret = -EIO;
18684dca4b63SNaphtali Sprei                 goto ro_cleanup;
186933e3963eSbellard             }
187033e3963eSbellard         }
187133e3963eSbellard     }
187295389c86Sbellard 
18731d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
18741d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
18751d44952fSChristoph Hellwig         bdrv_flush(bs);
18761d44952fSChristoph Hellwig     }
187795389c86Sbellard 
18783f5075aeSChristoph Hellwig     /*
18793f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
18803f5075aeSChristoph Hellwig      * stable on disk.
18813f5075aeSChristoph Hellwig      */
18823f5075aeSChristoph Hellwig     if (bs->backing_hd)
18833f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
18844dca4b63SNaphtali Sprei 
18854dca4b63SNaphtali Sprei ro_cleanup:
18867267c094SAnthony Liguori     g_free(buf);
18874dca4b63SNaphtali Sprei 
18884dca4b63SNaphtali Sprei     if (ro) {
18890bce597dSJeff Cody         /* ignoring error return here */
18900bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
18914dca4b63SNaphtali Sprei     }
18924dca4b63SNaphtali Sprei 
18931d44952fSChristoph Hellwig     return ret;
189433e3963eSbellard }
189533e3963eSbellard 
1896e8877497SStefan Hajnoczi int bdrv_commit_all(void)
18976ab4b5abSMarkus Armbruster {
18986ab4b5abSMarkus Armbruster     BlockDriverState *bs;
18996ab4b5abSMarkus Armbruster 
19006ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1901272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
1902e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
1903e8877497SStefan Hajnoczi             if (ret < 0) {
1904e8877497SStefan Hajnoczi                 return ret;
19056ab4b5abSMarkus Armbruster             }
19066ab4b5abSMarkus Armbruster         }
1907272d2d8eSJeff Cody     }
1908e8877497SStefan Hajnoczi     return 0;
1909e8877497SStefan Hajnoczi }
19106ab4b5abSMarkus Armbruster 
1911dbffbdcfSStefan Hajnoczi /**
1912dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1913dbffbdcfSStefan Hajnoczi  *
1914dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1915dbffbdcfSStefan Hajnoczi  */
1916dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1917dbffbdcfSStefan Hajnoczi {
1918dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1919f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1920dbffbdcfSStefan Hajnoczi }
1921dbffbdcfSStefan Hajnoczi 
1922dbffbdcfSStefan Hajnoczi /**
1923dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1924dbffbdcfSStefan Hajnoczi  */
1925dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1926dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1927dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1928dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1929dbffbdcfSStefan Hajnoczi {
1930dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1931dbffbdcfSStefan Hajnoczi         .bs = bs,
1932dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1933dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1934dbffbdcfSStefan Hajnoczi         .is_write = is_write,
19355f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1936dbffbdcfSStefan Hajnoczi     };
1937dbffbdcfSStefan Hajnoczi 
1938f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1939f4658285SStefan Hajnoczi 
1940dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1941dbffbdcfSStefan Hajnoczi }
1942dbffbdcfSStefan Hajnoczi 
1943d83947acSStefan Hajnoczi /**
1944d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1945d83947acSStefan Hajnoczi  */
1946343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
1947d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
1948d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
1949d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
1950d83947acSStefan Hajnoczi {
1951d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
1952d83947acSStefan Hajnoczi 
1953d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1954d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
1955d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
1956d83947acSStefan Hajnoczi     } else {
1957d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1958d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1959d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1960d83947acSStefan Hajnoczi                                             nb_sectors, c);
1961d83947acSStefan Hajnoczi     }
1962d83947acSStefan Hajnoczi }
1963d83947acSStefan Hajnoczi 
1964f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1965f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
1966d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
1967d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
1968d83947acSStefan Hajnoczi         return false;
1969d83947acSStefan Hajnoczi     }
1970d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
1971d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
1972d83947acSStefan Hajnoczi         return false;
1973d83947acSStefan Hajnoczi     }
1974d83947acSStefan Hajnoczi     return true;
1975f4658285SStefan Hajnoczi }
1976f4658285SStefan Hajnoczi 
1977f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1978f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
1979f4658285SStefan Hajnoczi {
1980f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
1981d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
1982d83947acSStefan Hajnoczi     int cluster_nb_sectors;
1983f4658285SStefan Hajnoczi     bool retry;
1984f4658285SStefan Hajnoczi 
1985d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
1986d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
1987d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
1988d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
1989d83947acSStefan Hajnoczi      * interleave between them.
1990d83947acSStefan Hajnoczi      */
1991343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
1992d83947acSStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
1993d83947acSStefan Hajnoczi 
1994f4658285SStefan Hajnoczi     do {
1995f4658285SStefan Hajnoczi         retry = false;
1996f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
1997d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
1998d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
19995f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
20005f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
20015f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
20025f8b6491SStefan Hajnoczi                  */
20035f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
20045f8b6491SStefan Hajnoczi 
2005f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
2006f4658285SStefan Hajnoczi                 retry = true;
2007f4658285SStefan Hajnoczi                 break;
2008f4658285SStefan Hajnoczi             }
2009f4658285SStefan Hajnoczi         }
2010f4658285SStefan Hajnoczi     } while (retry);
2011f4658285SStefan Hajnoczi }
2012f4658285SStefan Hajnoczi 
2013756e6736SKevin Wolf /*
2014756e6736SKevin Wolf  * Return values:
2015756e6736SKevin Wolf  * 0        - success
2016756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2017756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2018756e6736SKevin Wolf  *            image file header
2019756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2020756e6736SKevin Wolf  */
2021756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2022756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2023756e6736SKevin Wolf {
2024756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2025469ef350SPaolo Bonzini     int ret;
2026756e6736SKevin Wolf 
20275f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
20285f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
20295f377794SPaolo Bonzini         return -EINVAL;
20305f377794SPaolo Bonzini     }
20315f377794SPaolo Bonzini 
2032756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2033469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2034756e6736SKevin Wolf     } else {
2035469ef350SPaolo Bonzini         ret = -ENOTSUP;
2036756e6736SKevin Wolf     }
2037469ef350SPaolo Bonzini 
2038469ef350SPaolo Bonzini     if (ret == 0) {
2039469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2040469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2041469ef350SPaolo Bonzini     }
2042469ef350SPaolo Bonzini     return ret;
2043756e6736SKevin Wolf }
2044756e6736SKevin Wolf 
20456ebdcee2SJeff Cody /*
20466ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
20476ebdcee2SJeff Cody  *
20486ebdcee2SJeff Cody  * active is the current topmost image.
20496ebdcee2SJeff Cody  *
20506ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
20516ebdcee2SJeff Cody  * or if active == bs.
20526ebdcee2SJeff Cody  */
20536ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
20546ebdcee2SJeff Cody                                     BlockDriverState *bs)
20556ebdcee2SJeff Cody {
20566ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
20576ebdcee2SJeff Cody     BlockDriverState *intermediate;
20586ebdcee2SJeff Cody 
20596ebdcee2SJeff Cody     assert(active != NULL);
20606ebdcee2SJeff Cody     assert(bs != NULL);
20616ebdcee2SJeff Cody 
20626ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
20636ebdcee2SJeff Cody      */
20646ebdcee2SJeff Cody     if (active == bs) {
20656ebdcee2SJeff Cody         return NULL;
20666ebdcee2SJeff Cody     }
20676ebdcee2SJeff Cody 
20686ebdcee2SJeff Cody     intermediate = active;
20696ebdcee2SJeff Cody     while (intermediate->backing_hd) {
20706ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
20716ebdcee2SJeff Cody             overlay = intermediate;
20726ebdcee2SJeff Cody             break;
20736ebdcee2SJeff Cody         }
20746ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
20756ebdcee2SJeff Cody     }
20766ebdcee2SJeff Cody 
20776ebdcee2SJeff Cody     return overlay;
20786ebdcee2SJeff Cody }
20796ebdcee2SJeff Cody 
20806ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
20816ebdcee2SJeff Cody     BlockDriverState *bs;
20826ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
20836ebdcee2SJeff Cody } BlkIntermediateStates;
20846ebdcee2SJeff Cody 
20856ebdcee2SJeff Cody 
20866ebdcee2SJeff Cody /*
20876ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
20886ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
20896ebdcee2SJeff Cody  *
20906ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
20916ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
20926ebdcee2SJeff Cody  *
20936ebdcee2SJeff Cody  * E.g., this will convert the following chain:
20946ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
20956ebdcee2SJeff Cody  *
20966ebdcee2SJeff Cody  * to
20976ebdcee2SJeff Cody  *
20986ebdcee2SJeff Cody  * bottom <- base <- active
20996ebdcee2SJeff Cody  *
21006ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
21016ebdcee2SJeff Cody  *
21026ebdcee2SJeff Cody  * base <- intermediate <- top <- active
21036ebdcee2SJeff Cody  *
21046ebdcee2SJeff Cody  * to
21056ebdcee2SJeff Cody  *
21066ebdcee2SJeff Cody  * base <- active
21076ebdcee2SJeff Cody  *
21086ebdcee2SJeff Cody  * Error conditions:
21096ebdcee2SJeff Cody  *  if active == top, that is considered an error
21106ebdcee2SJeff Cody  *
21116ebdcee2SJeff Cody  */
21126ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
21136ebdcee2SJeff Cody                            BlockDriverState *base)
21146ebdcee2SJeff Cody {
21156ebdcee2SJeff Cody     BlockDriverState *intermediate;
21166ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
21176ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
21186ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
21196ebdcee2SJeff Cody     int ret = -EIO;
21206ebdcee2SJeff Cody 
21216ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
21226ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
21236ebdcee2SJeff Cody 
21246ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
21256ebdcee2SJeff Cody         goto exit;
21266ebdcee2SJeff Cody     }
21276ebdcee2SJeff Cody 
21286ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
21296ebdcee2SJeff Cody 
21306ebdcee2SJeff Cody     if (new_top_bs == NULL) {
21316ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
21326ebdcee2SJeff Cody         goto exit;
21336ebdcee2SJeff Cody     }
21346ebdcee2SJeff Cody 
21356ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
21366ebdcee2SJeff Cody      * to do, no intermediate images */
21376ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
21386ebdcee2SJeff Cody         ret = 0;
21396ebdcee2SJeff Cody         goto exit;
21406ebdcee2SJeff Cody     }
21416ebdcee2SJeff Cody 
21426ebdcee2SJeff Cody     intermediate = top;
21436ebdcee2SJeff Cody 
21446ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
21456ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
21466ebdcee2SJeff Cody      */
21476ebdcee2SJeff Cody     while (intermediate) {
21486ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
21496ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
21506ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
21516ebdcee2SJeff Cody 
21526ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
21536ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
21546ebdcee2SJeff Cody             break;
21556ebdcee2SJeff Cody         }
21566ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
21576ebdcee2SJeff Cody     }
21586ebdcee2SJeff Cody     if (base_bs == NULL) {
21596ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
21606ebdcee2SJeff Cody          * unravel everything, and exit with error */
21616ebdcee2SJeff Cody         goto exit;
21626ebdcee2SJeff Cody     }
21636ebdcee2SJeff Cody 
21646ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
21656ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
21666ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
21676ebdcee2SJeff Cody     if (ret) {
21686ebdcee2SJeff Cody         goto exit;
21696ebdcee2SJeff Cody     }
21706ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
21716ebdcee2SJeff Cody 
21726ebdcee2SJeff Cody 
21736ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
21746ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
21756ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
21766ebdcee2SJeff Cody         bdrv_delete(intermediate_state->bs);
21776ebdcee2SJeff Cody     }
21786ebdcee2SJeff Cody     ret = 0;
21796ebdcee2SJeff Cody 
21806ebdcee2SJeff Cody exit:
21816ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
21826ebdcee2SJeff Cody         g_free(intermediate_state);
21836ebdcee2SJeff Cody     }
21846ebdcee2SJeff Cody     return ret;
21856ebdcee2SJeff Cody }
21866ebdcee2SJeff Cody 
21876ebdcee2SJeff Cody 
218871d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
218971d0770cSaliguori                                    size_t size)
219071d0770cSaliguori {
219171d0770cSaliguori     int64_t len;
219271d0770cSaliguori 
219371d0770cSaliguori     if (!bdrv_is_inserted(bs))
219471d0770cSaliguori         return -ENOMEDIUM;
219571d0770cSaliguori 
219671d0770cSaliguori     if (bs->growable)
219771d0770cSaliguori         return 0;
219871d0770cSaliguori 
219971d0770cSaliguori     len = bdrv_getlength(bs);
220071d0770cSaliguori 
2201fbb7b4e0SKevin Wolf     if (offset < 0)
2202fbb7b4e0SKevin Wolf         return -EIO;
2203fbb7b4e0SKevin Wolf 
2204fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
220571d0770cSaliguori         return -EIO;
220671d0770cSaliguori 
220771d0770cSaliguori     return 0;
220871d0770cSaliguori }
220971d0770cSaliguori 
221071d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
221171d0770cSaliguori                               int nb_sectors)
221271d0770cSaliguori {
2213eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2214eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
221571d0770cSaliguori }
221671d0770cSaliguori 
22171c9805a3SStefan Hajnoczi typedef struct RwCo {
22181c9805a3SStefan Hajnoczi     BlockDriverState *bs;
22191c9805a3SStefan Hajnoczi     int64_t sector_num;
22201c9805a3SStefan Hajnoczi     int nb_sectors;
22211c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
22221c9805a3SStefan Hajnoczi     bool is_write;
22231c9805a3SStefan Hajnoczi     int ret;
22244105eaaaSPeter Lieven     BdrvRequestFlags flags;
22251c9805a3SStefan Hajnoczi } RwCo;
22261c9805a3SStefan Hajnoczi 
22271c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2228fc01f7e7Sbellard {
22291c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2230fc01f7e7Sbellard 
22311c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
22321c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
22334105eaaaSPeter Lieven                                      rwco->nb_sectors, rwco->qiov,
22344105eaaaSPeter Lieven                                      rwco->flags);
22351c9805a3SStefan Hajnoczi     } else {
22361c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
22374105eaaaSPeter Lieven                                       rwco->nb_sectors, rwco->qiov,
22384105eaaaSPeter Lieven                                       rwco->flags);
22391c9805a3SStefan Hajnoczi     }
22401c9805a3SStefan Hajnoczi }
2241e7a8a783SKevin Wolf 
22421c9805a3SStefan Hajnoczi /*
22438d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
22441c9805a3SStefan Hajnoczi  */
22458d3b1a2dSKevin Wolf static int bdrv_rwv_co(BlockDriverState *bs, int64_t sector_num,
22464105eaaaSPeter Lieven                        QEMUIOVector *qiov, bool is_write,
22474105eaaaSPeter Lieven                        BdrvRequestFlags flags)
22481c9805a3SStefan Hajnoczi {
22491c9805a3SStefan Hajnoczi     Coroutine *co;
22501c9805a3SStefan Hajnoczi     RwCo rwco = {
22511c9805a3SStefan Hajnoczi         .bs = bs,
22521c9805a3SStefan Hajnoczi         .sector_num = sector_num,
22538d3b1a2dSKevin Wolf         .nb_sectors = qiov->size >> BDRV_SECTOR_BITS,
22548d3b1a2dSKevin Wolf         .qiov = qiov,
22551c9805a3SStefan Hajnoczi         .is_write = is_write,
22561c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
22574105eaaaSPeter Lieven         .flags = flags,
22581c9805a3SStefan Hajnoczi     };
22598d3b1a2dSKevin Wolf     assert((qiov->size & (BDRV_SECTOR_SIZE - 1)) == 0);
22601c9805a3SStefan Hajnoczi 
2261498e386cSZhi Yong Wu     /**
2262498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2263498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2264498e386cSZhi Yong Wu      * if it has been enabled.
2265498e386cSZhi Yong Wu      */
2266498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2267498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2268498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2269498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2270498e386cSZhi Yong Wu     }
2271498e386cSZhi Yong Wu 
22721c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
22731c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
22741c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
22751c9805a3SStefan Hajnoczi     } else {
22761c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
22771c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
22781c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
22791c9805a3SStefan Hajnoczi             qemu_aio_wait();
22801c9805a3SStefan Hajnoczi         }
22811c9805a3SStefan Hajnoczi     }
22821c9805a3SStefan Hajnoczi     return rwco.ret;
2283e7a8a783SKevin Wolf }
2284e7a8a783SKevin Wolf 
22858d3b1a2dSKevin Wolf /*
22868d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
22878d3b1a2dSKevin Wolf  */
22888d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
22894105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
22908d3b1a2dSKevin Wolf {
22918d3b1a2dSKevin Wolf     QEMUIOVector qiov;
22928d3b1a2dSKevin Wolf     struct iovec iov = {
22938d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
22948d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
22958d3b1a2dSKevin Wolf     };
22968d3b1a2dSKevin Wolf 
22978d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
22984105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, &qiov, is_write, flags);
22998d3b1a2dSKevin Wolf }
23008d3b1a2dSKevin Wolf 
23011c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
23021c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
23031c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
23041c9805a3SStefan Hajnoczi {
23054105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
230683f64091Sbellard }
2307fc01f7e7Sbellard 
230807d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
230907d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
231007d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
231107d27a44SMarkus Armbruster {
231207d27a44SMarkus Armbruster     bool enabled;
231307d27a44SMarkus Armbruster     int ret;
231407d27a44SMarkus Armbruster 
231507d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
231607d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
23174e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
231807d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
231907d27a44SMarkus Armbruster     return ret;
232007d27a44SMarkus Armbruster }
232107d27a44SMarkus Armbruster 
232219cb3738Sbellard /* Return < 0 if error. Important errors are:
232319cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
232419cb3738Sbellard   -ENOMEDIUM   No media inserted.
232519cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
232619cb3738Sbellard   -EACCES      Trying to write a read-only device
232719cb3738Sbellard */
2328fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2329fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2330fc01f7e7Sbellard {
23314105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
233283f64091Sbellard }
233383f64091Sbellard 
23348d3b1a2dSKevin Wolf int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
23358d3b1a2dSKevin Wolf {
23364105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, qiov, true, 0);
23374105eaaaSPeter Lieven }
23384105eaaaSPeter Lieven 
23394105eaaaSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
23404105eaaaSPeter Lieven {
23414105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
23424105eaaaSPeter Lieven                       BDRV_REQ_ZERO_WRITE);
23438d3b1a2dSKevin Wolf }
23448d3b1a2dSKevin Wolf 
2345eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2346eda578e5Saliguori                void *buf, int count1)
234783f64091Sbellard {
23486ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
234983f64091Sbellard     int len, nb_sectors, count;
235083f64091Sbellard     int64_t sector_num;
23519a8c4cceSKevin Wolf     int ret;
235283f64091Sbellard 
235383f64091Sbellard     count = count1;
235483f64091Sbellard     /* first read to align to sector start */
23556ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
235683f64091Sbellard     if (len > count)
235783f64091Sbellard         len = count;
23586ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
235983f64091Sbellard     if (len > 0) {
23609a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23619a8c4cceSKevin Wolf             return ret;
23626ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
236383f64091Sbellard         count -= len;
236483f64091Sbellard         if (count == 0)
236583f64091Sbellard             return count1;
236683f64091Sbellard         sector_num++;
236783f64091Sbellard         buf += len;
236883f64091Sbellard     }
236983f64091Sbellard 
237083f64091Sbellard     /* read the sectors "in place" */
23716ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
237283f64091Sbellard     if (nb_sectors > 0) {
23739a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
23749a8c4cceSKevin Wolf             return ret;
237583f64091Sbellard         sector_num += nb_sectors;
23766ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
237783f64091Sbellard         buf += len;
237883f64091Sbellard         count -= len;
237983f64091Sbellard     }
238083f64091Sbellard 
238183f64091Sbellard     /* add data from the last sector */
238283f64091Sbellard     if (count > 0) {
23839a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23849a8c4cceSKevin Wolf             return ret;
238583f64091Sbellard         memcpy(buf, tmp_buf, count);
238683f64091Sbellard     }
238783f64091Sbellard     return count1;
238883f64091Sbellard }
238983f64091Sbellard 
23908d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
239183f64091Sbellard {
23926ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
239383f64091Sbellard     int len, nb_sectors, count;
239483f64091Sbellard     int64_t sector_num;
23959a8c4cceSKevin Wolf     int ret;
239683f64091Sbellard 
23978d3b1a2dSKevin Wolf     count = qiov->size;
23988d3b1a2dSKevin Wolf 
239983f64091Sbellard     /* first write to align to sector start */
24006ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
240183f64091Sbellard     if (len > count)
240283f64091Sbellard         len = count;
24036ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
240483f64091Sbellard     if (len > 0) {
24059a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
24069a8c4cceSKevin Wolf             return ret;
24078d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
24088d3b1a2dSKevin Wolf                           len);
24099a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
24109a8c4cceSKevin Wolf             return ret;
241183f64091Sbellard         count -= len;
241283f64091Sbellard         if (count == 0)
24138d3b1a2dSKevin Wolf             return qiov->size;
241483f64091Sbellard         sector_num++;
241583f64091Sbellard     }
241683f64091Sbellard 
241783f64091Sbellard     /* write the sectors "in place" */
24186ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
241983f64091Sbellard     if (nb_sectors > 0) {
24208d3b1a2dSKevin Wolf         QEMUIOVector qiov_inplace;
24218d3b1a2dSKevin Wolf 
24228d3b1a2dSKevin Wolf         qemu_iovec_init(&qiov_inplace, qiov->niov);
24238d3b1a2dSKevin Wolf         qemu_iovec_concat(&qiov_inplace, qiov, len,
24248d3b1a2dSKevin Wolf                           nb_sectors << BDRV_SECTOR_BITS);
24258d3b1a2dSKevin Wolf         ret = bdrv_writev(bs, sector_num, &qiov_inplace);
24268d3b1a2dSKevin Wolf         qemu_iovec_destroy(&qiov_inplace);
24278d3b1a2dSKevin Wolf         if (ret < 0) {
24289a8c4cceSKevin Wolf             return ret;
24298d3b1a2dSKevin Wolf         }
24308d3b1a2dSKevin Wolf 
243183f64091Sbellard         sector_num += nb_sectors;
24326ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
243383f64091Sbellard         count -= len;
243483f64091Sbellard     }
243583f64091Sbellard 
243683f64091Sbellard     /* add data from the last sector */
243783f64091Sbellard     if (count > 0) {
24389a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
24399a8c4cceSKevin Wolf             return ret;
24408d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
24419a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
24429a8c4cceSKevin Wolf             return ret;
244383f64091Sbellard     }
24448d3b1a2dSKevin Wolf     return qiov->size;
24458d3b1a2dSKevin Wolf }
24468d3b1a2dSKevin Wolf 
24478d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
24488d3b1a2dSKevin Wolf                 const void *buf, int count1)
24498d3b1a2dSKevin Wolf {
24508d3b1a2dSKevin Wolf     QEMUIOVector qiov;
24518d3b1a2dSKevin Wolf     struct iovec iov = {
24528d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
24538d3b1a2dSKevin Wolf         .iov_len    = count1,
24548d3b1a2dSKevin Wolf     };
24558d3b1a2dSKevin Wolf 
24568d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
24578d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
245883f64091Sbellard }
245983f64091Sbellard 
2460f08145feSKevin Wolf /*
2461f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2462f08145feSKevin Wolf  * request (acts as a barrier)
2463f08145feSKevin Wolf  *
2464f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2465f08145feSKevin Wolf  */
2466f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2467f08145feSKevin Wolf     const void *buf, int count)
2468f08145feSKevin Wolf {
2469f08145feSKevin Wolf     int ret;
2470f08145feSKevin Wolf 
2471f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2472f08145feSKevin Wolf     if (ret < 0) {
2473f08145feSKevin Wolf         return ret;
2474f08145feSKevin Wolf     }
2475f08145feSKevin Wolf 
2476f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2477f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2478f08145feSKevin Wolf         bdrv_flush(bs);
2479f08145feSKevin Wolf     }
2480f08145feSKevin Wolf 
2481f08145feSKevin Wolf     return 0;
2482f08145feSKevin Wolf }
2483f08145feSKevin Wolf 
2484470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2485ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2486ab185921SStefan Hajnoczi {
2487ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2488ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2489ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2490ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2491ab185921SStefan Hajnoczi      */
2492ab185921SStefan Hajnoczi     void *bounce_buffer;
2493ab185921SStefan Hajnoczi 
249479c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2495ab185921SStefan Hajnoczi     struct iovec iov;
2496ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2497ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2498ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2499ab185921SStefan Hajnoczi     size_t skip_bytes;
2500ab185921SStefan Hajnoczi     int ret;
2501ab185921SStefan Hajnoczi 
2502ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2503ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2504ab185921SStefan Hajnoczi      */
2505343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2506ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2507ab185921SStefan Hajnoczi 
2508470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2509ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2510ab185921SStefan Hajnoczi 
2511ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2512ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2513ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2514ab185921SStefan Hajnoczi 
251579c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2516ab185921SStefan Hajnoczi                              &bounce_qiov);
2517ab185921SStefan Hajnoczi     if (ret < 0) {
2518ab185921SStefan Hajnoczi         goto err;
2519ab185921SStefan Hajnoczi     }
2520ab185921SStefan Hajnoczi 
252179c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
252279c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2523621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
252479c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
252579c053bdSStefan Hajnoczi     } else {
2526f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2527f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2528f05fa4adSPaolo Bonzini          */
252979c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2530ab185921SStefan Hajnoczi                                   &bounce_qiov);
253179c053bdSStefan Hajnoczi     }
253279c053bdSStefan Hajnoczi 
2533ab185921SStefan Hajnoczi     if (ret < 0) {
2534ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2535ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2536ab185921SStefan Hajnoczi          * Simply report it in all cases.
2537ab185921SStefan Hajnoczi          */
2538ab185921SStefan Hajnoczi         goto err;
2539ab185921SStefan Hajnoczi     }
2540ab185921SStefan Hajnoczi 
2541ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
254203396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2543ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2544ab185921SStefan Hajnoczi 
2545ab185921SStefan Hajnoczi err:
2546ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2547ab185921SStefan Hajnoczi     return ret;
2548ab185921SStefan Hajnoczi }
2549ab185921SStefan Hajnoczi 
2550c5fbe571SStefan Hajnoczi /*
2551c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
2552c5fbe571SStefan Hajnoczi  */
2553c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2554470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2555470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
2556da1fa91dSKevin Wolf {
2557da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2558dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
2559dbffbdcfSStefan Hajnoczi     int ret;
2560da1fa91dSKevin Wolf 
2561da1fa91dSKevin Wolf     if (!drv) {
2562da1fa91dSKevin Wolf         return -ENOMEDIUM;
2563da1fa91dSKevin Wolf     }
2564da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2565da1fa91dSKevin Wolf         return -EIO;
2566da1fa91dSKevin Wolf     }
2567da1fa91dSKevin Wolf 
2568f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
2569470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
2570470c0504SStefan Hajnoczi     }
2571470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2572470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
2573470c0504SStefan Hajnoczi     }
2574470c0504SStefan Hajnoczi 
2575470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2576f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2577f4658285SStefan Hajnoczi     }
2578f4658285SStefan Hajnoczi 
2579cc0681c4SBenoît Canet     /* throttling disk I/O */
2580cc0681c4SBenoît Canet     if (bs->io_limits_enabled) {
2581cc0681c4SBenoît Canet         bdrv_io_limits_intercept(bs, nb_sectors, false);
2582cc0681c4SBenoît Canet     }
2583cc0681c4SBenoît Canet 
2584dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2585ab185921SStefan Hajnoczi 
2586470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2587ab185921SStefan Hajnoczi         int pnum;
2588ab185921SStefan Hajnoczi 
2589ab185921SStefan Hajnoczi         ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2590ab185921SStefan Hajnoczi         if (ret < 0) {
2591ab185921SStefan Hajnoczi             goto out;
2592ab185921SStefan Hajnoczi         }
2593ab185921SStefan Hajnoczi 
2594ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2595470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2596ab185921SStefan Hajnoczi             goto out;
2597ab185921SStefan Hajnoczi         }
2598ab185921SStefan Hajnoczi     }
2599ab185921SStefan Hajnoczi 
2600893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2601dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2602893a8f62SMORITA Kazutaka     } else {
2603893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2604893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2605893a8f62SMORITA Kazutaka 
2606893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2607893a8f62SMORITA Kazutaka         if (len < 0) {
2608893a8f62SMORITA Kazutaka             ret = len;
2609893a8f62SMORITA Kazutaka             goto out;
2610893a8f62SMORITA Kazutaka         }
2611893a8f62SMORITA Kazutaka 
2612893a8f62SMORITA Kazutaka         total_sectors = len >> BDRV_SECTOR_BITS;
2613893a8f62SMORITA Kazutaka         max_nb_sectors = MAX(0, total_sectors - sector_num);
2614893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
2615893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
2616893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
2617893a8f62SMORITA Kazutaka         } else {
2618893a8f62SMORITA Kazutaka             ret = 0;
2619893a8f62SMORITA Kazutaka         }
2620893a8f62SMORITA Kazutaka 
2621893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
2622893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2623893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
2624893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
2625893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
2626893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
2627893a8f62SMORITA Kazutaka         }
2628893a8f62SMORITA Kazutaka     }
2629ab185921SStefan Hajnoczi 
2630ab185921SStefan Hajnoczi out:
2631dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2632470c0504SStefan Hajnoczi 
2633470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2634470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
2635470c0504SStefan Hajnoczi     }
2636470c0504SStefan Hajnoczi 
2637dbffbdcfSStefan Hajnoczi     return ret;
2638da1fa91dSKevin Wolf }
2639da1fa91dSKevin Wolf 
2640c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2641da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
2642da1fa91dSKevin Wolf {
2643c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2644da1fa91dSKevin Wolf 
2645470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2646470c0504SStefan Hajnoczi }
2647470c0504SStefan Hajnoczi 
2648470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2649470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2650470c0504SStefan Hajnoczi {
2651470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2652470c0504SStefan Hajnoczi 
2653470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2654470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
2655c5fbe571SStefan Hajnoczi }
2656c5fbe571SStefan Hajnoczi 
2657f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2658f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
2659f08f2ddaSStefan Hajnoczi {
2660f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2661f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
2662f08f2ddaSStefan Hajnoczi     struct iovec iov;
2663f08f2ddaSStefan Hajnoczi     int ret;
2664f08f2ddaSStefan Hajnoczi 
2665621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
2666621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
2667621f0589SKevin Wolf 
2668f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
2669f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
2670621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2671621f0589SKevin Wolf         if (ret != -ENOTSUP) {
2672621f0589SKevin Wolf             return ret;
2673621f0589SKevin Wolf         }
2674f08f2ddaSStefan Hajnoczi     }
2675f08f2ddaSStefan Hajnoczi 
2676f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
2677f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
2678f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2679f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
2680f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
2681f08f2ddaSStefan Hajnoczi 
2682f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2683f08f2ddaSStefan Hajnoczi 
2684f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
2685f08f2ddaSStefan Hajnoczi     return ret;
2686f08f2ddaSStefan Hajnoczi }
2687f08f2ddaSStefan Hajnoczi 
2688c5fbe571SStefan Hajnoczi /*
2689c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
2690c5fbe571SStefan Hajnoczi  */
2691c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2692f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2693f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
2694c5fbe571SStefan Hajnoczi {
2695c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
2696dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
26976b7cb247SStefan Hajnoczi     int ret;
2698da1fa91dSKevin Wolf 
2699da1fa91dSKevin Wolf     if (!bs->drv) {
2700da1fa91dSKevin Wolf         return -ENOMEDIUM;
2701da1fa91dSKevin Wolf     }
2702da1fa91dSKevin Wolf     if (bs->read_only) {
2703da1fa91dSKevin Wolf         return -EACCES;
2704da1fa91dSKevin Wolf     }
2705da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2706da1fa91dSKevin Wolf         return -EIO;
2707da1fa91dSKevin Wolf     }
2708da1fa91dSKevin Wolf 
2709470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2710f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2711f4658285SStefan Hajnoczi     }
2712f4658285SStefan Hajnoczi 
2713cc0681c4SBenoît Canet     /* throttling disk I/O */
2714cc0681c4SBenoît Canet     if (bs->io_limits_enabled) {
2715cc0681c4SBenoît Canet         bdrv_io_limits_intercept(bs, nb_sectors, true);
2716cc0681c4SBenoît Canet     }
2717cc0681c4SBenoît Canet 
2718dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2719dbffbdcfSStefan Hajnoczi 
2720d616b224SStefan Hajnoczi     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2721d616b224SStefan Hajnoczi 
2722d616b224SStefan Hajnoczi     if (ret < 0) {
2723d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
2724d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
2725f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2726f08f2ddaSStefan Hajnoczi     } else {
27276b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2728f08f2ddaSStefan Hajnoczi     }
27296b7cb247SStefan Hajnoczi 
2730f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
2731f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
2732f05fa4adSPaolo Bonzini     }
2733f05fa4adSPaolo Bonzini 
2734da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
27351755da16SPaolo Bonzini         bdrv_set_dirty(bs, sector_num, nb_sectors);
2736da1fa91dSKevin Wolf     }
2737da1fa91dSKevin Wolf 
2738da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2739da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
2740da1fa91dSKevin Wolf     }
2741da1fa91dSKevin Wolf 
2742dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2743dbffbdcfSStefan Hajnoczi 
27446b7cb247SStefan Hajnoczi     return ret;
2745da1fa91dSKevin Wolf }
2746da1fa91dSKevin Wolf 
2747c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2748c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
2749c5fbe571SStefan Hajnoczi {
2750c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2751c5fbe571SStefan Hajnoczi 
2752f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2753f08f2ddaSStefan Hajnoczi }
2754f08f2ddaSStefan Hajnoczi 
2755f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2756f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
2757f08f2ddaSStefan Hajnoczi {
2758f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2759f08f2ddaSStefan Hajnoczi 
2760f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2761f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
2762c5fbe571SStefan Hajnoczi }
2763c5fbe571SStefan Hajnoczi 
276483f64091Sbellard /**
276583f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
276683f64091Sbellard  */
276783f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
276883f64091Sbellard {
276983f64091Sbellard     BlockDriver *drv = bs->drv;
277051762288SStefan Hajnoczi     int ret;
277183f64091Sbellard     if (!drv)
277219cb3738Sbellard         return -ENOMEDIUM;
277383f64091Sbellard     if (!drv->bdrv_truncate)
277483f64091Sbellard         return -ENOTSUP;
277559f2689dSNaphtali Sprei     if (bs->read_only)
277659f2689dSNaphtali Sprei         return -EACCES;
27778591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
27788591675fSMarcelo Tosatti         return -EBUSY;
277951762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
278051762288SStefan Hajnoczi     if (ret == 0) {
278151762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2782145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
278351762288SStefan Hajnoczi     }
278451762288SStefan Hajnoczi     return ret;
278583f64091Sbellard }
278683f64091Sbellard 
278783f64091Sbellard /**
27884a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
27894a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
27904a1d5e1fSFam Zheng  */
27914a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
27924a1d5e1fSFam Zheng {
27934a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
27944a1d5e1fSFam Zheng     if (!drv) {
27954a1d5e1fSFam Zheng         return -ENOMEDIUM;
27964a1d5e1fSFam Zheng     }
27974a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
27984a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
27994a1d5e1fSFam Zheng     }
28004a1d5e1fSFam Zheng     if (bs->file) {
28014a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
28024a1d5e1fSFam Zheng     }
28034a1d5e1fSFam Zheng     return -ENOTSUP;
28044a1d5e1fSFam Zheng }
28054a1d5e1fSFam Zheng 
28064a1d5e1fSFam Zheng /**
280783f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
280883f64091Sbellard  */
280983f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
281083f64091Sbellard {
281183f64091Sbellard     BlockDriver *drv = bs->drv;
281283f64091Sbellard     if (!drv)
281319cb3738Sbellard         return -ENOMEDIUM;
281451762288SStefan Hajnoczi 
28152c6942faSMarkus Armbruster     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
281646a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
281783f64091Sbellard             return drv->bdrv_getlength(bs);
2818fc01f7e7Sbellard         }
281946a4e4e6SStefan Hajnoczi     }
282046a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
282146a4e4e6SStefan Hajnoczi }
2822fc01f7e7Sbellard 
282319cb3738Sbellard /* return 0 as number of sectors if no device present or error */
282496b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2825fc01f7e7Sbellard {
282619cb3738Sbellard     int64_t length;
282719cb3738Sbellard     length = bdrv_getlength(bs);
282819cb3738Sbellard     if (length < 0)
282919cb3738Sbellard         length = 0;
283019cb3738Sbellard     else
28316ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
283219cb3738Sbellard     *nb_sectors_ptr = length;
2833fc01f7e7Sbellard }
2834cf98951bSbellard 
2835ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2836ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2837abd7f68dSMarkus Armbruster {
2838abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2839abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2840abd7f68dSMarkus Armbruster }
2841abd7f68dSMarkus Armbruster 
28421ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2843abd7f68dSMarkus Armbruster {
2844abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2845abd7f68dSMarkus Armbruster }
2846abd7f68dSMarkus Armbruster 
28473e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
28483e1caa5fSPaolo Bonzini {
28493e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
28503e1caa5fSPaolo Bonzini 
28513e1caa5fSPaolo Bonzini     switch (on_err) {
28523e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
28533e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
28543e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
28553e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
28563e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
28573e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
28583e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
28593e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
28603e1caa5fSPaolo Bonzini     default:
28613e1caa5fSPaolo Bonzini         abort();
28623e1caa5fSPaolo Bonzini     }
28633e1caa5fSPaolo Bonzini }
28643e1caa5fSPaolo Bonzini 
28653e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
28663e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
28673e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
28683e1caa5fSPaolo Bonzini  */
28693e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
28703e1caa5fSPaolo Bonzini                        bool is_read, int error)
28713e1caa5fSPaolo Bonzini {
28723e1caa5fSPaolo Bonzini     assert(error >= 0);
287332c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
28743e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
28753e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
28763e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
28773e1caa5fSPaolo Bonzini     }
28783e1caa5fSPaolo Bonzini }
28793e1caa5fSPaolo Bonzini 
2880b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2881b338082bSbellard {
2882b338082bSbellard     return bs->read_only;
2883b338082bSbellard }
2884b338082bSbellard 
2885985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2886985a03b0Sths {
2887985a03b0Sths     return bs->sg;
2888985a03b0Sths }
2889985a03b0Sths 
2890e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2891e900a7b7SChristoph Hellwig {
2892e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2893e900a7b7SChristoph Hellwig }
2894e900a7b7SChristoph Hellwig 
2895425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2896425b0148SPaolo Bonzini {
2897425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
289855b110f2SJeff Cody 
289955b110f2SJeff Cody     /* so a reopen() will preserve wce */
290055b110f2SJeff Cody     if (wce) {
290155b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
290255b110f2SJeff Cody     } else {
290355b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
290455b110f2SJeff Cody     }
2905425b0148SPaolo Bonzini }
2906425b0148SPaolo Bonzini 
2907ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2908ea2384d3Sbellard {
2909ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2910ea2384d3Sbellard         return 1;
2911ea2384d3Sbellard     return bs->encrypted;
2912ea2384d3Sbellard }
2913ea2384d3Sbellard 
2914c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2915c0f4ce77Saliguori {
2916c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2917c0f4ce77Saliguori 
2918c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2919c0f4ce77Saliguori         return 1;
2920c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2921c0f4ce77Saliguori }
2922c0f4ce77Saliguori 
2923ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2924ea2384d3Sbellard {
2925ea2384d3Sbellard     int ret;
2926ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2927ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2928ea2384d3Sbellard         if (ret < 0)
2929ea2384d3Sbellard             return ret;
2930ea2384d3Sbellard         if (!bs->encrypted)
2931ea2384d3Sbellard             return 0;
2932ea2384d3Sbellard     }
2933fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2934fd04a2aeSShahar Havivi         return -EINVAL;
2935fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2936fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2937fd04a2aeSShahar Havivi     }
2938c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2939bb5fc20fSaliguori     if (ret < 0) {
2940bb5fc20fSaliguori         bs->valid_key = 0;
2941bb5fc20fSaliguori     } else if (!bs->valid_key) {
2942bb5fc20fSaliguori         bs->valid_key = 1;
2943bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
29447d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
2945bb5fc20fSaliguori     }
2946c0f4ce77Saliguori     return ret;
2947ea2384d3Sbellard }
2948ea2384d3Sbellard 
2949f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2950ea2384d3Sbellard {
2951f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2952ea2384d3Sbellard }
2953ea2384d3Sbellard 
2954ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2955ea2384d3Sbellard                          void *opaque)
2956ea2384d3Sbellard {
2957ea2384d3Sbellard     BlockDriver *drv;
2958ea2384d3Sbellard 
29598a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2960ea2384d3Sbellard         it(opaque, drv->format_name);
2961ea2384d3Sbellard     }
2962ea2384d3Sbellard }
2963ea2384d3Sbellard 
2964b338082bSbellard BlockDriverState *bdrv_find(const char *name)
2965b338082bSbellard {
2966b338082bSbellard     BlockDriverState *bs;
2967b338082bSbellard 
29681b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
29691b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
2970b338082bSbellard             return bs;
2971b338082bSbellard         }
29721b7bdbc1SStefan Hajnoczi     }
2973b338082bSbellard     return NULL;
2974b338082bSbellard }
2975b338082bSbellard 
29762f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
29772f399b0aSMarkus Armbruster {
29782f399b0aSMarkus Armbruster     if (!bs) {
29792f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
29802f399b0aSMarkus Armbruster     }
29812f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
29822f399b0aSMarkus Armbruster }
29832f399b0aSMarkus Armbruster 
298451de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
298581d0912dSbellard {
298681d0912dSbellard     BlockDriverState *bs;
298781d0912dSbellard 
29881b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
298951de9760Saliguori         it(opaque, bs);
299081d0912dSbellard     }
299181d0912dSbellard }
299281d0912dSbellard 
2993ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
2994ea2384d3Sbellard {
2995ea2384d3Sbellard     return bs->device_name;
2996ea2384d3Sbellard }
2997ea2384d3Sbellard 
2998c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2999c8433287SMarkus Armbruster {
3000c8433287SMarkus Armbruster     return bs->open_flags;
3001c8433287SMarkus Armbruster }
3002c8433287SMarkus Armbruster 
3003f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3004c6ca28d6Saliguori {
3005c6ca28d6Saliguori     BlockDriverState *bs;
3006f0f0fdfeSKevin Wolf     int result = 0;
3007c6ca28d6Saliguori 
30081b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
3009f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
3010f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3011f0f0fdfeSKevin Wolf             result = ret;
3012c6ca28d6Saliguori         }
30131b7bdbc1SStefan Hajnoczi     }
3014c6ca28d6Saliguori 
3015f0f0fdfeSKevin Wolf     return result;
3016f0f0fdfeSKevin Wolf }
3017f0f0fdfeSKevin Wolf 
30183ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
30193ac21627SPeter Lieven {
30203ac21627SPeter Lieven     return 1;
30213ac21627SPeter Lieven }
30223ac21627SPeter Lieven 
3023f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3024f2feebbdSKevin Wolf {
3025f2feebbdSKevin Wolf     assert(bs->drv);
3026f2feebbdSKevin Wolf 
3027336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3028336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3029f2feebbdSKevin Wolf     }
3030f2feebbdSKevin Wolf 
30313ac21627SPeter Lieven     /* safe default */
30323ac21627SPeter Lieven     return 0;
3033f2feebbdSKevin Wolf }
3034f2feebbdSKevin Wolf 
3035376ae3f1SStefan Hajnoczi typedef struct BdrvCoIsAllocatedData {
3036376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3037b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3038376ae3f1SStefan Hajnoczi     int64_t sector_num;
3039376ae3f1SStefan Hajnoczi     int nb_sectors;
3040376ae3f1SStefan Hajnoczi     int *pnum;
3041376ae3f1SStefan Hajnoczi     int ret;
3042376ae3f1SStefan Hajnoczi     bool done;
3043376ae3f1SStefan Hajnoczi } BdrvCoIsAllocatedData;
3044376ae3f1SStefan Hajnoczi 
3045f58c7b35Sths /*
3046f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3047f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3048f58c7b35Sths  * hence all their sectors are reported as allocated.
3049f58c7b35Sths  *
3050bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3051bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3052bd9533e3SStefan Hajnoczi  *
3053f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3054f58c7b35Sths  * the specified sector) that are known to be in the same
3055f58c7b35Sths  * allocated/unallocated state.
3056f58c7b35Sths  *
3057bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3058bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3059f58c7b35Sths  */
3060060f51c9SStefan Hajnoczi int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
3061060f51c9SStefan Hajnoczi                                       int nb_sectors, int *pnum)
3062f58c7b35Sths {
3063f58c7b35Sths     int64_t n;
3064bd9533e3SStefan Hajnoczi 
30656aebab14SStefan Hajnoczi     if (sector_num >= bs->total_sectors) {
30666aebab14SStefan Hajnoczi         *pnum = 0;
30676aebab14SStefan Hajnoczi         return 0;
30686aebab14SStefan Hajnoczi     }
3069bd9533e3SStefan Hajnoczi 
30706aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3071bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3072bd9533e3SStefan Hajnoczi         nb_sectors = n;
3073bd9533e3SStefan Hajnoczi     }
3074bd9533e3SStefan Hajnoczi 
3075bd9533e3SStefan Hajnoczi     if (!bs->drv->bdrv_co_is_allocated) {
3076bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
30776aebab14SStefan Hajnoczi         return 1;
30786aebab14SStefan Hajnoczi     }
30796aebab14SStefan Hajnoczi 
3080060f51c9SStefan Hajnoczi     return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
3081060f51c9SStefan Hajnoczi }
3082060f51c9SStefan Hajnoczi 
3083060f51c9SStefan Hajnoczi /* Coroutine wrapper for bdrv_is_allocated() */
3084060f51c9SStefan Hajnoczi static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
3085060f51c9SStefan Hajnoczi {
3086060f51c9SStefan Hajnoczi     BdrvCoIsAllocatedData *data = opaque;
3087060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3088060f51c9SStefan Hajnoczi 
3089060f51c9SStefan Hajnoczi     data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
3090060f51c9SStefan Hajnoczi                                      data->pnum);
3091060f51c9SStefan Hajnoczi     data->done = true;
3092060f51c9SStefan Hajnoczi }
3093060f51c9SStefan Hajnoczi 
3094060f51c9SStefan Hajnoczi /*
3095060f51c9SStefan Hajnoczi  * Synchronous wrapper around bdrv_co_is_allocated().
3096060f51c9SStefan Hajnoczi  *
3097060f51c9SStefan Hajnoczi  * See bdrv_co_is_allocated() for details.
3098060f51c9SStefan Hajnoczi  */
3099060f51c9SStefan Hajnoczi int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
3100060f51c9SStefan Hajnoczi                       int *pnum)
3101060f51c9SStefan Hajnoczi {
3102376ae3f1SStefan Hajnoczi     Coroutine *co;
3103376ae3f1SStefan Hajnoczi     BdrvCoIsAllocatedData data = {
3104376ae3f1SStefan Hajnoczi         .bs = bs,
3105376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3106376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3107376ae3f1SStefan Hajnoczi         .pnum = pnum,
3108376ae3f1SStefan Hajnoczi         .done = false,
3109376ae3f1SStefan Hajnoczi     };
3110376ae3f1SStefan Hajnoczi 
3111376ae3f1SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
3112376ae3f1SStefan Hajnoczi     qemu_coroutine_enter(co, &data);
3113376ae3f1SStefan Hajnoczi     while (!data.done) {
3114376ae3f1SStefan Hajnoczi         qemu_aio_wait();
3115376ae3f1SStefan Hajnoczi     }
3116376ae3f1SStefan Hajnoczi     return data.ret;
3117376ae3f1SStefan Hajnoczi }
3118f58c7b35Sths 
3119188a7bbfSPaolo Bonzini /*
3120188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3121188a7bbfSPaolo Bonzini  *
3122188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3123188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3124188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3125188a7bbfSPaolo Bonzini  *
3126188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3127188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3128188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3129188a7bbfSPaolo Bonzini  *
3130188a7bbfSPaolo Bonzini  */
3131188a7bbfSPaolo Bonzini int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
3132188a7bbfSPaolo Bonzini                                             BlockDriverState *base,
3133188a7bbfSPaolo Bonzini                                             int64_t sector_num,
3134188a7bbfSPaolo Bonzini                                             int nb_sectors, int *pnum)
3135188a7bbfSPaolo Bonzini {
3136188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3137188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3138188a7bbfSPaolo Bonzini 
3139188a7bbfSPaolo Bonzini     intermediate = top;
3140188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3141188a7bbfSPaolo Bonzini         int pnum_inter;
3142188a7bbfSPaolo Bonzini         ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
3143188a7bbfSPaolo Bonzini                                    &pnum_inter);
3144188a7bbfSPaolo Bonzini         if (ret < 0) {
3145188a7bbfSPaolo Bonzini             return ret;
3146188a7bbfSPaolo Bonzini         } else if (ret) {
3147188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3148188a7bbfSPaolo Bonzini             return 1;
3149188a7bbfSPaolo Bonzini         }
3150188a7bbfSPaolo Bonzini 
3151188a7bbfSPaolo Bonzini         /*
3152188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3153188a7bbfSPaolo Bonzini          * might have
3154188a7bbfSPaolo Bonzini          *
3155188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3156188a7bbfSPaolo Bonzini          */
315763ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
315863ba17d3SVishvananda Ishaya             (intermediate == top ||
315963ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3160188a7bbfSPaolo Bonzini             n = pnum_inter;
3161188a7bbfSPaolo Bonzini         }
3162188a7bbfSPaolo Bonzini 
3163188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3164188a7bbfSPaolo Bonzini     }
3165188a7bbfSPaolo Bonzini 
3166188a7bbfSPaolo Bonzini     *pnum = n;
3167188a7bbfSPaolo Bonzini     return 0;
3168188a7bbfSPaolo Bonzini }
3169188a7bbfSPaolo Bonzini 
3170b35b2bbaSMiroslav Rezanina /* Coroutine wrapper for bdrv_is_allocated_above() */
3171b35b2bbaSMiroslav Rezanina static void coroutine_fn bdrv_is_allocated_above_co_entry(void *opaque)
3172b35b2bbaSMiroslav Rezanina {
3173b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData *data = opaque;
3174b35b2bbaSMiroslav Rezanina     BlockDriverState *top = data->bs;
3175b35b2bbaSMiroslav Rezanina     BlockDriverState *base = data->base;
3176b35b2bbaSMiroslav Rezanina 
3177b35b2bbaSMiroslav Rezanina     data->ret = bdrv_co_is_allocated_above(top, base, data->sector_num,
3178b35b2bbaSMiroslav Rezanina                                            data->nb_sectors, data->pnum);
3179b35b2bbaSMiroslav Rezanina     data->done = true;
3180b35b2bbaSMiroslav Rezanina }
3181b35b2bbaSMiroslav Rezanina 
3182b35b2bbaSMiroslav Rezanina /*
3183b35b2bbaSMiroslav Rezanina  * Synchronous wrapper around bdrv_co_is_allocated_above().
3184b35b2bbaSMiroslav Rezanina  *
3185b35b2bbaSMiroslav Rezanina  * See bdrv_co_is_allocated_above() for details.
3186b35b2bbaSMiroslav Rezanina  */
3187b35b2bbaSMiroslav Rezanina int bdrv_is_allocated_above(BlockDriverState *top, BlockDriverState *base,
3188b35b2bbaSMiroslav Rezanina                             int64_t sector_num, int nb_sectors, int *pnum)
3189b35b2bbaSMiroslav Rezanina {
3190b35b2bbaSMiroslav Rezanina     Coroutine *co;
3191b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData data = {
3192b35b2bbaSMiroslav Rezanina         .bs = top,
3193b35b2bbaSMiroslav Rezanina         .base = base,
3194b35b2bbaSMiroslav Rezanina         .sector_num = sector_num,
3195b35b2bbaSMiroslav Rezanina         .nb_sectors = nb_sectors,
3196b35b2bbaSMiroslav Rezanina         .pnum = pnum,
3197b35b2bbaSMiroslav Rezanina         .done = false,
3198b35b2bbaSMiroslav Rezanina     };
3199b35b2bbaSMiroslav Rezanina 
3200b35b2bbaSMiroslav Rezanina     co = qemu_coroutine_create(bdrv_is_allocated_above_co_entry);
3201b35b2bbaSMiroslav Rezanina     qemu_coroutine_enter(co, &data);
3202b35b2bbaSMiroslav Rezanina     while (!data.done) {
3203b35b2bbaSMiroslav Rezanina         qemu_aio_wait();
3204b35b2bbaSMiroslav Rezanina     }
3205b35b2bbaSMiroslav Rezanina     return data.ret;
3206b35b2bbaSMiroslav Rezanina }
3207b35b2bbaSMiroslav Rezanina 
3208045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3209045df330Saliguori {
3210045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3211045df330Saliguori         return bs->backing_file;
3212045df330Saliguori     else if (bs->encrypted)
3213045df330Saliguori         return bs->filename;
3214045df330Saliguori     else
3215045df330Saliguori         return NULL;
3216045df330Saliguori }
3217045df330Saliguori 
321883f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
321983f64091Sbellard                                char *filename, int filename_size)
322083f64091Sbellard {
322183f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
322283f64091Sbellard }
322383f64091Sbellard 
3224faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3225faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3226faea38e7Sbellard {
3227faea38e7Sbellard     BlockDriver *drv = bs->drv;
3228faea38e7Sbellard     if (!drv)
322919cb3738Sbellard         return -ENOMEDIUM;
3230faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3231faea38e7Sbellard         return -ENOTSUP;
3232fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3233fbb7b4e0SKevin Wolf         return -EIO;
32347cd1e32aSlirans@il.ibm.com 
32351755da16SPaolo Bonzini     assert(!bs->dirty_bitmap);
32367cd1e32aSlirans@il.ibm.com 
3237faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3238faea38e7Sbellard }
3239faea38e7Sbellard 
3240faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3241faea38e7Sbellard {
3242faea38e7Sbellard     BlockDriver *drv = bs->drv;
3243faea38e7Sbellard     if (!drv)
324419cb3738Sbellard         return -ENOMEDIUM;
3245faea38e7Sbellard     if (!drv->bdrv_get_info)
3246faea38e7Sbellard         return -ENOTSUP;
3247faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3248faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3249faea38e7Sbellard }
3250faea38e7Sbellard 
325145566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
325245566e9cSChristoph Hellwig                       int64_t pos, int size)
3253178e08a5Saliguori {
3254cf8074b3SKevin Wolf     QEMUIOVector qiov;
3255cf8074b3SKevin Wolf     struct iovec iov = {
3256cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
3257cf8074b3SKevin Wolf         .iov_len    = size,
3258cf8074b3SKevin Wolf     };
3259cf8074b3SKevin Wolf 
3260cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
3261cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
3262cf8074b3SKevin Wolf }
3263cf8074b3SKevin Wolf 
3264cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3265cf8074b3SKevin Wolf {
3266178e08a5Saliguori     BlockDriver *drv = bs->drv;
3267cf8074b3SKevin Wolf 
3268cf8074b3SKevin Wolf     if (!drv) {
3269178e08a5Saliguori         return -ENOMEDIUM;
3270cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
3271cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
3272cf8074b3SKevin Wolf     } else if (bs->file) {
3273cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
3274cf8074b3SKevin Wolf     }
3275cf8074b3SKevin Wolf 
32767cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3277178e08a5Saliguori }
3278178e08a5Saliguori 
327945566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
328045566e9cSChristoph Hellwig                       int64_t pos, int size)
3281178e08a5Saliguori {
3282178e08a5Saliguori     BlockDriver *drv = bs->drv;
3283178e08a5Saliguori     if (!drv)
3284178e08a5Saliguori         return -ENOMEDIUM;
32857cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
328645566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
32877cdb1f6dSMORITA Kazutaka     if (bs->file)
32887cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
32897cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3290178e08a5Saliguori }
3291178e08a5Saliguori 
32928b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
32938b9b0cc2SKevin Wolf {
3294bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
32958b9b0cc2SKevin Wolf         return;
32968b9b0cc2SKevin Wolf     }
32978b9b0cc2SKevin Wolf 
3298bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
329941c695c7SKevin Wolf }
33008b9b0cc2SKevin Wolf 
330141c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
330241c695c7SKevin Wolf                           const char *tag)
330341c695c7SKevin Wolf {
330441c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
330541c695c7SKevin Wolf         bs = bs->file;
330641c695c7SKevin Wolf     }
330741c695c7SKevin Wolf 
330841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
330941c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
331041c695c7SKevin Wolf     }
331141c695c7SKevin Wolf 
331241c695c7SKevin Wolf     return -ENOTSUP;
331341c695c7SKevin Wolf }
331441c695c7SKevin Wolf 
331541c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
331641c695c7SKevin Wolf {
331741c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
331841c695c7SKevin Wolf         bs = bs->file;
331941c695c7SKevin Wolf     }
332041c695c7SKevin Wolf 
332141c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
332241c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
332341c695c7SKevin Wolf     }
332441c695c7SKevin Wolf 
332541c695c7SKevin Wolf     return -ENOTSUP;
332641c695c7SKevin Wolf }
332741c695c7SKevin Wolf 
332841c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
332941c695c7SKevin Wolf {
333041c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
333141c695c7SKevin Wolf         bs = bs->file;
333241c695c7SKevin Wolf     }
333341c695c7SKevin Wolf 
333441c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
333541c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
333641c695c7SKevin Wolf     }
333741c695c7SKevin Wolf 
333841c695c7SKevin Wolf     return false;
33398b9b0cc2SKevin Wolf }
33408b9b0cc2SKevin Wolf 
3341199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3342199630b6SBlue Swirl {
3343199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3344199630b6SBlue Swirl }
3345199630b6SBlue Swirl 
3346b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3347b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3348b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3349b1b1d783SJeff Cody  * the CWD rather than the chain. */
3350e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3351e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3352e8a6bb9cSMarcelo Tosatti {
3353b1b1d783SJeff Cody     char *filename_full = NULL;
3354b1b1d783SJeff Cody     char *backing_file_full = NULL;
3355b1b1d783SJeff Cody     char *filename_tmp = NULL;
3356b1b1d783SJeff Cody     int is_protocol = 0;
3357b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3358b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3359b1b1d783SJeff Cody 
3360b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3361e8a6bb9cSMarcelo Tosatti         return NULL;
3362e8a6bb9cSMarcelo Tosatti     }
3363e8a6bb9cSMarcelo Tosatti 
3364b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3365b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3366b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3367b1b1d783SJeff Cody 
3368b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3369b1b1d783SJeff Cody 
3370b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3371b1b1d783SJeff Cody 
3372b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3373b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3374b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3375b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3376b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3377b1b1d783SJeff Cody                 break;
3378b1b1d783SJeff Cody             }
3379e8a6bb9cSMarcelo Tosatti         } else {
3380b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3381b1b1d783SJeff Cody              * image's filename path */
3382b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3383b1b1d783SJeff Cody                          backing_file);
3384b1b1d783SJeff Cody 
3385b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3386b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3387b1b1d783SJeff Cody                 continue;
3388b1b1d783SJeff Cody             }
3389b1b1d783SJeff Cody 
3390b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3391b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3392b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3393b1b1d783SJeff Cody                          curr_bs->backing_file);
3394b1b1d783SJeff Cody 
3395b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3396b1b1d783SJeff Cody                 continue;
3397b1b1d783SJeff Cody             }
3398b1b1d783SJeff Cody 
3399b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3400b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3401b1b1d783SJeff Cody                 break;
3402b1b1d783SJeff Cody             }
3403e8a6bb9cSMarcelo Tosatti         }
3404e8a6bb9cSMarcelo Tosatti     }
3405e8a6bb9cSMarcelo Tosatti 
3406b1b1d783SJeff Cody     g_free(filename_full);
3407b1b1d783SJeff Cody     g_free(backing_file_full);
3408b1b1d783SJeff Cody     g_free(filename_tmp);
3409b1b1d783SJeff Cody     return retval;
3410e8a6bb9cSMarcelo Tosatti }
3411e8a6bb9cSMarcelo Tosatti 
3412f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3413f198fd1cSBenoît Canet {
3414f198fd1cSBenoît Canet     if (!bs->drv) {
3415f198fd1cSBenoît Canet         return 0;
3416f198fd1cSBenoît Canet     }
3417f198fd1cSBenoît Canet 
3418f198fd1cSBenoît Canet     if (!bs->backing_hd) {
3419f198fd1cSBenoît Canet         return 0;
3420f198fd1cSBenoît Canet     }
3421f198fd1cSBenoît Canet 
3422f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3423f198fd1cSBenoît Canet }
3424f198fd1cSBenoît Canet 
342579fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
342679fac568SJeff Cody {
342779fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
342879fac568SJeff Cody 
342979fac568SJeff Cody     if (!bs) {
343079fac568SJeff Cody         return NULL;
343179fac568SJeff Cody     }
343279fac568SJeff Cody 
343379fac568SJeff Cody     curr_bs = bs;
343479fac568SJeff Cody 
343579fac568SJeff Cody     while (curr_bs->backing_hd) {
343679fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
343779fac568SJeff Cody     }
343879fac568SJeff Cody     return curr_bs;
343979fac568SJeff Cody }
344079fac568SJeff Cody 
3441ea2384d3Sbellard /**************************************************************/
344283f64091Sbellard /* async I/Os */
3443ea2384d3Sbellard 
34443b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3445f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
344683f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
3447ea2384d3Sbellard {
3448bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3449bbf0a440SStefan Hajnoczi 
3450b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
34518c5873d6SStefan Hajnoczi                                  cb, opaque, false);
345283f64091Sbellard }
345383f64091Sbellard 
3454f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3455f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
345683f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
34577674e7bfSbellard {
3458bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3459bbf0a440SStefan Hajnoczi 
34601a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
34618c5873d6SStefan Hajnoczi                                  cb, opaque, true);
346283f64091Sbellard }
346383f64091Sbellard 
346440b4f539SKevin Wolf 
346540b4f539SKevin Wolf typedef struct MultiwriteCB {
346640b4f539SKevin Wolf     int error;
346740b4f539SKevin Wolf     int num_requests;
346840b4f539SKevin Wolf     int num_callbacks;
346940b4f539SKevin Wolf     struct {
347040b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
347140b4f539SKevin Wolf         void *opaque;
347240b4f539SKevin Wolf         QEMUIOVector *free_qiov;
347340b4f539SKevin Wolf     } callbacks[];
347440b4f539SKevin Wolf } MultiwriteCB;
347540b4f539SKevin Wolf 
347640b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
347740b4f539SKevin Wolf {
347840b4f539SKevin Wolf     int i;
347940b4f539SKevin Wolf 
348040b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
348140b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
34821e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
34831e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
34841e1ea48dSStefan Hajnoczi         }
34857267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
348640b4f539SKevin Wolf     }
348740b4f539SKevin Wolf }
348840b4f539SKevin Wolf 
348940b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
349040b4f539SKevin Wolf {
349140b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
349240b4f539SKevin Wolf 
34936d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
34946d519a5fSStefan Hajnoczi 
3495cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
349640b4f539SKevin Wolf         mcb->error = ret;
349740b4f539SKevin Wolf     }
349840b4f539SKevin Wolf 
349940b4f539SKevin Wolf     mcb->num_requests--;
350040b4f539SKevin Wolf     if (mcb->num_requests == 0) {
350140b4f539SKevin Wolf         multiwrite_user_cb(mcb);
35027267c094SAnthony Liguori         g_free(mcb);
350340b4f539SKevin Wolf     }
350440b4f539SKevin Wolf }
350540b4f539SKevin Wolf 
350640b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
350740b4f539SKevin Wolf {
350877be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
350977be4366SChristoph Hellwig 
351077be4366SChristoph Hellwig     /*
351177be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
351277be4366SChristoph Hellwig      * here as that could overflow the return value.
351377be4366SChristoph Hellwig      */
351477be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
351577be4366SChristoph Hellwig         return 1;
351677be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
351777be4366SChristoph Hellwig         return -1;
351877be4366SChristoph Hellwig     } else {
351977be4366SChristoph Hellwig         return 0;
352077be4366SChristoph Hellwig     }
352140b4f539SKevin Wolf }
352240b4f539SKevin Wolf 
352340b4f539SKevin Wolf /*
352440b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
352540b4f539SKevin Wolf  * requests that remain after merging.
352640b4f539SKevin Wolf  */
352740b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
352840b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
352940b4f539SKevin Wolf {
353040b4f539SKevin Wolf     int i, outidx;
353140b4f539SKevin Wolf 
353240b4f539SKevin Wolf     // Sort requests by start sector
353340b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
353440b4f539SKevin Wolf 
353540b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
353640b4f539SKevin Wolf     // filling up gaps with zero sectors.
353740b4f539SKevin Wolf     outidx = 0;
353840b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
353940b4f539SKevin Wolf         int merge = 0;
354040b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
354140b4f539SKevin Wolf 
3542b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
354340b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
354440b4f539SKevin Wolf             merge = 1;
354540b4f539SKevin Wolf         }
354640b4f539SKevin Wolf 
3547e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3548e2a305fbSChristoph Hellwig             merge = 0;
3549e2a305fbSChristoph Hellwig         }
3550e2a305fbSChristoph Hellwig 
355140b4f539SKevin Wolf         if (merge) {
355240b4f539SKevin Wolf             size_t size;
35537267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
355440b4f539SKevin Wolf             qemu_iovec_init(qiov,
355540b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
355640b4f539SKevin Wolf 
355740b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
355840b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
355940b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
35601b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
356140b4f539SKevin Wolf 
3562b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3563b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
356440b4f539SKevin Wolf 
356540b4f539SKevin Wolf             // Add the second request
35661b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
356740b4f539SKevin Wolf 
3568cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
356940b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
357040b4f539SKevin Wolf 
357140b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
357240b4f539SKevin Wolf         } else {
357340b4f539SKevin Wolf             outidx++;
357440b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
357540b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
357640b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
357740b4f539SKevin Wolf         }
357840b4f539SKevin Wolf     }
357940b4f539SKevin Wolf 
358040b4f539SKevin Wolf     return outidx + 1;
358140b4f539SKevin Wolf }
358240b4f539SKevin Wolf 
358340b4f539SKevin Wolf /*
358440b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
358540b4f539SKevin Wolf  *
358640b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
358740b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
358840b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
358940b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
359040b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
359140b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
359240b4f539SKevin Wolf  *
359340b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
359440b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
359540b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
359640b4f539SKevin Wolf  */
359740b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
359840b4f539SKevin Wolf {
359940b4f539SKevin Wolf     MultiwriteCB *mcb;
360040b4f539SKevin Wolf     int i;
360140b4f539SKevin Wolf 
3602301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3603301db7c2SRyan Harper     if (bs->drv == NULL) {
3604301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3605301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3606301db7c2SRyan Harper         }
3607301db7c2SRyan Harper         return -1;
3608301db7c2SRyan Harper     }
3609301db7c2SRyan Harper 
361040b4f539SKevin Wolf     if (num_reqs == 0) {
361140b4f539SKevin Wolf         return 0;
361240b4f539SKevin Wolf     }
361340b4f539SKevin Wolf 
361440b4f539SKevin Wolf     // Create MultiwriteCB structure
36157267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
361640b4f539SKevin Wolf     mcb->num_requests = 0;
361740b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
361840b4f539SKevin Wolf 
361940b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
362040b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
362140b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
362240b4f539SKevin Wolf     }
362340b4f539SKevin Wolf 
362440b4f539SKevin Wolf     // Check for mergable requests
362540b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
362640b4f539SKevin Wolf 
36276d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
36286d519a5fSStefan Hajnoczi 
3629df9309fbSPaolo Bonzini     /* Run the aio requests. */
3630df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
363140b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3632ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
363340b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
363440b4f539SKevin Wolf     }
363540b4f539SKevin Wolf 
363640b4f539SKevin Wolf     return 0;
363740b4f539SKevin Wolf }
363840b4f539SKevin Wolf 
363983f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
364083f64091Sbellard {
3641d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
364283f64091Sbellard }
364383f64091Sbellard 
364483f64091Sbellard /**************************************************************/
364583f64091Sbellard /* async block device emulation */
364683f64091Sbellard 
3647c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
3648c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
3649c16b5a2cSChristoph Hellwig     QEMUBH *bh;
3650c16b5a2cSChristoph Hellwig     int ret;
3651c16b5a2cSChristoph Hellwig     /* vector translation state */
3652c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
3653c16b5a2cSChristoph Hellwig     uint8_t *bounce;
3654c16b5a2cSChristoph Hellwig     int is_write;
3655c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
3656c16b5a2cSChristoph Hellwig 
3657c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3658c16b5a2cSChristoph Hellwig {
3659b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
3660b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
36616a7ad299SDor Laor     qemu_bh_delete(acb->bh);
366236afc451SAvi Kivity     acb->bh = NULL;
3663c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
3664c16b5a2cSChristoph Hellwig }
3665c16b5a2cSChristoph Hellwig 
3666d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
3667c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
3668c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
3669c16b5a2cSChristoph Hellwig };
3670c16b5a2cSChristoph Hellwig 
367183f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
3672beac80cdSbellard {
3673ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
3674f141eafeSaliguori 
3675f141eafeSaliguori     if (!acb->is_write)
367603396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
3677ceb42de8Saliguori     qemu_vfree(acb->bounce);
3678ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
36796a7ad299SDor Laor     qemu_bh_delete(acb->bh);
368036afc451SAvi Kivity     acb->bh = NULL;
3681ce1a14dcSpbrook     qemu_aio_release(acb);
3682beac80cdSbellard }
3683beac80cdSbellard 
3684f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3685f141eafeSaliguori                                             int64_t sector_num,
3686f141eafeSaliguori                                             QEMUIOVector *qiov,
3687f141eafeSaliguori                                             int nb_sectors,
3688f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
3689f141eafeSaliguori                                             void *opaque,
3690f141eafeSaliguori                                             int is_write)
3691f141eafeSaliguori 
3692ea2384d3Sbellard {
3693ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
369483f64091Sbellard 
3695d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
3696f141eafeSaliguori     acb->is_write = is_write;
3697f141eafeSaliguori     acb->qiov = qiov;
3698e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
3699ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3700f141eafeSaliguori 
3701f141eafeSaliguori     if (is_write) {
3702d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
37031ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3704f141eafeSaliguori     } else {
37051ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3706f141eafeSaliguori     }
3707f141eafeSaliguori 
3708ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
3709f141eafeSaliguori 
3710ce1a14dcSpbrook     return &acb->common;
37117a6cba61Spbrook }
37127a6cba61Spbrook 
3713f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3714f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3715ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
371683f64091Sbellard {
3717f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
371883f64091Sbellard }
371983f64091Sbellard 
3720f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3721f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3722f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
3723f141eafeSaliguori {
3724f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3725f141eafeSaliguori }
3726f141eafeSaliguori 
372768485420SKevin Wolf 
372868485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
372968485420SKevin Wolf     BlockDriverAIOCB common;
373068485420SKevin Wolf     BlockRequest req;
373168485420SKevin Wolf     bool is_write;
3732d318aea9SKevin Wolf     bool *done;
373368485420SKevin Wolf     QEMUBH* bh;
373468485420SKevin Wolf } BlockDriverAIOCBCoroutine;
373568485420SKevin Wolf 
373668485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
373768485420SKevin Wolf {
3738d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
3739d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
3740d318aea9SKevin Wolf     bool done = false;
3741d318aea9SKevin Wolf 
3742d318aea9SKevin Wolf     acb->done = &done;
3743d318aea9SKevin Wolf     while (!done) {
3744d318aea9SKevin Wolf         qemu_aio_wait();
3745d318aea9SKevin Wolf     }
374668485420SKevin Wolf }
374768485420SKevin Wolf 
3748d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
374968485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
375068485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
375168485420SKevin Wolf };
375268485420SKevin Wolf 
375335246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
375468485420SKevin Wolf {
375568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
375668485420SKevin Wolf 
375768485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
3758d318aea9SKevin Wolf 
3759d318aea9SKevin Wolf     if (acb->done) {
3760d318aea9SKevin Wolf         *acb->done = true;
3761d318aea9SKevin Wolf     }
3762d318aea9SKevin Wolf 
376368485420SKevin Wolf     qemu_bh_delete(acb->bh);
376468485420SKevin Wolf     qemu_aio_release(acb);
376568485420SKevin Wolf }
376668485420SKevin Wolf 
3767b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3768b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
3769b2a61371SStefan Hajnoczi {
3770b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
3771b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
3772b2a61371SStefan Hajnoczi 
3773b2a61371SStefan Hajnoczi     if (!acb->is_write) {
3774b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
3775470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3776b2a61371SStefan Hajnoczi     } else {
3777b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
3778f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3779b2a61371SStefan Hajnoczi     }
3780b2a61371SStefan Hajnoczi 
378135246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3782b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
3783b2a61371SStefan Hajnoczi }
3784b2a61371SStefan Hajnoczi 
378568485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
378668485420SKevin Wolf                                                int64_t sector_num,
378768485420SKevin Wolf                                                QEMUIOVector *qiov,
378868485420SKevin Wolf                                                int nb_sectors,
378968485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
379068485420SKevin Wolf                                                void *opaque,
37918c5873d6SStefan Hajnoczi                                                bool is_write)
379268485420SKevin Wolf {
379368485420SKevin Wolf     Coroutine *co;
379468485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
379568485420SKevin Wolf 
3796d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
379768485420SKevin Wolf     acb->req.sector = sector_num;
379868485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
379968485420SKevin Wolf     acb->req.qiov = qiov;
380068485420SKevin Wolf     acb->is_write = is_write;
3801d318aea9SKevin Wolf     acb->done = NULL;
380268485420SKevin Wolf 
38038c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
380468485420SKevin Wolf     qemu_coroutine_enter(co, acb);
380568485420SKevin Wolf 
380668485420SKevin Wolf     return &acb->common;
380768485420SKevin Wolf }
380868485420SKevin Wolf 
380907f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
3810b2e12bc6SChristoph Hellwig {
381107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
381207f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
3813b2e12bc6SChristoph Hellwig 
381407f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
381507f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3816b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
3817b2e12bc6SChristoph Hellwig }
3818b2e12bc6SChristoph Hellwig 
381907f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
3820016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
3821016f5cf6SAlexander Graf {
382207f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
3823016f5cf6SAlexander Graf 
382407f07615SPaolo Bonzini     Coroutine *co;
382507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
3826016f5cf6SAlexander Graf 
3827d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
3828d318aea9SKevin Wolf     acb->done = NULL;
3829d318aea9SKevin Wolf 
383007f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
383107f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
3832016f5cf6SAlexander Graf 
3833016f5cf6SAlexander Graf     return &acb->common;
3834016f5cf6SAlexander Graf }
3835016f5cf6SAlexander Graf 
38364265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
38374265d620SPaolo Bonzini {
38384265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
38394265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
38404265d620SPaolo Bonzini 
38414265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
38424265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
38434265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
38444265d620SPaolo Bonzini }
38454265d620SPaolo Bonzini 
38464265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
38474265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
38484265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
38494265d620SPaolo Bonzini {
38504265d620SPaolo Bonzini     Coroutine *co;
38514265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
38524265d620SPaolo Bonzini 
38534265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
38544265d620SPaolo Bonzini 
3855d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
38564265d620SPaolo Bonzini     acb->req.sector = sector_num;
38574265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
3858d318aea9SKevin Wolf     acb->done = NULL;
38594265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
38604265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
38614265d620SPaolo Bonzini 
38624265d620SPaolo Bonzini     return &acb->common;
38634265d620SPaolo Bonzini }
38644265d620SPaolo Bonzini 
3865ea2384d3Sbellard void bdrv_init(void)
3866ea2384d3Sbellard {
38675efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3868ea2384d3Sbellard }
3869ce1a14dcSpbrook 
3870eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3871eb852011SMarkus Armbruster {
3872eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3873eb852011SMarkus Armbruster     bdrv_init();
3874eb852011SMarkus Armbruster }
3875eb852011SMarkus Armbruster 
3876d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
38776bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
38786bbff9a0Saliguori {
3879ce1a14dcSpbrook     BlockDriverAIOCB *acb;
3880ce1a14dcSpbrook 
3881d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
3882d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
3883ce1a14dcSpbrook     acb->bs = bs;
3884ce1a14dcSpbrook     acb->cb = cb;
3885ce1a14dcSpbrook     acb->opaque = opaque;
3886ce1a14dcSpbrook     return acb;
3887ce1a14dcSpbrook }
3888ce1a14dcSpbrook 
3889ce1a14dcSpbrook void qemu_aio_release(void *p)
3890ce1a14dcSpbrook {
3891d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
3892d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
3893ce1a14dcSpbrook }
389419cb3738Sbellard 
389519cb3738Sbellard /**************************************************************/
3896f9f05dc5SKevin Wolf /* Coroutine block device emulation */
3897f9f05dc5SKevin Wolf 
3898f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
3899f9f05dc5SKevin Wolf     Coroutine *coroutine;
3900f9f05dc5SKevin Wolf     int ret;
3901f9f05dc5SKevin Wolf } CoroutineIOCompletion;
3902f9f05dc5SKevin Wolf 
3903f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
3904f9f05dc5SKevin Wolf {
3905f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
3906f9f05dc5SKevin Wolf 
3907f9f05dc5SKevin Wolf     co->ret = ret;
3908f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
3909f9f05dc5SKevin Wolf }
3910f9f05dc5SKevin Wolf 
3911f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
3912f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
3913f9f05dc5SKevin Wolf                                       bool is_write)
3914f9f05dc5SKevin Wolf {
3915f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
3916f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
3917f9f05dc5SKevin Wolf     };
3918f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
3919f9f05dc5SKevin Wolf 
3920f9f05dc5SKevin Wolf     if (is_write) {
3921a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
3922f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
3923f9f05dc5SKevin Wolf     } else {
3924a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
3925f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
3926f9f05dc5SKevin Wolf     }
3927f9f05dc5SKevin Wolf 
392859370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
3929f9f05dc5SKevin Wolf     if (!acb) {
3930f9f05dc5SKevin Wolf         return -EIO;
3931f9f05dc5SKevin Wolf     }
3932f9f05dc5SKevin Wolf     qemu_coroutine_yield();
3933f9f05dc5SKevin Wolf 
3934f9f05dc5SKevin Wolf     return co.ret;
3935f9f05dc5SKevin Wolf }
3936f9f05dc5SKevin Wolf 
3937f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3938f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3939f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3940f9f05dc5SKevin Wolf {
3941f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3942f9f05dc5SKevin Wolf }
3943f9f05dc5SKevin Wolf 
3944f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3945f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3946f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3947f9f05dc5SKevin Wolf {
3948f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3949f9f05dc5SKevin Wolf }
3950f9f05dc5SKevin Wolf 
395107f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
3952e7a8a783SKevin Wolf {
395307f07615SPaolo Bonzini     RwCo *rwco = opaque;
395407f07615SPaolo Bonzini 
395507f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
395607f07615SPaolo Bonzini }
395707f07615SPaolo Bonzini 
395807f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
395907f07615SPaolo Bonzini {
3960eb489bb1SKevin Wolf     int ret;
3961eb489bb1SKevin Wolf 
396229cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
396307f07615SPaolo Bonzini         return 0;
3964eb489bb1SKevin Wolf     }
3965eb489bb1SKevin Wolf 
3966ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
3967bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
3968eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
3969eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
3970eb489bb1SKevin Wolf         if (ret < 0) {
3971eb489bb1SKevin Wolf             return ret;
3972eb489bb1SKevin Wolf         }
3973eb489bb1SKevin Wolf     }
3974eb489bb1SKevin Wolf 
3975ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
3976ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
3977d4c82329SKevin Wolf         goto flush_parent;
3978ca716364SKevin Wolf     }
3979ca716364SKevin Wolf 
3980bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
3981eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
398229cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
398307f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
398407f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
3985e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
3986e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
3987e7a8a783SKevin Wolf         };
3988e7a8a783SKevin Wolf 
398907f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
399007f07615SPaolo Bonzini         if (acb == NULL) {
399129cdb251SPaolo Bonzini             ret = -EIO;
399207f07615SPaolo Bonzini         } else {
3993e7a8a783SKevin Wolf             qemu_coroutine_yield();
399429cdb251SPaolo Bonzini             ret = co.ret;
3995e7a8a783SKevin Wolf         }
399607f07615SPaolo Bonzini     } else {
399707f07615SPaolo Bonzini         /*
399807f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
399907f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
400007f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
400107f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
400207f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
400307f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
400407f07615SPaolo Bonzini          * mode.
400507f07615SPaolo Bonzini          *
400607f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
400707f07615SPaolo Bonzini          */
400829cdb251SPaolo Bonzini         ret = 0;
400907f07615SPaolo Bonzini     }
401029cdb251SPaolo Bonzini     if (ret < 0) {
401129cdb251SPaolo Bonzini         return ret;
401229cdb251SPaolo Bonzini     }
401329cdb251SPaolo Bonzini 
401429cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
401529cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
401629cdb251SPaolo Bonzini      */
4017d4c82329SKevin Wolf flush_parent:
401829cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
401907f07615SPaolo Bonzini }
402007f07615SPaolo Bonzini 
40210f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
40220f15423cSAnthony Liguori {
40230f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
40240f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
40250f15423cSAnthony Liguori     }
40260f15423cSAnthony Liguori }
40270f15423cSAnthony Liguori 
40280f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
40290f15423cSAnthony Liguori {
40300f15423cSAnthony Liguori     BlockDriverState *bs;
40310f15423cSAnthony Liguori 
40320f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
40330f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
40340f15423cSAnthony Liguori     }
40350f15423cSAnthony Liguori }
40360f15423cSAnthony Liguori 
403707789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
403807789269SBenoît Canet {
403907789269SBenoît Canet     BlockDriverState *bs;
404007789269SBenoît Canet 
404107789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
404207789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
404307789269SBenoît Canet     }
404407789269SBenoît Canet }
404507789269SBenoît Canet 
404607f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
404707f07615SPaolo Bonzini {
404807f07615SPaolo Bonzini     Coroutine *co;
404907f07615SPaolo Bonzini     RwCo rwco = {
405007f07615SPaolo Bonzini         .bs = bs,
405107f07615SPaolo Bonzini         .ret = NOT_DONE,
405207f07615SPaolo Bonzini     };
405307f07615SPaolo Bonzini 
405407f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
405507f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
405607f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
405707f07615SPaolo Bonzini     } else {
405807f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
405907f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
406007f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
406107f07615SPaolo Bonzini             qemu_aio_wait();
406207f07615SPaolo Bonzini         }
406307f07615SPaolo Bonzini     }
406407f07615SPaolo Bonzini 
406507f07615SPaolo Bonzini     return rwco.ret;
406607f07615SPaolo Bonzini }
4067e7a8a783SKevin Wolf 
40684265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
40694265d620SPaolo Bonzini {
40704265d620SPaolo Bonzini     RwCo *rwco = opaque;
40714265d620SPaolo Bonzini 
40724265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
40734265d620SPaolo Bonzini }
40744265d620SPaolo Bonzini 
40754265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
40764265d620SPaolo Bonzini                                  int nb_sectors)
40774265d620SPaolo Bonzini {
40784265d620SPaolo Bonzini     if (!bs->drv) {
40794265d620SPaolo Bonzini         return -ENOMEDIUM;
40804265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
40814265d620SPaolo Bonzini         return -EIO;
40824265d620SPaolo Bonzini     } else if (bs->read_only) {
40834265d620SPaolo Bonzini         return -EROFS;
4084df702c9bSPaolo Bonzini     }
4085df702c9bSPaolo Bonzini 
4086df702c9bSPaolo Bonzini     if (bs->dirty_bitmap) {
40878f0720ecSPaolo Bonzini         bdrv_reset_dirty(bs, sector_num, nb_sectors);
4088df702c9bSPaolo Bonzini     }
4089df702c9bSPaolo Bonzini 
40909e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
40919e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
40929e8f1835SPaolo Bonzini         return 0;
40939e8f1835SPaolo Bonzini     }
40949e8f1835SPaolo Bonzini 
4095df702c9bSPaolo Bonzini     if (bs->drv->bdrv_co_discard) {
40964265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
40974265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
40984265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
40994265d620SPaolo Bonzini         CoroutineIOCompletion co = {
41004265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
41014265d620SPaolo Bonzini         };
41024265d620SPaolo Bonzini 
41034265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
41044265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
41054265d620SPaolo Bonzini         if (acb == NULL) {
41064265d620SPaolo Bonzini             return -EIO;
41074265d620SPaolo Bonzini         } else {
41084265d620SPaolo Bonzini             qemu_coroutine_yield();
41094265d620SPaolo Bonzini             return co.ret;
41104265d620SPaolo Bonzini         }
41114265d620SPaolo Bonzini     } else {
41124265d620SPaolo Bonzini         return 0;
41134265d620SPaolo Bonzini     }
41144265d620SPaolo Bonzini }
41154265d620SPaolo Bonzini 
41164265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
41174265d620SPaolo Bonzini {
41184265d620SPaolo Bonzini     Coroutine *co;
41194265d620SPaolo Bonzini     RwCo rwco = {
41204265d620SPaolo Bonzini         .bs = bs,
41214265d620SPaolo Bonzini         .sector_num = sector_num,
41224265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
41234265d620SPaolo Bonzini         .ret = NOT_DONE,
41244265d620SPaolo Bonzini     };
41254265d620SPaolo Bonzini 
41264265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
41274265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
41284265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
41294265d620SPaolo Bonzini     } else {
41304265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
41314265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
41324265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
41334265d620SPaolo Bonzini             qemu_aio_wait();
41344265d620SPaolo Bonzini         }
41354265d620SPaolo Bonzini     }
41364265d620SPaolo Bonzini 
41374265d620SPaolo Bonzini     return rwco.ret;
41384265d620SPaolo Bonzini }
41394265d620SPaolo Bonzini 
4140f9f05dc5SKevin Wolf /**************************************************************/
414119cb3738Sbellard /* removable device support */
414219cb3738Sbellard 
414319cb3738Sbellard /**
414419cb3738Sbellard  * Return TRUE if the media is present
414519cb3738Sbellard  */
414619cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
414719cb3738Sbellard {
414819cb3738Sbellard     BlockDriver *drv = bs->drv;
4149a1aff5bfSMarkus Armbruster 
415019cb3738Sbellard     if (!drv)
415119cb3738Sbellard         return 0;
415219cb3738Sbellard     if (!drv->bdrv_is_inserted)
4153a1aff5bfSMarkus Armbruster         return 1;
4154a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
415519cb3738Sbellard }
415619cb3738Sbellard 
415719cb3738Sbellard /**
41588e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
41598e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
416019cb3738Sbellard  */
416119cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
416219cb3738Sbellard {
416319cb3738Sbellard     BlockDriver *drv = bs->drv;
416419cb3738Sbellard 
41658e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
41668e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
41678e49ca46SMarkus Armbruster     }
41688e49ca46SMarkus Armbruster     return -ENOTSUP;
416919cb3738Sbellard }
417019cb3738Sbellard 
417119cb3738Sbellard /**
417219cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
417319cb3738Sbellard  */
4174f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
417519cb3738Sbellard {
417619cb3738Sbellard     BlockDriver *drv = bs->drv;
417719cb3738Sbellard 
4178822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4179822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
418019cb3738Sbellard     }
41816f382ed2SLuiz Capitulino 
41826f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
41836f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
41846f382ed2SLuiz Capitulino     }
418519cb3738Sbellard }
418619cb3738Sbellard 
418719cb3738Sbellard /**
418819cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
418919cb3738Sbellard  * to eject it manually).
419019cb3738Sbellard  */
4191025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
419219cb3738Sbellard {
419319cb3738Sbellard     BlockDriver *drv = bs->drv;
419419cb3738Sbellard 
4195025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4196b8c6d095SStefan Hajnoczi 
4197025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4198025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
419919cb3738Sbellard     }
420019cb3738Sbellard }
4201985a03b0Sths 
4202985a03b0Sths /* needed for generic scsi interface */
4203985a03b0Sths 
4204985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4205985a03b0Sths {
4206985a03b0Sths     BlockDriver *drv = bs->drv;
4207985a03b0Sths 
4208985a03b0Sths     if (drv && drv->bdrv_ioctl)
4209985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4210985a03b0Sths     return -ENOTSUP;
4211985a03b0Sths }
42127d780669Saliguori 
4213221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4214221f715dSaliguori         unsigned long int req, void *buf,
42157d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
42167d780669Saliguori {
4217221f715dSaliguori     BlockDriver *drv = bs->drv;
42187d780669Saliguori 
4219221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4220221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4221221f715dSaliguori     return NULL;
42227d780669Saliguori }
4223e268ca52Saliguori 
42247b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
42257b6f9300SMarkus Armbruster {
42267b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
42277b6f9300SMarkus Armbruster }
42287cd1e32aSlirans@il.ibm.com 
4229e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
4230e268ca52Saliguori {
4231e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4232e268ca52Saliguori }
42337cd1e32aSlirans@il.ibm.com 
4234c53b1c51SStefan Hajnoczi /*
4235c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
4236c53b1c51SStefan Hajnoczi  */
4237c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4238c53b1c51SStefan Hajnoczi {
4239c53b1c51SStefan Hajnoczi     int i;
4240c53b1c51SStefan Hajnoczi 
4241c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
4242c53b1c51SStefan Hajnoczi         if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4243c53b1c51SStefan Hajnoczi             return false;
4244c53b1c51SStefan Hajnoczi         }
4245c53b1c51SStefan Hajnoczi     }
4246c53b1c51SStefan Hajnoczi 
4247c53b1c51SStefan Hajnoczi     return true;
4248c53b1c51SStefan Hajnoczi }
4249c53b1c51SStefan Hajnoczi 
425050717e94SPaolo Bonzini void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
42517cd1e32aSlirans@il.ibm.com {
42527cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
4253a55eb92cSJan Kiszka 
425450717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
425550717e94SPaolo Bonzini 
425650717e94SPaolo Bonzini     if (granularity) {
425750717e94SPaolo Bonzini         granularity >>= BDRV_SECTOR_BITS;
425850717e94SPaolo Bonzini         assert(!bs->dirty_bitmap);
42598f0720ecSPaolo Bonzini         bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
426050717e94SPaolo Bonzini         bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
42617cd1e32aSlirans@il.ibm.com     } else {
4262c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
42638f0720ecSPaolo Bonzini             hbitmap_free(bs->dirty_bitmap);
4264c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
42657cd1e32aSlirans@il.ibm.com         }
42667cd1e32aSlirans@il.ibm.com     }
42677cd1e32aSlirans@il.ibm.com }
42687cd1e32aSlirans@il.ibm.com 
42697cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
42707cd1e32aSlirans@il.ibm.com {
42718f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
42728f0720ecSPaolo Bonzini         return hbitmap_get(bs->dirty_bitmap, sector);
42737cd1e32aSlirans@il.ibm.com     } else {
42747cd1e32aSlirans@il.ibm.com         return 0;
42757cd1e32aSlirans@il.ibm.com     }
42767cd1e32aSlirans@il.ibm.com }
42777cd1e32aSlirans@il.ibm.com 
42788f0720ecSPaolo Bonzini void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
42791755da16SPaolo Bonzini {
42808f0720ecSPaolo Bonzini     hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
42811755da16SPaolo Bonzini }
42821755da16SPaolo Bonzini 
42831755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
42841755da16SPaolo Bonzini                     int nr_sectors)
42851755da16SPaolo Bonzini {
42868f0720ecSPaolo Bonzini     hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
42871755da16SPaolo Bonzini }
42881755da16SPaolo Bonzini 
42897cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
42907cd1e32aSlirans@il.ibm.com                       int nr_sectors)
42917cd1e32aSlirans@il.ibm.com {
42928f0720ecSPaolo Bonzini     hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
42937cd1e32aSlirans@il.ibm.com }
4294aaa0eb75SLiran Schour 
4295aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4296aaa0eb75SLiran Schour {
42978f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
4298acc906c6SPaolo Bonzini         return hbitmap_count(bs->dirty_bitmap);
42998f0720ecSPaolo Bonzini     } else {
43008f0720ecSPaolo Bonzini         return 0;
43018f0720ecSPaolo Bonzini     }
4302aaa0eb75SLiran Schour }
4303f88e1a42SJes Sorensen 
4304*9fcb0251SFam Zheng /* Get a reference to bs */
4305*9fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
4306*9fcb0251SFam Zheng {
4307*9fcb0251SFam Zheng     bs->refcnt++;
4308*9fcb0251SFam Zheng }
4309*9fcb0251SFam Zheng 
4310*9fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
4311*9fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
4312*9fcb0251SFam Zheng  * deleted. */
4313*9fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
4314*9fcb0251SFam Zheng {
4315*9fcb0251SFam Zheng     assert(bs->refcnt > 0);
4316*9fcb0251SFam Zheng     if (--bs->refcnt == 0) {
4317*9fcb0251SFam Zheng         bdrv_delete(bs);
4318*9fcb0251SFam Zheng     }
4319*9fcb0251SFam Zheng }
4320*9fcb0251SFam Zheng 
4321db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4322db593f25SMarcelo Tosatti {
4323db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
4324db593f25SMarcelo Tosatti     bs->in_use = in_use;
4325db593f25SMarcelo Tosatti }
4326db593f25SMarcelo Tosatti 
4327db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
4328db593f25SMarcelo Tosatti {
4329db593f25SMarcelo Tosatti     return bs->in_use;
4330db593f25SMarcelo Tosatti }
4331db593f25SMarcelo Tosatti 
433228a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
433328a7282aSLuiz Capitulino {
4334d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
433558e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
433628a7282aSLuiz Capitulino }
433728a7282aSLuiz Capitulino 
433828a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
433928a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
434028a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
434128a7282aSLuiz Capitulino {
4342d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
434392aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
434492aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
434592aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
434628a7282aSLuiz Capitulino }
434728a7282aSLuiz Capitulino 
434828a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
434928a7282aSLuiz Capitulino {
4350d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
435128a7282aSLuiz Capitulino }
435228a7282aSLuiz Capitulino 
435328a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
435428a7282aSLuiz Capitulino {
435528a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
435658e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
43573bd293c3SPaolo Bonzini         if (bs->job) {
43583bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
43593bd293c3SPaolo Bonzini         }
436028a7282aSLuiz Capitulino     }
436128a7282aSLuiz Capitulino }
436228a7282aSLuiz Capitulino 
436328a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
436428a7282aSLuiz Capitulino {
43653e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
43663e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
436758e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
436858e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
436928a7282aSLuiz Capitulino     }
437028a7282aSLuiz Capitulino }
437128a7282aSLuiz Capitulino 
4372a597e79cSChristoph Hellwig void
4373a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4374a597e79cSChristoph Hellwig         enum BlockAcctType type)
4375a597e79cSChristoph Hellwig {
4376a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4377a597e79cSChristoph Hellwig 
4378a597e79cSChristoph Hellwig     cookie->bytes = bytes;
4379c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
4380a597e79cSChristoph Hellwig     cookie->type = type;
4381a597e79cSChristoph Hellwig }
4382a597e79cSChristoph Hellwig 
4383a597e79cSChristoph Hellwig void
4384a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4385a597e79cSChristoph Hellwig {
4386a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
4387a597e79cSChristoph Hellwig 
4388a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
4389a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
4390c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4391a597e79cSChristoph Hellwig }
4392a597e79cSChristoph Hellwig 
4393d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
4394f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
4395f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
4396f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
4397f88e1a42SJes Sorensen {
4398f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
4399d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
4400f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
4401f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
440296df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
4403f88e1a42SJes Sorensen     int ret = 0;
4404f88e1a42SJes Sorensen 
4405f88e1a42SJes Sorensen     /* Find driver and parse its options */
4406f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
4407f88e1a42SJes Sorensen     if (!drv) {
440871c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
4409d92ada22SLuiz Capitulino         return;
4410f88e1a42SJes Sorensen     }
4411f88e1a42SJes Sorensen 
441298289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
4413f88e1a42SJes Sorensen     if (!proto_drv) {
441471c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
4415d92ada22SLuiz Capitulino         return;
4416f88e1a42SJes Sorensen     }
4417f88e1a42SJes Sorensen 
4418f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4419f88e1a42SJes Sorensen                                               drv->create_options);
4420f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4421f88e1a42SJes Sorensen                                               proto_drv->create_options);
4422f88e1a42SJes Sorensen 
4423f88e1a42SJes Sorensen     /* Create parameter list with default values */
4424f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
4425f88e1a42SJes Sorensen 
4426f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4427f88e1a42SJes Sorensen 
4428f88e1a42SJes Sorensen     /* Parse -o options */
4429f88e1a42SJes Sorensen     if (options) {
4430f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
4431f88e1a42SJes Sorensen         if (param == NULL) {
443271c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
4433f88e1a42SJes Sorensen             goto out;
4434f88e1a42SJes Sorensen         }
4435f88e1a42SJes Sorensen     }
4436f88e1a42SJes Sorensen 
4437f88e1a42SJes Sorensen     if (base_filename) {
4438f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4439f88e1a42SJes Sorensen                                  base_filename)) {
444071c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
444171c79813SLuiz Capitulino                        fmt);
4442f88e1a42SJes Sorensen             goto out;
4443f88e1a42SJes Sorensen         }
4444f88e1a42SJes Sorensen     }
4445f88e1a42SJes Sorensen 
4446f88e1a42SJes Sorensen     if (base_fmt) {
4447f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
444871c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
444971c79813SLuiz Capitulino                              "format '%s'", fmt);
4450f88e1a42SJes Sorensen             goto out;
4451f88e1a42SJes Sorensen         }
4452f88e1a42SJes Sorensen     }
4453f88e1a42SJes Sorensen 
4454792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4455792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4456792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
445771c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
445871c79813SLuiz Capitulino                              "same filename as the backing file");
4459792da93aSJes Sorensen             goto out;
4460792da93aSJes Sorensen         }
4461792da93aSJes Sorensen     }
4462792da93aSJes Sorensen 
4463f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4464f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
446596df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
446696df67d1SStefan Hajnoczi         if (!backing_drv) {
446771c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
446871c79813SLuiz Capitulino                        backing_fmt->value.s);
4469f88e1a42SJes Sorensen             goto out;
4470f88e1a42SJes Sorensen         }
4471f88e1a42SJes Sorensen     }
4472f88e1a42SJes Sorensen 
4473f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4474f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4475d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4476d220894eSKevin Wolf     if (size && size->value.n == -1) {
4477f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4478f88e1a42SJes Sorensen             uint64_t size;
4479f88e1a42SJes Sorensen             char buf[32];
448063090dacSPaolo Bonzini             int back_flags;
448163090dacSPaolo Bonzini 
448263090dacSPaolo Bonzini             /* backing files always opened read-only */
448363090dacSPaolo Bonzini             back_flags =
448463090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4485f88e1a42SJes Sorensen 
4486f88e1a42SJes Sorensen             bs = bdrv_new("");
4487f88e1a42SJes Sorensen 
4488de9c0cecSKevin Wolf             ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4489de9c0cecSKevin Wolf                             backing_drv);
4490f88e1a42SJes Sorensen             if (ret < 0) {
449171c79813SLuiz Capitulino                 error_setg_errno(errp, -ret, "Could not open '%s'",
449271c79813SLuiz Capitulino                                  backing_file->value.s);
4493f88e1a42SJes Sorensen                 goto out;
4494f88e1a42SJes Sorensen             }
4495f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4496f88e1a42SJes Sorensen             size *= 512;
4497f88e1a42SJes Sorensen 
4498f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4499f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4500f88e1a42SJes Sorensen         } else {
450171c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
4502f88e1a42SJes Sorensen             goto out;
4503f88e1a42SJes Sorensen         }
4504f88e1a42SJes Sorensen     }
4505f88e1a42SJes Sorensen 
4506f382d43aSMiroslav Rezanina     if (!quiet) {
4507f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
4508f88e1a42SJes Sorensen         print_option_parameters(param);
4509f88e1a42SJes Sorensen         puts("");
4510f382d43aSMiroslav Rezanina     }
4511f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
4512f88e1a42SJes Sorensen     if (ret < 0) {
4513f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
451471c79813SLuiz Capitulino             error_setg(errp,"Formatting or formatting option not supported for "
451571c79813SLuiz Capitulino                             "file format '%s'", fmt);
4516f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
4517f3f4d2c0SKevin Wolf             const char *cluster_size_hint = "";
4518f3f4d2c0SKevin Wolf             if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
4519f3f4d2c0SKevin Wolf                 cluster_size_hint = " (try using a larger cluster size)";
4520f3f4d2c0SKevin Wolf             }
4521f3f4d2c0SKevin Wolf             error_setg(errp, "The image size is too large for file format '%s'%s",
4522f3f4d2c0SKevin Wolf                        fmt, cluster_size_hint);
4523f88e1a42SJes Sorensen         } else {
452471c79813SLuiz Capitulino             error_setg(errp, "%s: error while creating %s: %s", filename, fmt,
452571c79813SLuiz Capitulino                        strerror(-ret));
4526f88e1a42SJes Sorensen         }
4527f88e1a42SJes Sorensen     }
4528f88e1a42SJes Sorensen 
4529f88e1a42SJes Sorensen out:
4530f88e1a42SJes Sorensen     free_option_parameters(create_options);
4531f88e1a42SJes Sorensen     free_option_parameters(param);
4532f88e1a42SJes Sorensen 
4533f88e1a42SJes Sorensen     if (bs) {
4534f88e1a42SJes Sorensen         bdrv_delete(bs);
4535f88e1a42SJes Sorensen     }
4536f88e1a42SJes Sorensen }
453785d126f3SStefan Hajnoczi 
453885d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
453985d126f3SStefan Hajnoczi {
454085d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
454185d126f3SStefan Hajnoczi     return qemu_get_aio_context();
454285d126f3SStefan Hajnoczi }
4543d616b224SStefan Hajnoczi 
4544d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
4545d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
4546d616b224SStefan Hajnoczi {
4547d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
4548d616b224SStefan Hajnoczi }
4549