xref: /openbmc/qemu/block.c (revision 49aa46bb4b894ff8bdb0339ee2a5dd3fcfe93ecd)
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"
27376253ecSaliguori #include "monitor.h"
28ea2384d3Sbellard #include "block_int.h"
295efa9d5aSAnthony Liguori #include "module.h"
30d15e5465SLuiz Capitulino #include "qemu-objects.h"
31fc01f7e7Sbellard 
3271e72a19SJuan Quintela #ifdef CONFIG_BSD
337674e7bfSbellard #include <sys/types.h>
347674e7bfSbellard #include <sys/stat.h>
357674e7bfSbellard #include <sys/ioctl.h>
3672cf2d4fSBlue Swirl #include <sys/queue.h>
37c5e97233Sblueswir1 #ifndef __DragonFly__
387674e7bfSbellard #include <sys/disk.h>
397674e7bfSbellard #endif
40c5e97233Sblueswir1 #endif
417674e7bfSbellard 
4249dc768dSaliguori #ifdef _WIN32
4349dc768dSaliguori #include <windows.h>
4449dc768dSaliguori #endif
4549dc768dSaliguori 
46f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
47f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
48c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
49f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
50f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
51ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
52b2e12bc6SChristoph Hellwig static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
53b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque);
54016f5cf6SAlexander Graf static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
55016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque);
5683f64091Sbellard static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
5783f64091Sbellard                         uint8_t *buf, int nb_sectors);
5883f64091Sbellard static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
5983f64091Sbellard                          const uint8_t *buf, int nb_sectors);
60ec530c81Sbellard 
611b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
621b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
637ee930d0Sblueswir1 
648a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
658a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
66ea2384d3Sbellard 
67f9092b10SMarkus Armbruster /* The device to use for VM snapshots */
68f9092b10SMarkus Armbruster static BlockDriverState *bs_snapshots;
69f9092b10SMarkus Armbruster 
70eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
71eb852011SMarkus Armbruster static int use_bdrv_whitelist;
72eb852011SMarkus Armbruster 
739e0b22f4SStefan Hajnoczi #ifdef _WIN32
749e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
759e0b22f4SStefan Hajnoczi {
769e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
779e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
789e0b22f4SStefan Hajnoczi             filename[1] == ':');
799e0b22f4SStefan Hajnoczi }
809e0b22f4SStefan Hajnoczi 
819e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
829e0b22f4SStefan Hajnoczi {
839e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
849e0b22f4SStefan Hajnoczi         filename[2] == '\0')
859e0b22f4SStefan Hajnoczi         return 1;
869e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
879e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
889e0b22f4SStefan Hajnoczi         return 1;
899e0b22f4SStefan Hajnoczi     return 0;
909e0b22f4SStefan Hajnoczi }
919e0b22f4SStefan Hajnoczi #endif
929e0b22f4SStefan Hajnoczi 
939e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
949e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
959e0b22f4SStefan Hajnoczi {
969e0b22f4SStefan Hajnoczi #ifdef _WIN32
979e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
989e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
999e0b22f4SStefan Hajnoczi         return 0;
1009e0b22f4SStefan Hajnoczi     }
1019e0b22f4SStefan Hajnoczi #endif
1029e0b22f4SStefan Hajnoczi 
1039e0b22f4SStefan Hajnoczi     return strchr(path, ':') != NULL;
1049e0b22f4SStefan Hajnoczi }
1059e0b22f4SStefan Hajnoczi 
10683f64091Sbellard int path_is_absolute(const char *path)
10783f64091Sbellard {
10883f64091Sbellard     const char *p;
10921664424Sbellard #ifdef _WIN32
11021664424Sbellard     /* specific case for names like: "\\.\d:" */
11121664424Sbellard     if (*path == '/' || *path == '\\')
11221664424Sbellard         return 1;
11321664424Sbellard #endif
11483f64091Sbellard     p = strchr(path, ':');
11583f64091Sbellard     if (p)
11683f64091Sbellard         p++;
11783f64091Sbellard     else
11883f64091Sbellard         p = path;
1193b9f94e1Sbellard #ifdef _WIN32
1203b9f94e1Sbellard     return (*p == '/' || *p == '\\');
1213b9f94e1Sbellard #else
1223b9f94e1Sbellard     return (*p == '/');
1233b9f94e1Sbellard #endif
12483f64091Sbellard }
12583f64091Sbellard 
12683f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
12783f64091Sbellard    path to it by considering it is relative to base_path. URL are
12883f64091Sbellard    supported. */
12983f64091Sbellard void path_combine(char *dest, int dest_size,
13083f64091Sbellard                   const char *base_path,
13183f64091Sbellard                   const char *filename)
13283f64091Sbellard {
13383f64091Sbellard     const char *p, *p1;
13483f64091Sbellard     int len;
13583f64091Sbellard 
13683f64091Sbellard     if (dest_size <= 0)
13783f64091Sbellard         return;
13883f64091Sbellard     if (path_is_absolute(filename)) {
13983f64091Sbellard         pstrcpy(dest, dest_size, filename);
14083f64091Sbellard     } else {
14183f64091Sbellard         p = strchr(base_path, ':');
14283f64091Sbellard         if (p)
14383f64091Sbellard             p++;
14483f64091Sbellard         else
14583f64091Sbellard             p = base_path;
1463b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1473b9f94e1Sbellard #ifdef _WIN32
1483b9f94e1Sbellard         {
1493b9f94e1Sbellard             const char *p2;
1503b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1513b9f94e1Sbellard             if (!p1 || p2 > p1)
1523b9f94e1Sbellard                 p1 = p2;
1533b9f94e1Sbellard         }
1543b9f94e1Sbellard #endif
15583f64091Sbellard         if (p1)
15683f64091Sbellard             p1++;
15783f64091Sbellard         else
15883f64091Sbellard             p1 = base_path;
15983f64091Sbellard         if (p1 > p)
16083f64091Sbellard             p = p1;
16183f64091Sbellard         len = p - base_path;
16283f64091Sbellard         if (len > dest_size - 1)
16383f64091Sbellard             len = dest_size - 1;
16483f64091Sbellard         memcpy(dest, base_path, len);
16583f64091Sbellard         dest[len] = '\0';
16683f64091Sbellard         pstrcat(dest, dest_size, filename);
16783f64091Sbellard     }
16883f64091Sbellard }
16983f64091Sbellard 
1705efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
171ea2384d3Sbellard {
172f141eafeSaliguori     if (!bdrv->bdrv_aio_readv) {
17383f64091Sbellard         /* add AIO emulation layer */
174f141eafeSaliguori         bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
175f141eafeSaliguori         bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
176eda578e5Saliguori     } else if (!bdrv->bdrv_read) {
17783f64091Sbellard         /* add synchronous IO emulation layer */
17883f64091Sbellard         bdrv->bdrv_read = bdrv_read_em;
17983f64091Sbellard         bdrv->bdrv_write = bdrv_write_em;
18083f64091Sbellard     }
181b2e12bc6SChristoph Hellwig 
182b2e12bc6SChristoph Hellwig     if (!bdrv->bdrv_aio_flush)
183b2e12bc6SChristoph Hellwig         bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
184b2e12bc6SChristoph Hellwig 
1858a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
186ea2384d3Sbellard }
187b338082bSbellard 
188b338082bSbellard /* create a new block device (by default it is empty) */
189b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
190fc01f7e7Sbellard {
1911b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
192b338082bSbellard 
193b338082bSbellard     bs = qemu_mallocz(sizeof(BlockDriverState));
194b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
195ea2384d3Sbellard     if (device_name[0] != '\0') {
1961b7bdbc1SStefan Hajnoczi         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
197ea2384d3Sbellard     }
198b338082bSbellard     return bs;
199b338082bSbellard }
200b338082bSbellard 
201ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
202ea2384d3Sbellard {
203ea2384d3Sbellard     BlockDriver *drv1;
2048a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2058a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
206ea2384d3Sbellard             return drv1;
207ea2384d3Sbellard         }
2088a22f02aSStefan Hajnoczi     }
209ea2384d3Sbellard     return NULL;
210ea2384d3Sbellard }
211ea2384d3Sbellard 
212eb852011SMarkus Armbruster static int bdrv_is_whitelisted(BlockDriver *drv)
213eb852011SMarkus Armbruster {
214eb852011SMarkus Armbruster     static const char *whitelist[] = {
215eb852011SMarkus Armbruster         CONFIG_BDRV_WHITELIST
216eb852011SMarkus Armbruster     };
217eb852011SMarkus Armbruster     const char **p;
218eb852011SMarkus Armbruster 
219eb852011SMarkus Armbruster     if (!whitelist[0])
220eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
221eb852011SMarkus Armbruster 
222eb852011SMarkus Armbruster     for (p = whitelist; *p; p++) {
223eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
224eb852011SMarkus Armbruster             return 1;
225eb852011SMarkus Armbruster         }
226eb852011SMarkus Armbruster     }
227eb852011SMarkus Armbruster     return 0;
228eb852011SMarkus Armbruster }
229eb852011SMarkus Armbruster 
230eb852011SMarkus Armbruster BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
231eb852011SMarkus Armbruster {
232eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
233eb852011SMarkus Armbruster     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
234eb852011SMarkus Armbruster }
235eb852011SMarkus Armbruster 
2360e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
2370e7e1989SKevin Wolf     QEMUOptionParameter *options)
238ea2384d3Sbellard {
239ea2384d3Sbellard     if (!drv->bdrv_create)
240ea2384d3Sbellard         return -ENOTSUP;
2410e7e1989SKevin Wolf 
2420e7e1989SKevin Wolf     return drv->bdrv_create(filename, options);
243ea2384d3Sbellard }
244ea2384d3Sbellard 
24584a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
24684a12e66SChristoph Hellwig {
24784a12e66SChristoph Hellwig     BlockDriver *drv;
24884a12e66SChristoph Hellwig 
249b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
25084a12e66SChristoph Hellwig     if (drv == NULL) {
25116905d71SStefan Hajnoczi         return -ENOENT;
25284a12e66SChristoph Hellwig     }
25384a12e66SChristoph Hellwig 
25484a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
25584a12e66SChristoph Hellwig }
25684a12e66SChristoph Hellwig 
257d5249393Sbellard #ifdef _WIN32
25895389c86Sbellard void get_tmp_filename(char *filename, int size)
259d5249393Sbellard {
2603b9f94e1Sbellard     char temp_dir[MAX_PATH];
2613b9f94e1Sbellard 
2623b9f94e1Sbellard     GetTempPath(MAX_PATH, temp_dir);
2633b9f94e1Sbellard     GetTempFileName(temp_dir, "qem", 0, filename);
264d5249393Sbellard }
265d5249393Sbellard #else
26695389c86Sbellard void get_tmp_filename(char *filename, int size)
267ea2384d3Sbellard {
268ea2384d3Sbellard     int fd;
2697ccfb2ebSblueswir1     const char *tmpdir;
270d5249393Sbellard     /* XXX: race condition possible */
2710badc1eeSaurel32     tmpdir = getenv("TMPDIR");
2720badc1eeSaurel32     if (!tmpdir)
2730badc1eeSaurel32         tmpdir = "/tmp";
2740badc1eeSaurel32     snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
275ea2384d3Sbellard     fd = mkstemp(filename);
276ea2384d3Sbellard     close(fd);
277ea2384d3Sbellard }
278d5249393Sbellard #endif
279ea2384d3Sbellard 
280f3a5d3f8SChristoph Hellwig /*
281f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
282f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
283f3a5d3f8SChristoph Hellwig  */
284f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
285f3a5d3f8SChristoph Hellwig {
286508c7cb3SChristoph Hellwig     int score_max = 0, score;
287508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
288f3a5d3f8SChristoph Hellwig 
2898a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
290508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
291508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
292508c7cb3SChristoph Hellwig             if (score > score_max) {
293508c7cb3SChristoph Hellwig                 score_max = score;
294508c7cb3SChristoph Hellwig                 drv = d;
295f3a5d3f8SChristoph Hellwig             }
296508c7cb3SChristoph Hellwig         }
297f3a5d3f8SChristoph Hellwig     }
298f3a5d3f8SChristoph Hellwig 
299508c7cb3SChristoph Hellwig     return drv;
300f3a5d3f8SChristoph Hellwig }
301f3a5d3f8SChristoph Hellwig 
302b50cbabcSMORITA Kazutaka BlockDriver *bdrv_find_protocol(const char *filename)
30384a12e66SChristoph Hellwig {
30484a12e66SChristoph Hellwig     BlockDriver *drv1;
30584a12e66SChristoph Hellwig     char protocol[128];
30684a12e66SChristoph Hellwig     int len;
30784a12e66SChristoph Hellwig     const char *p;
30884a12e66SChristoph Hellwig 
30966f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
31066f82ceeSKevin Wolf 
31139508e7aSChristoph Hellwig     /*
31239508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
31339508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
31439508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
31539508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
31639508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
31739508e7aSChristoph Hellwig      */
31884a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
31939508e7aSChristoph Hellwig     if (drv1) {
32084a12e66SChristoph Hellwig         return drv1;
32184a12e66SChristoph Hellwig     }
32239508e7aSChristoph Hellwig 
3239e0b22f4SStefan Hajnoczi     if (!path_has_protocol(filename)) {
32439508e7aSChristoph Hellwig         return bdrv_find_format("file");
32539508e7aSChristoph Hellwig     }
3269e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
3279e0b22f4SStefan Hajnoczi     assert(p != NULL);
32884a12e66SChristoph Hellwig     len = p - filename;
32984a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
33084a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
33184a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
33284a12e66SChristoph Hellwig     protocol[len] = '\0';
33384a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
33484a12e66SChristoph Hellwig         if (drv1->protocol_name &&
33584a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
33684a12e66SChristoph Hellwig             return drv1;
33784a12e66SChristoph Hellwig         }
33884a12e66SChristoph Hellwig     }
33984a12e66SChristoph Hellwig     return NULL;
34084a12e66SChristoph Hellwig }
34184a12e66SChristoph Hellwig 
342c98ac35dSStefan Weil static int find_image_format(const char *filename, BlockDriver **pdrv)
343ea2384d3Sbellard {
34483f64091Sbellard     int ret, score, score_max;
345ea2384d3Sbellard     BlockDriver *drv1, *drv;
34683f64091Sbellard     uint8_t buf[2048];
34783f64091Sbellard     BlockDriverState *bs;
348ea2384d3Sbellard 
349f5edb014SNaphtali Sprei     ret = bdrv_file_open(&bs, filename, 0);
350c98ac35dSStefan Weil     if (ret < 0) {
351c98ac35dSStefan Weil         *pdrv = NULL;
352c98ac35dSStefan Weil         return ret;
353c98ac35dSStefan Weil     }
354f8ea0b00SNicholas Bellinger 
35508a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
35608a00559SKevin Wolf     if (bs->sg || !bdrv_is_inserted(bs)) {
3571a396859SNicholas A. Bellinger         bdrv_delete(bs);
358c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
359c98ac35dSStefan Weil         if (!drv) {
360c98ac35dSStefan Weil             ret = -ENOENT;
361c98ac35dSStefan Weil         }
362c98ac35dSStefan Weil         *pdrv = drv;
363c98ac35dSStefan Weil         return ret;
3641a396859SNicholas A. Bellinger     }
365f8ea0b00SNicholas Bellinger 
36683f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
36783f64091Sbellard     bdrv_delete(bs);
368ea2384d3Sbellard     if (ret < 0) {
369c98ac35dSStefan Weil         *pdrv = NULL;
370c98ac35dSStefan Weil         return ret;
371ea2384d3Sbellard     }
372ea2384d3Sbellard 
373ea2384d3Sbellard     score_max = 0;
37484a12e66SChristoph Hellwig     drv = NULL;
3758a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
37683f64091Sbellard         if (drv1->bdrv_probe) {
377ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
378ea2384d3Sbellard             if (score > score_max) {
379ea2384d3Sbellard                 score_max = score;
380ea2384d3Sbellard                 drv = drv1;
381ea2384d3Sbellard             }
382ea2384d3Sbellard         }
38383f64091Sbellard     }
384c98ac35dSStefan Weil     if (!drv) {
385c98ac35dSStefan Weil         ret = -ENOENT;
386c98ac35dSStefan Weil     }
387c98ac35dSStefan Weil     *pdrv = drv;
388c98ac35dSStefan Weil     return ret;
389ea2384d3Sbellard }
390ea2384d3Sbellard 
39151762288SStefan Hajnoczi /**
39251762288SStefan Hajnoczi  * Set the current 'total_sectors' value
39351762288SStefan Hajnoczi  */
39451762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
39551762288SStefan Hajnoczi {
39651762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
39751762288SStefan Hajnoczi 
398396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
399396759adSNicholas Bellinger     if (bs->sg)
400396759adSNicholas Bellinger         return 0;
401396759adSNicholas Bellinger 
40251762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
40351762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
40451762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
40551762288SStefan Hajnoczi         if (length < 0) {
40651762288SStefan Hajnoczi             return length;
40751762288SStefan Hajnoczi         }
40851762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
40951762288SStefan Hajnoczi     }
41051762288SStefan Hajnoczi 
41151762288SStefan Hajnoczi     bs->total_sectors = hint;
41251762288SStefan Hajnoczi     return 0;
41351762288SStefan Hajnoczi }
41451762288SStefan Hajnoczi 
415b6ce07aaSKevin Wolf /*
41657915332SKevin Wolf  * Common part for opening disk images and files
41757915332SKevin Wolf  */
41857915332SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, const char *filename,
41957915332SKevin Wolf     int flags, BlockDriver *drv)
42057915332SKevin Wolf {
42157915332SKevin Wolf     int ret, open_flags;
42257915332SKevin Wolf 
42357915332SKevin Wolf     assert(drv != NULL);
42457915332SKevin Wolf 
42566f82ceeSKevin Wolf     bs->file = NULL;
42651762288SStefan Hajnoczi     bs->total_sectors = 0;
42757915332SKevin Wolf     bs->encrypted = 0;
42857915332SKevin Wolf     bs->valid_key = 0;
42957915332SKevin Wolf     bs->open_flags = flags;
43057915332SKevin Wolf     /* buffer_alignment defaulted to 512, drivers can change this value */
43157915332SKevin Wolf     bs->buffer_alignment = 512;
43257915332SKevin Wolf 
43357915332SKevin Wolf     pstrcpy(bs->filename, sizeof(bs->filename), filename);
43457915332SKevin Wolf 
43557915332SKevin Wolf     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
43657915332SKevin Wolf         return -ENOTSUP;
43757915332SKevin Wolf     }
43857915332SKevin Wolf 
43957915332SKevin Wolf     bs->drv = drv;
44057915332SKevin Wolf     bs->opaque = qemu_mallocz(drv->instance_size);
44157915332SKevin Wolf 
442a6599793SChristoph Hellwig     if (flags & BDRV_O_CACHE_WB)
44357915332SKevin Wolf         bs->enable_write_cache = 1;
44457915332SKevin Wolf 
44557915332SKevin Wolf     /*
44657915332SKevin Wolf      * Clear flags that are internal to the block layer before opening the
44757915332SKevin Wolf      * image.
44857915332SKevin Wolf      */
44957915332SKevin Wolf     open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
45057915332SKevin Wolf 
45157915332SKevin Wolf     /*
452ebabb67aSStefan Weil      * Snapshots should be writable.
45357915332SKevin Wolf      */
45457915332SKevin Wolf     if (bs->is_temporary) {
45557915332SKevin Wolf         open_flags |= BDRV_O_RDWR;
45657915332SKevin Wolf     }
45757915332SKevin Wolf 
45866f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
45966f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
46066f82ceeSKevin Wolf         ret = drv->bdrv_file_open(bs, filename, open_flags);
46166f82ceeSKevin Wolf     } else {
46266f82ceeSKevin Wolf         ret = bdrv_file_open(&bs->file, filename, open_flags);
46366f82ceeSKevin Wolf         if (ret >= 0) {
46466f82ceeSKevin Wolf             ret = drv->bdrv_open(bs, open_flags);
46566f82ceeSKevin Wolf         }
46666f82ceeSKevin Wolf     }
46766f82ceeSKevin Wolf 
46857915332SKevin Wolf     if (ret < 0) {
46957915332SKevin Wolf         goto free_and_fail;
47057915332SKevin Wolf     }
47157915332SKevin Wolf 
47257915332SKevin Wolf     bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
47351762288SStefan Hajnoczi 
47451762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
47551762288SStefan Hajnoczi     if (ret < 0) {
47651762288SStefan Hajnoczi         goto free_and_fail;
47757915332SKevin Wolf     }
47851762288SStefan Hajnoczi 
47957915332SKevin Wolf #ifndef _WIN32
48057915332SKevin Wolf     if (bs->is_temporary) {
48157915332SKevin Wolf         unlink(filename);
48257915332SKevin Wolf     }
48357915332SKevin Wolf #endif
48457915332SKevin Wolf     return 0;
48557915332SKevin Wolf 
48657915332SKevin Wolf free_and_fail:
48766f82ceeSKevin Wolf     if (bs->file) {
48866f82ceeSKevin Wolf         bdrv_delete(bs->file);
48966f82ceeSKevin Wolf         bs->file = NULL;
49066f82ceeSKevin Wolf     }
49157915332SKevin Wolf     qemu_free(bs->opaque);
49257915332SKevin Wolf     bs->opaque = NULL;
49357915332SKevin Wolf     bs->drv = NULL;
49457915332SKevin Wolf     return ret;
49557915332SKevin Wolf }
49657915332SKevin Wolf 
49757915332SKevin Wolf /*
498b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
499b6ce07aaSKevin Wolf  */
50083f64091Sbellard int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
501b338082bSbellard {
50283f64091Sbellard     BlockDriverState *bs;
5036db95603SChristoph Hellwig     BlockDriver *drv;
50483f64091Sbellard     int ret;
5053b0d4f61Sbellard 
506b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
5076db95603SChristoph Hellwig     if (!drv) {
5086db95603SChristoph Hellwig         return -ENOENT;
5096db95603SChristoph Hellwig     }
5106db95603SChristoph Hellwig 
51183f64091Sbellard     bs = bdrv_new("");
512b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
51383f64091Sbellard     if (ret < 0) {
51483f64091Sbellard         bdrv_delete(bs);
51583f64091Sbellard         return ret;
5163b0d4f61Sbellard     }
51771d0770cSaliguori     bs->growable = 1;
51883f64091Sbellard     *pbs = bs;
51983f64091Sbellard     return 0;
5203b0d4f61Sbellard }
5213b0d4f61Sbellard 
522b6ce07aaSKevin Wolf /*
523b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
524b6ce07aaSKevin Wolf  */
525d6e9098eSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
526ea2384d3Sbellard               BlockDriver *drv)
527ea2384d3Sbellard {
528b6ce07aaSKevin Wolf     int ret;
52933e3963eSbellard 
53083f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
531ea2384d3Sbellard         BlockDriverState *bs1;
532ea2384d3Sbellard         int64_t total_size;
5337c96d46eSaliguori         int is_protocol = 0;
53491a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
53591a073a9SKevin Wolf         QEMUOptionParameter *options;
536b6ce07aaSKevin Wolf         char tmp_filename[PATH_MAX];
537b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
53833e3963eSbellard 
539ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
540ea2384d3Sbellard            instead of opening 'filename' directly */
541ea2384d3Sbellard 
542ea2384d3Sbellard         /* if there is a backing file, use it */
543ea2384d3Sbellard         bs1 = bdrv_new("");
544d6e9098eSKevin Wolf         ret = bdrv_open(bs1, filename, 0, drv);
54551d7c00cSaliguori         if (ret < 0) {
546ea2384d3Sbellard             bdrv_delete(bs1);
54751d7c00cSaliguori             return ret;
548ea2384d3Sbellard         }
5493e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
5507c96d46eSaliguori 
5517c96d46eSaliguori         if (bs1->drv && bs1->drv->protocol_name)
5527c96d46eSaliguori             is_protocol = 1;
5537c96d46eSaliguori 
554ea2384d3Sbellard         bdrv_delete(bs1);
555ea2384d3Sbellard 
556ea2384d3Sbellard         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
5577c96d46eSaliguori 
5587c96d46eSaliguori         /* Real path is meaningless for protocols */
5597c96d46eSaliguori         if (is_protocol)
5607c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
5617c96d46eSaliguori                      "%s", filename);
562114cdfa9SKirill A. Shutemov         else if (!realpath(filename, backing_filename))
563114cdfa9SKirill A. Shutemov             return -errno;
5647c96d46eSaliguori 
56591a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
56691a073a9SKevin Wolf         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
56791a073a9SKevin Wolf 
5683e82990bSJes Sorensen         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
56991a073a9SKevin Wolf         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
57091a073a9SKevin Wolf         if (drv) {
57191a073a9SKevin Wolf             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
57291a073a9SKevin Wolf                 drv->format_name);
57391a073a9SKevin Wolf         }
57491a073a9SKevin Wolf 
57591a073a9SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
576d748768cSJan Kiszka         free_option_parameters(options);
57751d7c00cSaliguori         if (ret < 0) {
57851d7c00cSaliguori             return ret;
579ea2384d3Sbellard         }
58091a073a9SKevin Wolf 
581ea2384d3Sbellard         filename = tmp_filename;
58291a073a9SKevin Wolf         drv = bdrv_qcow2;
583ea2384d3Sbellard         bs->is_temporary = 1;
584ea2384d3Sbellard     }
585ea2384d3Sbellard 
586b6ce07aaSKevin Wolf     /* Find the right image format driver */
5876db95603SChristoph Hellwig     if (!drv) {
588c98ac35dSStefan Weil         ret = find_image_format(filename, &drv);
589ea2384d3Sbellard     }
5906987307cSChristoph Hellwig 
59151d7c00cSaliguori     if (!drv) {
59251d7c00cSaliguori         goto unlink_and_fail;
59383f64091Sbellard     }
594b6ce07aaSKevin Wolf 
595b6ce07aaSKevin Wolf     /* Open the image */
596b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
597b6ce07aaSKevin Wolf     if (ret < 0) {
5986987307cSChristoph Hellwig         goto unlink_and_fail;
5996987307cSChristoph Hellwig     }
6006987307cSChristoph Hellwig 
601b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
602b6ce07aaSKevin Wolf     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
603b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
604b6ce07aaSKevin Wolf         int back_flags;
605b6ce07aaSKevin Wolf         BlockDriver *back_drv = NULL;
606b6ce07aaSKevin Wolf 
607b6ce07aaSKevin Wolf         bs->backing_hd = bdrv_new("");
608df2dbb4aSStefan Hajnoczi 
609df2dbb4aSStefan Hajnoczi         if (path_has_protocol(bs->backing_file)) {
610df2dbb4aSStefan Hajnoczi             pstrcpy(backing_filename, sizeof(backing_filename),
611df2dbb4aSStefan Hajnoczi                     bs->backing_file);
612df2dbb4aSStefan Hajnoczi         } else {
613b6ce07aaSKevin Wolf             path_combine(backing_filename, sizeof(backing_filename),
614b6ce07aaSKevin Wolf                          filename, bs->backing_file);
615df2dbb4aSStefan Hajnoczi         }
616df2dbb4aSStefan Hajnoczi 
617df2dbb4aSStefan Hajnoczi         if (bs->backing_format[0] != '\0') {
618b6ce07aaSKevin Wolf             back_drv = bdrv_find_format(bs->backing_format);
619df2dbb4aSStefan Hajnoczi         }
620b6ce07aaSKevin Wolf 
621b6ce07aaSKevin Wolf         /* backing files always opened read-only */
622b6ce07aaSKevin Wolf         back_flags =
623b6ce07aaSKevin Wolf             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
624b6ce07aaSKevin Wolf 
625b6ce07aaSKevin Wolf         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
626b6ce07aaSKevin Wolf         if (ret < 0) {
627b6ce07aaSKevin Wolf             bdrv_close(bs);
628b6ce07aaSKevin Wolf             return ret;
629b6ce07aaSKevin Wolf         }
630b6ce07aaSKevin Wolf         if (bs->is_temporary) {
631b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
632b6ce07aaSKevin Wolf         } else {
633b6ce07aaSKevin Wolf             /* base image inherits from "parent" */
634b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = bs->keep_read_only;
635b6ce07aaSKevin Wolf         }
636b6ce07aaSKevin Wolf     }
637b6ce07aaSKevin Wolf 
638b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
639b6ce07aaSKevin Wolf         /* call the change callback */
640b6ce07aaSKevin Wolf         bs->media_changed = 1;
641b6ce07aaSKevin Wolf         if (bs->change_cb)
642db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
643b6ce07aaSKevin Wolf     }
644b6ce07aaSKevin Wolf 
645b6ce07aaSKevin Wolf     return 0;
646b6ce07aaSKevin Wolf 
647b6ce07aaSKevin Wolf unlink_and_fail:
648b6ce07aaSKevin Wolf     if (bs->is_temporary) {
649b6ce07aaSKevin Wolf         unlink(filename);
650b6ce07aaSKevin Wolf     }
651b6ce07aaSKevin Wolf     return ret;
652b6ce07aaSKevin Wolf }
653b6ce07aaSKevin Wolf 
654fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
655fc01f7e7Sbellard {
65619cb3738Sbellard     if (bs->drv) {
657f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
658f9092b10SMarkus Armbruster             bs_snapshots = NULL;
659f9092b10SMarkus Armbruster         }
660557df6acSStefan Hajnoczi         if (bs->backing_hd) {
661ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
662557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
663557df6acSStefan Hajnoczi         }
664ea2384d3Sbellard         bs->drv->bdrv_close(bs);
665ea2384d3Sbellard         qemu_free(bs->opaque);
666ea2384d3Sbellard #ifdef _WIN32
667ea2384d3Sbellard         if (bs->is_temporary) {
668ea2384d3Sbellard             unlink(bs->filename);
669ea2384d3Sbellard         }
67067b915a5Sbellard #endif
671ea2384d3Sbellard         bs->opaque = NULL;
672ea2384d3Sbellard         bs->drv = NULL;
673b338082bSbellard 
67466f82ceeSKevin Wolf         if (bs->file != NULL) {
67566f82ceeSKevin Wolf             bdrv_close(bs->file);
67666f82ceeSKevin Wolf         }
67766f82ceeSKevin Wolf 
678b338082bSbellard         /* call the change callback */
67919cb3738Sbellard         bs->media_changed = 1;
680b338082bSbellard         if (bs->change_cb)
681db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
682b338082bSbellard     }
683b338082bSbellard }
684b338082bSbellard 
6852bc93fedSMORITA Kazutaka void bdrv_close_all(void)
6862bc93fedSMORITA Kazutaka {
6872bc93fedSMORITA Kazutaka     BlockDriverState *bs;
6882bc93fedSMORITA Kazutaka 
6892bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
6902bc93fedSMORITA Kazutaka         bdrv_close(bs);
6912bc93fedSMORITA Kazutaka     }
6922bc93fedSMORITA Kazutaka }
6932bc93fedSMORITA Kazutaka 
694d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
695d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
696d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
697d22b2f41SRyan Harper {
698d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
699d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
700d22b2f41SRyan Harper     }
701d22b2f41SRyan Harper     bs->device_name[0] = '\0';
702d22b2f41SRyan Harper }
703d22b2f41SRyan Harper 
704b338082bSbellard void bdrv_delete(BlockDriverState *bs)
705b338082bSbellard {
70618846deeSMarkus Armbruster     assert(!bs->peer);
70718846deeSMarkus Armbruster 
7081b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
709d22b2f41SRyan Harper     bdrv_make_anon(bs);
71034c6f050Saurel32 
711b338082bSbellard     bdrv_close(bs);
71266f82ceeSKevin Wolf     if (bs->file != NULL) {
71366f82ceeSKevin Wolf         bdrv_delete(bs->file);
71466f82ceeSKevin Wolf     }
71566f82ceeSKevin Wolf 
716f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
717b338082bSbellard     qemu_free(bs);
718fc01f7e7Sbellard }
719fc01f7e7Sbellard 
72018846deeSMarkus Armbruster int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
72118846deeSMarkus Armbruster {
72218846deeSMarkus Armbruster     if (bs->peer) {
72318846deeSMarkus Armbruster         return -EBUSY;
72418846deeSMarkus Armbruster     }
72518846deeSMarkus Armbruster     bs->peer = qdev;
72618846deeSMarkus Armbruster     return 0;
72718846deeSMarkus Armbruster }
72818846deeSMarkus Armbruster 
72918846deeSMarkus Armbruster void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
73018846deeSMarkus Armbruster {
73118846deeSMarkus Armbruster     assert(bs->peer == qdev);
73218846deeSMarkus Armbruster     bs->peer = NULL;
733a19712b0SMarkus Armbruster     bs->change_cb = NULL;
734a19712b0SMarkus Armbruster     bs->change_opaque = NULL;
73518846deeSMarkus Armbruster }
73618846deeSMarkus Armbruster 
73718846deeSMarkus Armbruster DeviceState *bdrv_get_attached(BlockDriverState *bs)
73818846deeSMarkus Armbruster {
73918846deeSMarkus Armbruster     return bs->peer;
74018846deeSMarkus Armbruster }
74118846deeSMarkus Armbruster 
742e97fc193Saliguori /*
743e97fc193Saliguori  * Run consistency checks on an image
744e97fc193Saliguori  *
745e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
746a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
747e076f338SKevin Wolf  * check are stored in res.
748e97fc193Saliguori  */
749e076f338SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
750e97fc193Saliguori {
751e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
752e97fc193Saliguori         return -ENOTSUP;
753e97fc193Saliguori     }
754e97fc193Saliguori 
755e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
7569ac228e0SKevin Wolf     return bs->drv->bdrv_check(bs, res);
757e97fc193Saliguori }
758e97fc193Saliguori 
7598a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
7608a426614SKevin Wolf 
76133e3963eSbellard /* commit COW file into the raw image */
76233e3963eSbellard int bdrv_commit(BlockDriverState *bs)
76333e3963eSbellard {
76419cb3738Sbellard     BlockDriver *drv = bs->drv;
765ee181196SKevin Wolf     BlockDriver *backing_drv;
7668a426614SKevin Wolf     int64_t sector, total_sectors;
7678a426614SKevin Wolf     int n, ro, open_flags;
7684dca4b63SNaphtali Sprei     int ret = 0, rw_ret = 0;
7698a426614SKevin Wolf     uint8_t *buf;
7704dca4b63SNaphtali Sprei     char filename[1024];
7714dca4b63SNaphtali Sprei     BlockDriverState *bs_rw, *bs_ro;
77233e3963eSbellard 
77319cb3738Sbellard     if (!drv)
77419cb3738Sbellard         return -ENOMEDIUM;
77533e3963eSbellard 
7764dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
7774dca4b63SNaphtali Sprei         return -ENOTSUP;
7784dca4b63SNaphtali Sprei     }
7794dca4b63SNaphtali Sprei 
7804dca4b63SNaphtali Sprei     if (bs->backing_hd->keep_read_only) {
781ea2384d3Sbellard         return -EACCES;
78233e3963eSbellard     }
78333e3963eSbellard 
784ee181196SKevin Wolf     backing_drv = bs->backing_hd->drv;
7854dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
7864dca4b63SNaphtali Sprei     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
7874dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
7884dca4b63SNaphtali Sprei 
7894dca4b63SNaphtali Sprei     if (ro) {
7904dca4b63SNaphtali Sprei         /* re-open as RW */
7914dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
7924dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
7934dca4b63SNaphtali Sprei         bs_rw = bdrv_new("");
794ee181196SKevin Wolf         rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
795ee181196SKevin Wolf             backing_drv);
7964dca4b63SNaphtali Sprei         if (rw_ret < 0) {
7974dca4b63SNaphtali Sprei             bdrv_delete(bs_rw);
7984dca4b63SNaphtali Sprei             /* try to re-open read-only */
7994dca4b63SNaphtali Sprei             bs_ro = bdrv_new("");
800ee181196SKevin Wolf             ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
801ee181196SKevin Wolf                 backing_drv);
8024dca4b63SNaphtali Sprei             if (ret < 0) {
8034dca4b63SNaphtali Sprei                 bdrv_delete(bs_ro);
8044dca4b63SNaphtali Sprei                 /* drive not functional anymore */
8054dca4b63SNaphtali Sprei                 bs->drv = NULL;
8064dca4b63SNaphtali Sprei                 return ret;
8074dca4b63SNaphtali Sprei             }
8084dca4b63SNaphtali Sprei             bs->backing_hd = bs_ro;
8094dca4b63SNaphtali Sprei             return rw_ret;
8104dca4b63SNaphtali Sprei         }
8114dca4b63SNaphtali Sprei         bs->backing_hd = bs_rw;
812ea2384d3Sbellard     }
813ea2384d3Sbellard 
8146ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
8158a426614SKevin Wolf     buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
8168a426614SKevin Wolf 
8178a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
8188a426614SKevin Wolf         if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
8198a426614SKevin Wolf 
8208a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
8214dca4b63SNaphtali Sprei                 ret = -EIO;
8224dca4b63SNaphtali Sprei                 goto ro_cleanup;
82333e3963eSbellard             }
82433e3963eSbellard 
8258a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
8264dca4b63SNaphtali Sprei                 ret = -EIO;
8274dca4b63SNaphtali Sprei                 goto ro_cleanup;
82833e3963eSbellard             }
82933e3963eSbellard         }
83033e3963eSbellard     }
83195389c86Sbellard 
8321d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
8331d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
8341d44952fSChristoph Hellwig         bdrv_flush(bs);
8351d44952fSChristoph Hellwig     }
83695389c86Sbellard 
8373f5075aeSChristoph Hellwig     /*
8383f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
8393f5075aeSChristoph Hellwig      * stable on disk.
8403f5075aeSChristoph Hellwig      */
8413f5075aeSChristoph Hellwig     if (bs->backing_hd)
8423f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
8434dca4b63SNaphtali Sprei 
8444dca4b63SNaphtali Sprei ro_cleanup:
8458a426614SKevin Wolf     qemu_free(buf);
8464dca4b63SNaphtali Sprei 
8474dca4b63SNaphtali Sprei     if (ro) {
8484dca4b63SNaphtali Sprei         /* re-open as RO */
8494dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
8504dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
8514dca4b63SNaphtali Sprei         bs_ro = bdrv_new("");
852ee181196SKevin Wolf         ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
853ee181196SKevin Wolf             backing_drv);
8544dca4b63SNaphtali Sprei         if (ret < 0) {
8554dca4b63SNaphtali Sprei             bdrv_delete(bs_ro);
8564dca4b63SNaphtali Sprei             /* drive not functional anymore */
8574dca4b63SNaphtali Sprei             bs->drv = NULL;
8584dca4b63SNaphtali Sprei             return ret;
8594dca4b63SNaphtali Sprei         }
8604dca4b63SNaphtali Sprei         bs->backing_hd = bs_ro;
8614dca4b63SNaphtali Sprei         bs->backing_hd->keep_read_only = 0;
8624dca4b63SNaphtali Sprei     }
8634dca4b63SNaphtali Sprei 
8641d44952fSChristoph Hellwig     return ret;
86533e3963eSbellard }
86633e3963eSbellard 
8676ab4b5abSMarkus Armbruster void bdrv_commit_all(void)
8686ab4b5abSMarkus Armbruster {
8696ab4b5abSMarkus Armbruster     BlockDriverState *bs;
8706ab4b5abSMarkus Armbruster 
8716ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
8726ab4b5abSMarkus Armbruster         bdrv_commit(bs);
8736ab4b5abSMarkus Armbruster     }
8746ab4b5abSMarkus Armbruster }
8756ab4b5abSMarkus Armbruster 
876756e6736SKevin Wolf /*
877756e6736SKevin Wolf  * Return values:
878756e6736SKevin Wolf  * 0        - success
879756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
880756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
881756e6736SKevin Wolf  *            image file header
882756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
883756e6736SKevin Wolf  */
884756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
885756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
886756e6736SKevin Wolf {
887756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
888756e6736SKevin Wolf 
889756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
890756e6736SKevin Wolf         return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
891756e6736SKevin Wolf     } else {
892756e6736SKevin Wolf         return -ENOTSUP;
893756e6736SKevin Wolf     }
894756e6736SKevin Wolf }
895756e6736SKevin Wolf 
89671d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
89771d0770cSaliguori                                    size_t size)
89871d0770cSaliguori {
89971d0770cSaliguori     int64_t len;
90071d0770cSaliguori 
90171d0770cSaliguori     if (!bdrv_is_inserted(bs))
90271d0770cSaliguori         return -ENOMEDIUM;
90371d0770cSaliguori 
90471d0770cSaliguori     if (bs->growable)
90571d0770cSaliguori         return 0;
90671d0770cSaliguori 
90771d0770cSaliguori     len = bdrv_getlength(bs);
90871d0770cSaliguori 
909fbb7b4e0SKevin Wolf     if (offset < 0)
910fbb7b4e0SKevin Wolf         return -EIO;
911fbb7b4e0SKevin Wolf 
912fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
91371d0770cSaliguori         return -EIO;
91471d0770cSaliguori 
91571d0770cSaliguori     return 0;
91671d0770cSaliguori }
91771d0770cSaliguori 
91871d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
91971d0770cSaliguori                               int nb_sectors)
92071d0770cSaliguori {
921eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
922eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
92371d0770cSaliguori }
92471d0770cSaliguori 
92519cb3738Sbellard /* return < 0 if error. See bdrv_write() for the return codes */
926fc01f7e7Sbellard int bdrv_read(BlockDriverState *bs, int64_t sector_num,
927fc01f7e7Sbellard               uint8_t *buf, int nb_sectors)
928fc01f7e7Sbellard {
929ea2384d3Sbellard     BlockDriver *drv = bs->drv;
930fc01f7e7Sbellard 
93119cb3738Sbellard     if (!drv)
93219cb3738Sbellard         return -ENOMEDIUM;
93371d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
93471d0770cSaliguori         return -EIO;
935b338082bSbellard 
93683f64091Sbellard     return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
93783f64091Sbellard }
938fc01f7e7Sbellard 
9397cd1e32aSlirans@il.ibm.com static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
9407cd1e32aSlirans@il.ibm.com                              int nb_sectors, int dirty)
9417cd1e32aSlirans@il.ibm.com {
9427cd1e32aSlirans@il.ibm.com     int64_t start, end;
943c6d22830SJan Kiszka     unsigned long val, idx, bit;
944a55eb92cSJan Kiszka 
9456ea44308SJan Kiszka     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
946c6d22830SJan Kiszka     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
9477cd1e32aSlirans@il.ibm.com 
9487cd1e32aSlirans@il.ibm.com     for (; start <= end; start++) {
949c6d22830SJan Kiszka         idx = start / (sizeof(unsigned long) * 8);
950c6d22830SJan Kiszka         bit = start % (sizeof(unsigned long) * 8);
951c6d22830SJan Kiszka         val = bs->dirty_bitmap[idx];
952c6d22830SJan Kiszka         if (dirty) {
9536d59fec1SMarcelo Tosatti             if (!(val & (1UL << bit))) {
954aaa0eb75SLiran Schour                 bs->dirty_count++;
9556d59fec1SMarcelo Tosatti                 val |= 1UL << bit;
956aaa0eb75SLiran Schour             }
957c6d22830SJan Kiszka         } else {
9586d59fec1SMarcelo Tosatti             if (val & (1UL << bit)) {
959aaa0eb75SLiran Schour                 bs->dirty_count--;
9606d59fec1SMarcelo Tosatti                 val &= ~(1UL << bit);
961c6d22830SJan Kiszka             }
962aaa0eb75SLiran Schour         }
963c6d22830SJan Kiszka         bs->dirty_bitmap[idx] = val;
9647cd1e32aSlirans@il.ibm.com     }
9657cd1e32aSlirans@il.ibm.com }
9667cd1e32aSlirans@il.ibm.com 
96719cb3738Sbellard /* Return < 0 if error. Important errors are:
96819cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
96919cb3738Sbellard   -ENOMEDIUM   No media inserted.
97019cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
97119cb3738Sbellard   -EACCES      Trying to write a read-only device
97219cb3738Sbellard */
973fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
974fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
975fc01f7e7Sbellard {
97683f64091Sbellard     BlockDriver *drv = bs->drv;
97719cb3738Sbellard     if (!bs->drv)
97819cb3738Sbellard         return -ENOMEDIUM;
9790849bf08Sbellard     if (bs->read_only)
98019cb3738Sbellard         return -EACCES;
98171d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
98271d0770cSaliguori         return -EIO;
98371d0770cSaliguori 
984c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
9857cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
9867cd1e32aSlirans@il.ibm.com     }
9877cd1e32aSlirans@il.ibm.com 
988294cc35fSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
989294cc35fSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
990294cc35fSKevin Wolf     }
991294cc35fSKevin Wolf 
99283f64091Sbellard     return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
99383f64091Sbellard }
99483f64091Sbellard 
995eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
996eda578e5Saliguori                void *buf, int count1)
99783f64091Sbellard {
9986ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
99983f64091Sbellard     int len, nb_sectors, count;
100083f64091Sbellard     int64_t sector_num;
10019a8c4cceSKevin Wolf     int ret;
100283f64091Sbellard 
100383f64091Sbellard     count = count1;
100483f64091Sbellard     /* first read to align to sector start */
10056ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
100683f64091Sbellard     if (len > count)
100783f64091Sbellard         len = count;
10086ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
100983f64091Sbellard     if (len > 0) {
10109a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10119a8c4cceSKevin Wolf             return ret;
10126ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
101383f64091Sbellard         count -= len;
101483f64091Sbellard         if (count == 0)
101583f64091Sbellard             return count1;
101683f64091Sbellard         sector_num++;
101783f64091Sbellard         buf += len;
101883f64091Sbellard     }
101983f64091Sbellard 
102083f64091Sbellard     /* read the sectors "in place" */
10216ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
102283f64091Sbellard     if (nb_sectors > 0) {
10239a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
10249a8c4cceSKevin Wolf             return ret;
102583f64091Sbellard         sector_num += nb_sectors;
10266ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
102783f64091Sbellard         buf += len;
102883f64091Sbellard         count -= len;
102983f64091Sbellard     }
103083f64091Sbellard 
103183f64091Sbellard     /* add data from the last sector */
103283f64091Sbellard     if (count > 0) {
10339a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10349a8c4cceSKevin Wolf             return ret;
103583f64091Sbellard         memcpy(buf, tmp_buf, count);
103683f64091Sbellard     }
103783f64091Sbellard     return count1;
103883f64091Sbellard }
103983f64091Sbellard 
1040eda578e5Saliguori int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1041eda578e5Saliguori                 const void *buf, int count1)
104283f64091Sbellard {
10436ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
104483f64091Sbellard     int len, nb_sectors, count;
104583f64091Sbellard     int64_t sector_num;
10469a8c4cceSKevin Wolf     int ret;
104783f64091Sbellard 
104883f64091Sbellard     count = count1;
104983f64091Sbellard     /* first write to align to sector start */
10506ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
105183f64091Sbellard     if (len > count)
105283f64091Sbellard         len = count;
10536ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
105483f64091Sbellard     if (len > 0) {
10559a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10569a8c4cceSKevin Wolf             return ret;
10576ea44308SJan Kiszka         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
10589a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
10599a8c4cceSKevin Wolf             return ret;
106083f64091Sbellard         count -= len;
106183f64091Sbellard         if (count == 0)
106283f64091Sbellard             return count1;
106383f64091Sbellard         sector_num++;
106483f64091Sbellard         buf += len;
106583f64091Sbellard     }
106683f64091Sbellard 
106783f64091Sbellard     /* write the sectors "in place" */
10686ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
106983f64091Sbellard     if (nb_sectors > 0) {
10709a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
10719a8c4cceSKevin Wolf             return ret;
107283f64091Sbellard         sector_num += nb_sectors;
10736ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
107483f64091Sbellard         buf += len;
107583f64091Sbellard         count -= len;
107683f64091Sbellard     }
107783f64091Sbellard 
107883f64091Sbellard     /* add data from the last sector */
107983f64091Sbellard     if (count > 0) {
10809a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10819a8c4cceSKevin Wolf             return ret;
108283f64091Sbellard         memcpy(tmp_buf, buf, count);
10839a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
10849a8c4cceSKevin Wolf             return ret;
108583f64091Sbellard     }
108683f64091Sbellard     return count1;
108783f64091Sbellard }
108883f64091Sbellard 
1089f08145feSKevin Wolf /*
1090f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1091f08145feSKevin Wolf  * request (acts as a barrier)
1092f08145feSKevin Wolf  *
1093f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1094f08145feSKevin Wolf  */
1095f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1096f08145feSKevin Wolf     const void *buf, int count)
1097f08145feSKevin Wolf {
1098f08145feSKevin Wolf     int ret;
1099f08145feSKevin Wolf 
1100f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
1101f08145feSKevin Wolf     if (ret < 0) {
1102f08145feSKevin Wolf         return ret;
1103f08145feSKevin Wolf     }
1104f08145feSKevin Wolf 
1105f08145feSKevin Wolf     /* No flush needed for cache=writethrough, it uses O_DSYNC */
1106f08145feSKevin Wolf     if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1107f08145feSKevin Wolf         bdrv_flush(bs);
1108f08145feSKevin Wolf     }
1109f08145feSKevin Wolf 
1110f08145feSKevin Wolf     return 0;
1111f08145feSKevin Wolf }
1112f08145feSKevin Wolf 
1113f08145feSKevin Wolf /*
1114f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1115f08145feSKevin Wolf  * request (acts as a barrier)
1116f08145feSKevin Wolf  *
1117f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1118f08145feSKevin Wolf  */
1119f08145feSKevin Wolf int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1120f08145feSKevin Wolf     const uint8_t *buf, int nb_sectors)
1121f08145feSKevin Wolf {
1122f08145feSKevin Wolf     return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1123f08145feSKevin Wolf         buf, BDRV_SECTOR_SIZE * nb_sectors);
1124f08145feSKevin Wolf }
1125f08145feSKevin Wolf 
112683f64091Sbellard /**
112783f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
112883f64091Sbellard  */
112983f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
113083f64091Sbellard {
113183f64091Sbellard     BlockDriver *drv = bs->drv;
113251762288SStefan Hajnoczi     int ret;
113383f64091Sbellard     if (!drv)
113419cb3738Sbellard         return -ENOMEDIUM;
113583f64091Sbellard     if (!drv->bdrv_truncate)
113683f64091Sbellard         return -ENOTSUP;
113759f2689dSNaphtali Sprei     if (bs->read_only)
113859f2689dSNaphtali Sprei         return -EACCES;
11398591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
11408591675fSMarcelo Tosatti         return -EBUSY;
114151762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
114251762288SStefan Hajnoczi     if (ret == 0) {
114351762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1144db97ee6aSChristoph Hellwig         if (bs->change_cb) {
1145db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1146db97ee6aSChristoph Hellwig         }
114751762288SStefan Hajnoczi     }
114851762288SStefan Hajnoczi     return ret;
114983f64091Sbellard }
115083f64091Sbellard 
115183f64091Sbellard /**
11524a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
11534a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
11544a1d5e1fSFam Zheng  */
11554a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
11564a1d5e1fSFam Zheng {
11574a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
11584a1d5e1fSFam Zheng     if (!drv) {
11594a1d5e1fSFam Zheng         return -ENOMEDIUM;
11604a1d5e1fSFam Zheng     }
11614a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
11624a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
11634a1d5e1fSFam Zheng     }
11644a1d5e1fSFam Zheng     if (bs->file) {
11654a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
11664a1d5e1fSFam Zheng     }
11674a1d5e1fSFam Zheng     return -ENOTSUP;
11684a1d5e1fSFam Zheng }
11694a1d5e1fSFam Zheng 
11704a1d5e1fSFam Zheng /**
117183f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
117283f64091Sbellard  */
117383f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
117483f64091Sbellard {
117583f64091Sbellard     BlockDriver *drv = bs->drv;
117683f64091Sbellard     if (!drv)
117719cb3738Sbellard         return -ENOMEDIUM;
117851762288SStefan Hajnoczi 
117946a4e4e6SStefan Hajnoczi     if (bs->growable || bs->removable) {
118046a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
118183f64091Sbellard             return drv->bdrv_getlength(bs);
1182fc01f7e7Sbellard         }
118346a4e4e6SStefan Hajnoczi     }
118446a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
118546a4e4e6SStefan Hajnoczi }
1186fc01f7e7Sbellard 
118719cb3738Sbellard /* return 0 as number of sectors if no device present or error */
118896b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1189fc01f7e7Sbellard {
119019cb3738Sbellard     int64_t length;
119119cb3738Sbellard     length = bdrv_getlength(bs);
119219cb3738Sbellard     if (length < 0)
119319cb3738Sbellard         length = 0;
119419cb3738Sbellard     else
11956ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
119619cb3738Sbellard     *nb_sectors_ptr = length;
1197fc01f7e7Sbellard }
1198cf98951bSbellard 
1199f3d54fc4Saliguori struct partition {
1200f3d54fc4Saliguori         uint8_t boot_ind;           /* 0x80 - active */
1201f3d54fc4Saliguori         uint8_t head;               /* starting head */
1202f3d54fc4Saliguori         uint8_t sector;             /* starting sector */
1203f3d54fc4Saliguori         uint8_t cyl;                /* starting cylinder */
1204f3d54fc4Saliguori         uint8_t sys_ind;            /* What partition type */
1205f3d54fc4Saliguori         uint8_t end_head;           /* end head */
1206f3d54fc4Saliguori         uint8_t end_sector;         /* end sector */
1207f3d54fc4Saliguori         uint8_t end_cyl;            /* end cylinder */
1208f3d54fc4Saliguori         uint32_t start_sect;        /* starting sector counting from 0 */
1209f3d54fc4Saliguori         uint32_t nr_sects;          /* nr of sectors in partition */
1210f3d54fc4Saliguori } __attribute__((packed));
1211f3d54fc4Saliguori 
1212f3d54fc4Saliguori /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1213f3d54fc4Saliguori static int guess_disk_lchs(BlockDriverState *bs,
1214f3d54fc4Saliguori                            int *pcylinders, int *pheads, int *psectors)
1215f3d54fc4Saliguori {
1216eb5a3165SJes Sorensen     uint8_t buf[BDRV_SECTOR_SIZE];
1217f3d54fc4Saliguori     int ret, i, heads, sectors, cylinders;
1218f3d54fc4Saliguori     struct partition *p;
1219f3d54fc4Saliguori     uint32_t nr_sects;
1220a38131b6Sblueswir1     uint64_t nb_sectors;
1221f3d54fc4Saliguori 
1222f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1223f3d54fc4Saliguori 
1224f3d54fc4Saliguori     ret = bdrv_read(bs, 0, buf, 1);
1225f3d54fc4Saliguori     if (ret < 0)
1226f3d54fc4Saliguori         return -1;
1227f3d54fc4Saliguori     /* test msdos magic */
1228f3d54fc4Saliguori     if (buf[510] != 0x55 || buf[511] != 0xaa)
1229f3d54fc4Saliguori         return -1;
1230f3d54fc4Saliguori     for(i = 0; i < 4; i++) {
1231f3d54fc4Saliguori         p = ((struct partition *)(buf + 0x1be)) + i;
1232f3d54fc4Saliguori         nr_sects = le32_to_cpu(p->nr_sects);
1233f3d54fc4Saliguori         if (nr_sects && p->end_head) {
1234f3d54fc4Saliguori             /* We make the assumption that the partition terminates on
1235f3d54fc4Saliguori                a cylinder boundary */
1236f3d54fc4Saliguori             heads = p->end_head + 1;
1237f3d54fc4Saliguori             sectors = p->end_sector & 63;
1238f3d54fc4Saliguori             if (sectors == 0)
1239f3d54fc4Saliguori                 continue;
1240f3d54fc4Saliguori             cylinders = nb_sectors / (heads * sectors);
1241f3d54fc4Saliguori             if (cylinders < 1 || cylinders > 16383)
1242f3d54fc4Saliguori                 continue;
1243f3d54fc4Saliguori             *pheads = heads;
1244f3d54fc4Saliguori             *psectors = sectors;
1245f3d54fc4Saliguori             *pcylinders = cylinders;
1246f3d54fc4Saliguori #if 0
1247f3d54fc4Saliguori             printf("guessed geometry: LCHS=%d %d %d\n",
1248f3d54fc4Saliguori                    cylinders, heads, sectors);
1249f3d54fc4Saliguori #endif
1250f3d54fc4Saliguori             return 0;
1251f3d54fc4Saliguori         }
1252f3d54fc4Saliguori     }
1253f3d54fc4Saliguori     return -1;
1254f3d54fc4Saliguori }
1255f3d54fc4Saliguori 
1256f3d54fc4Saliguori void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1257f3d54fc4Saliguori {
1258f3d54fc4Saliguori     int translation, lba_detected = 0;
1259f3d54fc4Saliguori     int cylinders, heads, secs;
1260a38131b6Sblueswir1     uint64_t nb_sectors;
1261f3d54fc4Saliguori 
1262f3d54fc4Saliguori     /* if a geometry hint is available, use it */
1263f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1264f3d54fc4Saliguori     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1265f3d54fc4Saliguori     translation = bdrv_get_translation_hint(bs);
1266f3d54fc4Saliguori     if (cylinders != 0) {
1267f3d54fc4Saliguori         *pcyls = cylinders;
1268f3d54fc4Saliguori         *pheads = heads;
1269f3d54fc4Saliguori         *psecs = secs;
1270f3d54fc4Saliguori     } else {
1271f3d54fc4Saliguori         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1272f3d54fc4Saliguori             if (heads > 16) {
1273f3d54fc4Saliguori                 /* if heads > 16, it means that a BIOS LBA
1274f3d54fc4Saliguori                    translation was active, so the default
1275f3d54fc4Saliguori                    hardware geometry is OK */
1276f3d54fc4Saliguori                 lba_detected = 1;
1277f3d54fc4Saliguori                 goto default_geometry;
1278f3d54fc4Saliguori             } else {
1279f3d54fc4Saliguori                 *pcyls = cylinders;
1280f3d54fc4Saliguori                 *pheads = heads;
1281f3d54fc4Saliguori                 *psecs = secs;
1282f3d54fc4Saliguori                 /* disable any translation to be in sync with
1283f3d54fc4Saliguori                    the logical geometry */
1284f3d54fc4Saliguori                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1285f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1286f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_NONE);
1287f3d54fc4Saliguori                 }
1288f3d54fc4Saliguori             }
1289f3d54fc4Saliguori         } else {
1290f3d54fc4Saliguori         default_geometry:
1291f3d54fc4Saliguori             /* if no geometry, use a standard physical disk geometry */
1292f3d54fc4Saliguori             cylinders = nb_sectors / (16 * 63);
1293f3d54fc4Saliguori 
1294f3d54fc4Saliguori             if (cylinders > 16383)
1295f3d54fc4Saliguori                 cylinders = 16383;
1296f3d54fc4Saliguori             else if (cylinders < 2)
1297f3d54fc4Saliguori                 cylinders = 2;
1298f3d54fc4Saliguori             *pcyls = cylinders;
1299f3d54fc4Saliguori             *pheads = 16;
1300f3d54fc4Saliguori             *psecs = 63;
1301f3d54fc4Saliguori             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1302f3d54fc4Saliguori                 if ((*pcyls * *pheads) <= 131072) {
1303f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1304f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LARGE);
1305f3d54fc4Saliguori                 } else {
1306f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1307f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LBA);
1308f3d54fc4Saliguori                 }
1309f3d54fc4Saliguori             }
1310f3d54fc4Saliguori         }
1311f3d54fc4Saliguori         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1312f3d54fc4Saliguori     }
1313f3d54fc4Saliguori }
1314f3d54fc4Saliguori 
1315b338082bSbellard void bdrv_set_geometry_hint(BlockDriverState *bs,
1316b338082bSbellard                             int cyls, int heads, int secs)
1317b338082bSbellard {
1318b338082bSbellard     bs->cyls = cyls;
1319b338082bSbellard     bs->heads = heads;
1320b338082bSbellard     bs->secs = secs;
1321b338082bSbellard }
1322b338082bSbellard 
132346d4767dSbellard void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
132446d4767dSbellard {
132546d4767dSbellard     bs->translation = translation;
132646d4767dSbellard }
132746d4767dSbellard 
1328b338082bSbellard void bdrv_get_geometry_hint(BlockDriverState *bs,
1329b338082bSbellard                             int *pcyls, int *pheads, int *psecs)
1330b338082bSbellard {
1331b338082bSbellard     *pcyls = bs->cyls;
1332b338082bSbellard     *pheads = bs->heads;
1333b338082bSbellard     *psecs = bs->secs;
1334b338082bSbellard }
1335b338082bSbellard 
13365bbdbb46SBlue Swirl /* Recognize floppy formats */
13375bbdbb46SBlue Swirl typedef struct FDFormat {
13385bbdbb46SBlue Swirl     FDriveType drive;
13395bbdbb46SBlue Swirl     uint8_t last_sect;
13405bbdbb46SBlue Swirl     uint8_t max_track;
13415bbdbb46SBlue Swirl     uint8_t max_head;
13425bbdbb46SBlue Swirl } FDFormat;
13435bbdbb46SBlue Swirl 
13445bbdbb46SBlue Swirl static const FDFormat fd_formats[] = {
13455bbdbb46SBlue Swirl     /* First entry is default format */
13465bbdbb46SBlue Swirl     /* 1.44 MB 3"1/2 floppy disks */
13475bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 18, 80, 1, },
13485bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 20, 80, 1, },
13495bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 21, 80, 1, },
13505bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 21, 82, 1, },
13515bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 21, 83, 1, },
13525bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 22, 80, 1, },
13535bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 23, 80, 1, },
13545bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 24, 80, 1, },
13555bbdbb46SBlue Swirl     /* 2.88 MB 3"1/2 floppy disks */
13565bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 36, 80, 1, },
13575bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 39, 80, 1, },
13585bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 40, 80, 1, },
13595bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 44, 80, 1, },
13605bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 48, 80, 1, },
13615bbdbb46SBlue Swirl     /* 720 kB 3"1/2 floppy disks */
13625bbdbb46SBlue Swirl     { FDRIVE_DRV_144,  9, 80, 1, },
13635bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 10, 80, 1, },
13645bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 10, 82, 1, },
13655bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 10, 83, 1, },
13665bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 13, 80, 1, },
13675bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 14, 80, 1, },
13685bbdbb46SBlue Swirl     /* 1.2 MB 5"1/4 floppy disks */
13695bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 15, 80, 1, },
13705bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 18, 80, 1, },
13715bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 18, 82, 1, },
13725bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 18, 83, 1, },
13735bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 20, 80, 1, },
13745bbdbb46SBlue Swirl     /* 720 kB 5"1/4 floppy disks */
13755bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  9, 80, 1, },
13765bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 11, 80, 1, },
13775bbdbb46SBlue Swirl     /* 360 kB 5"1/4 floppy disks */
13785bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  9, 40, 1, },
13795bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  9, 40, 0, },
13805bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 10, 41, 1, },
13815bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 10, 42, 1, },
13825bbdbb46SBlue Swirl     /* 320 kB 5"1/4 floppy disks */
13835bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  8, 40, 1, },
13845bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  8, 40, 0, },
13855bbdbb46SBlue Swirl     /* 360 kB must match 5"1/4 better than 3"1/2... */
13865bbdbb46SBlue Swirl     { FDRIVE_DRV_144,  9, 80, 0, },
13875bbdbb46SBlue Swirl     /* end */
13885bbdbb46SBlue Swirl     { FDRIVE_DRV_NONE, -1, -1, 0, },
13895bbdbb46SBlue Swirl };
13905bbdbb46SBlue Swirl 
13915bbdbb46SBlue Swirl void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
13925bbdbb46SBlue Swirl                                    int *max_track, int *last_sect,
13935bbdbb46SBlue Swirl                                    FDriveType drive_in, FDriveType *drive)
13945bbdbb46SBlue Swirl {
13955bbdbb46SBlue Swirl     const FDFormat *parse;
13965bbdbb46SBlue Swirl     uint64_t nb_sectors, size;
13975bbdbb46SBlue Swirl     int i, first_match, match;
13985bbdbb46SBlue Swirl 
13995bbdbb46SBlue Swirl     bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
14005bbdbb46SBlue Swirl     if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
14015bbdbb46SBlue Swirl         /* User defined disk */
14025bbdbb46SBlue Swirl     } else {
14035bbdbb46SBlue Swirl         bdrv_get_geometry(bs, &nb_sectors);
14045bbdbb46SBlue Swirl         match = -1;
14055bbdbb46SBlue Swirl         first_match = -1;
14065bbdbb46SBlue Swirl         for (i = 0; ; i++) {
14075bbdbb46SBlue Swirl             parse = &fd_formats[i];
14085bbdbb46SBlue Swirl             if (parse->drive == FDRIVE_DRV_NONE) {
14095bbdbb46SBlue Swirl                 break;
14105bbdbb46SBlue Swirl             }
14115bbdbb46SBlue Swirl             if (drive_in == parse->drive ||
14125bbdbb46SBlue Swirl                 drive_in == FDRIVE_DRV_NONE) {
14135bbdbb46SBlue Swirl                 size = (parse->max_head + 1) * parse->max_track *
14145bbdbb46SBlue Swirl                     parse->last_sect;
14155bbdbb46SBlue Swirl                 if (nb_sectors == size) {
14165bbdbb46SBlue Swirl                     match = i;
14175bbdbb46SBlue Swirl                     break;
14185bbdbb46SBlue Swirl                 }
14195bbdbb46SBlue Swirl                 if (first_match == -1) {
14205bbdbb46SBlue Swirl                     first_match = i;
14215bbdbb46SBlue Swirl                 }
14225bbdbb46SBlue Swirl             }
14235bbdbb46SBlue Swirl         }
14245bbdbb46SBlue Swirl         if (match == -1) {
14255bbdbb46SBlue Swirl             if (first_match == -1) {
14265bbdbb46SBlue Swirl                 match = 1;
14275bbdbb46SBlue Swirl             } else {
14285bbdbb46SBlue Swirl                 match = first_match;
14295bbdbb46SBlue Swirl             }
14305bbdbb46SBlue Swirl             parse = &fd_formats[match];
14315bbdbb46SBlue Swirl         }
14325bbdbb46SBlue Swirl         *nb_heads = parse->max_head + 1;
14335bbdbb46SBlue Swirl         *max_track = parse->max_track;
14345bbdbb46SBlue Swirl         *last_sect = parse->last_sect;
14355bbdbb46SBlue Swirl         *drive = parse->drive;
14365bbdbb46SBlue Swirl     }
14375bbdbb46SBlue Swirl }
14385bbdbb46SBlue Swirl 
143946d4767dSbellard int bdrv_get_translation_hint(BlockDriverState *bs)
144046d4767dSbellard {
144146d4767dSbellard     return bs->translation;
144246d4767dSbellard }
144346d4767dSbellard 
1444abd7f68dSMarkus Armbruster void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1445abd7f68dSMarkus Armbruster                        BlockErrorAction on_write_error)
1446abd7f68dSMarkus Armbruster {
1447abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
1448abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
1449abd7f68dSMarkus Armbruster }
1450abd7f68dSMarkus Armbruster 
1451abd7f68dSMarkus Armbruster BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1452abd7f68dSMarkus Armbruster {
1453abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
1454abd7f68dSMarkus Armbruster }
1455abd7f68dSMarkus Armbruster 
14567d0d6950SMarkus Armbruster void bdrv_set_removable(BlockDriverState *bs, int removable)
14577d0d6950SMarkus Armbruster {
14587d0d6950SMarkus Armbruster     bs->removable = removable;
14597d0d6950SMarkus Armbruster     if (removable && bs == bs_snapshots) {
14607d0d6950SMarkus Armbruster         bs_snapshots = NULL;
14617d0d6950SMarkus Armbruster     }
14627d0d6950SMarkus Armbruster }
14637d0d6950SMarkus Armbruster 
1464b338082bSbellard int bdrv_is_removable(BlockDriverState *bs)
1465b338082bSbellard {
1466b338082bSbellard     return bs->removable;
1467b338082bSbellard }
1468b338082bSbellard 
1469b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
1470b338082bSbellard {
1471b338082bSbellard     return bs->read_only;
1472b338082bSbellard }
1473b338082bSbellard 
1474985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
1475985a03b0Sths {
1476985a03b0Sths     return bs->sg;
1477985a03b0Sths }
1478985a03b0Sths 
1479e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
1480e900a7b7SChristoph Hellwig {
1481e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
1482e900a7b7SChristoph Hellwig }
1483e900a7b7SChristoph Hellwig 
148419cb3738Sbellard /* XXX: no longer used */
1485b338082bSbellard void bdrv_set_change_cb(BlockDriverState *bs,
1486db97ee6aSChristoph Hellwig                         void (*change_cb)(void *opaque, int reason),
1487db97ee6aSChristoph Hellwig                         void *opaque)
1488b338082bSbellard {
1489b338082bSbellard     bs->change_cb = change_cb;
1490b338082bSbellard     bs->change_opaque = opaque;
1491b338082bSbellard }
1492b338082bSbellard 
1493ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
1494ea2384d3Sbellard {
1495ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
1496ea2384d3Sbellard         return 1;
1497ea2384d3Sbellard     return bs->encrypted;
1498ea2384d3Sbellard }
1499ea2384d3Sbellard 
1500c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
1501c0f4ce77Saliguori {
1502c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
1503c0f4ce77Saliguori 
1504c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1505c0f4ce77Saliguori         return 1;
1506c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
1507c0f4ce77Saliguori }
1508c0f4ce77Saliguori 
1509ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
1510ea2384d3Sbellard {
1511ea2384d3Sbellard     int ret;
1512ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
1513ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
1514ea2384d3Sbellard         if (ret < 0)
1515ea2384d3Sbellard             return ret;
1516ea2384d3Sbellard         if (!bs->encrypted)
1517ea2384d3Sbellard             return 0;
1518ea2384d3Sbellard     }
1519fd04a2aeSShahar Havivi     if (!bs->encrypted) {
1520fd04a2aeSShahar Havivi         return -EINVAL;
1521fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1522fd04a2aeSShahar Havivi         return -ENOMEDIUM;
1523fd04a2aeSShahar Havivi     }
1524c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
1525bb5fc20fSaliguori     if (ret < 0) {
1526bb5fc20fSaliguori         bs->valid_key = 0;
1527bb5fc20fSaliguori     } else if (!bs->valid_key) {
1528bb5fc20fSaliguori         bs->valid_key = 1;
1529bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
1530bb5fc20fSaliguori         bs->media_changed = 1;
1531bb5fc20fSaliguori         if (bs->change_cb)
1532db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
1533bb5fc20fSaliguori     }
1534c0f4ce77Saliguori     return ret;
1535ea2384d3Sbellard }
1536ea2384d3Sbellard 
1537ea2384d3Sbellard void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1538ea2384d3Sbellard {
153919cb3738Sbellard     if (!bs->drv) {
1540ea2384d3Sbellard         buf[0] = '\0';
1541ea2384d3Sbellard     } else {
1542ea2384d3Sbellard         pstrcpy(buf, buf_size, bs->drv->format_name);
1543ea2384d3Sbellard     }
1544ea2384d3Sbellard }
1545ea2384d3Sbellard 
1546ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1547ea2384d3Sbellard                          void *opaque)
1548ea2384d3Sbellard {
1549ea2384d3Sbellard     BlockDriver *drv;
1550ea2384d3Sbellard 
15518a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
1552ea2384d3Sbellard         it(opaque, drv->format_name);
1553ea2384d3Sbellard     }
1554ea2384d3Sbellard }
1555ea2384d3Sbellard 
1556b338082bSbellard BlockDriverState *bdrv_find(const char *name)
1557b338082bSbellard {
1558b338082bSbellard     BlockDriverState *bs;
1559b338082bSbellard 
15601b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
15611b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
1562b338082bSbellard             return bs;
1563b338082bSbellard         }
15641b7bdbc1SStefan Hajnoczi     }
1565b338082bSbellard     return NULL;
1566b338082bSbellard }
1567b338082bSbellard 
15682f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
15692f399b0aSMarkus Armbruster {
15702f399b0aSMarkus Armbruster     if (!bs) {
15712f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
15722f399b0aSMarkus Armbruster     }
15732f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
15742f399b0aSMarkus Armbruster }
15752f399b0aSMarkus Armbruster 
157651de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
157781d0912dSbellard {
157881d0912dSbellard     BlockDriverState *bs;
157981d0912dSbellard 
15801b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
158151de9760Saliguori         it(opaque, bs);
158281d0912dSbellard     }
158381d0912dSbellard }
158481d0912dSbellard 
1585ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
1586ea2384d3Sbellard {
1587ea2384d3Sbellard     return bs->device_name;
1588ea2384d3Sbellard }
1589ea2384d3Sbellard 
1590205ef796SKevin Wolf int bdrv_flush(BlockDriverState *bs)
15917a6cba61Spbrook {
1592016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
1593205ef796SKevin Wolf         return 0;
1594016f5cf6SAlexander Graf     }
1595016f5cf6SAlexander Graf 
1596205ef796SKevin Wolf     if (bs->drv && bs->drv->bdrv_flush) {
1597205ef796SKevin Wolf         return bs->drv->bdrv_flush(bs);
1598205ef796SKevin Wolf     }
1599205ef796SKevin Wolf 
1600205ef796SKevin Wolf     /*
1601205ef796SKevin Wolf      * Some block drivers always operate in either writethrough or unsafe mode
1602205ef796SKevin Wolf      * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1603205ef796SKevin Wolf      * the server works (because the behaviour is hardcoded or depends on
1604205ef796SKevin Wolf      * server-side configuration), so we can't ensure that everything is safe
1605205ef796SKevin Wolf      * on disk. Returning an error doesn't work because that would break guests
1606205ef796SKevin Wolf      * even if the server operates in writethrough mode.
1607205ef796SKevin Wolf      *
1608205ef796SKevin Wolf      * Let's hope the user knows what he's doing.
1609205ef796SKevin Wolf      */
1610205ef796SKevin Wolf     return 0;
16117a6cba61Spbrook }
16127a6cba61Spbrook 
1613c6ca28d6Saliguori void bdrv_flush_all(void)
1614c6ca28d6Saliguori {
1615c6ca28d6Saliguori     BlockDriverState *bs;
1616c6ca28d6Saliguori 
16171b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1618c6ca28d6Saliguori         if (bs->drv && !bdrv_is_read_only(bs) &&
16191b7bdbc1SStefan Hajnoczi             (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1620c6ca28d6Saliguori             bdrv_flush(bs);
1621c6ca28d6Saliguori         }
16221b7bdbc1SStefan Hajnoczi     }
16231b7bdbc1SStefan Hajnoczi }
1624c6ca28d6Saliguori 
1625f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
1626f2feebbdSKevin Wolf {
1627f2feebbdSKevin Wolf     assert(bs->drv);
1628f2feebbdSKevin Wolf 
1629336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
1630336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
1631f2feebbdSKevin Wolf     }
1632f2feebbdSKevin Wolf 
1633f2feebbdSKevin Wolf     return 1;
1634f2feebbdSKevin Wolf }
1635f2feebbdSKevin Wolf 
1636bb8bf76fSChristoph Hellwig int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1637bb8bf76fSChristoph Hellwig {
1638bb8bf76fSChristoph Hellwig     if (!bs->drv) {
1639bb8bf76fSChristoph Hellwig         return -ENOMEDIUM;
1640bb8bf76fSChristoph Hellwig     }
1641bb8bf76fSChristoph Hellwig     if (!bs->drv->bdrv_discard) {
1642bb8bf76fSChristoph Hellwig         return 0;
1643bb8bf76fSChristoph Hellwig     }
1644bb8bf76fSChristoph Hellwig     return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1645bb8bf76fSChristoph Hellwig }
1646bb8bf76fSChristoph Hellwig 
1647f58c7b35Sths /*
1648f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
1649f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
1650f58c7b35Sths  * hence all their sectors are reported as allocated.
1651f58c7b35Sths  *
1652f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
1653f58c7b35Sths  * the specified sector) that are known to be in the same
1654f58c7b35Sths  * allocated/unallocated state.
1655f58c7b35Sths  *
1656f58c7b35Sths  * 'nb_sectors' is the max value 'pnum' should be set to.
1657f58c7b35Sths  */
1658f58c7b35Sths int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1659f58c7b35Sths 	int *pnum)
1660f58c7b35Sths {
1661f58c7b35Sths     int64_t n;
1662f58c7b35Sths     if (!bs->drv->bdrv_is_allocated) {
1663f58c7b35Sths         if (sector_num >= bs->total_sectors) {
1664f58c7b35Sths             *pnum = 0;
1665f58c7b35Sths             return 0;
1666f58c7b35Sths         }
1667f58c7b35Sths         n = bs->total_sectors - sector_num;
1668f58c7b35Sths         *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1669f58c7b35Sths         return 1;
1670f58c7b35Sths     }
1671f58c7b35Sths     return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1672f58c7b35Sths }
1673f58c7b35Sths 
16742582bfedSLuiz Capitulino void bdrv_mon_event(const BlockDriverState *bdrv,
16752582bfedSLuiz Capitulino                     BlockMonEventAction action, int is_read)
16762582bfedSLuiz Capitulino {
16772582bfedSLuiz Capitulino     QObject *data;
16782582bfedSLuiz Capitulino     const char *action_str;
16792582bfedSLuiz Capitulino 
16802582bfedSLuiz Capitulino     switch (action) {
16812582bfedSLuiz Capitulino     case BDRV_ACTION_REPORT:
16822582bfedSLuiz Capitulino         action_str = "report";
16832582bfedSLuiz Capitulino         break;
16842582bfedSLuiz Capitulino     case BDRV_ACTION_IGNORE:
16852582bfedSLuiz Capitulino         action_str = "ignore";
16862582bfedSLuiz Capitulino         break;
16872582bfedSLuiz Capitulino     case BDRV_ACTION_STOP:
16882582bfedSLuiz Capitulino         action_str = "stop";
16892582bfedSLuiz Capitulino         break;
16902582bfedSLuiz Capitulino     default:
16912582bfedSLuiz Capitulino         abort();
16922582bfedSLuiz Capitulino     }
16932582bfedSLuiz Capitulino 
16942582bfedSLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
16952582bfedSLuiz Capitulino                               bdrv->device_name,
16962582bfedSLuiz Capitulino                               action_str,
16972582bfedSLuiz Capitulino                               is_read ? "read" : "write");
16982582bfedSLuiz Capitulino     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
16992582bfedSLuiz Capitulino 
17002582bfedSLuiz Capitulino     qobject_decref(data);
17012582bfedSLuiz Capitulino }
17022582bfedSLuiz Capitulino 
1703d15e5465SLuiz Capitulino static void bdrv_print_dict(QObject *obj, void *opaque)
1704b338082bSbellard {
1705d15e5465SLuiz Capitulino     QDict *bs_dict;
1706d15e5465SLuiz Capitulino     Monitor *mon = opaque;
1707b338082bSbellard 
1708d15e5465SLuiz Capitulino     bs_dict = qobject_to_qdict(obj);
1709d15e5465SLuiz Capitulino 
1710d8aeeb31SMarkus Armbruster     monitor_printf(mon, "%s: removable=%d",
1711d15e5465SLuiz Capitulino                         qdict_get_str(bs_dict, "device"),
1712d15e5465SLuiz Capitulino                         qdict_get_bool(bs_dict, "removable"));
1713d15e5465SLuiz Capitulino 
1714d15e5465SLuiz Capitulino     if (qdict_get_bool(bs_dict, "removable")) {
1715d15e5465SLuiz Capitulino         monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1716b338082bSbellard     }
1717d15e5465SLuiz Capitulino 
1718d15e5465SLuiz Capitulino     if (qdict_haskey(bs_dict, "inserted")) {
1719d15e5465SLuiz Capitulino         QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1720d15e5465SLuiz Capitulino 
1721376253ecSaliguori         monitor_printf(mon, " file=");
1722d15e5465SLuiz Capitulino         monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1723d15e5465SLuiz Capitulino         if (qdict_haskey(qdict, "backing_file")) {
1724376253ecSaliguori             monitor_printf(mon, " backing_file=");
1725d15e5465SLuiz Capitulino             monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1726fef30743Sths         }
1727d15e5465SLuiz Capitulino         monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1728d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "ro"),
1729d15e5465SLuiz Capitulino                             qdict_get_str(qdict, "drv"),
1730d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "encrypted"));
1731b338082bSbellard     } else {
1732376253ecSaliguori         monitor_printf(mon, " [not inserted]");
1733b338082bSbellard     }
1734d15e5465SLuiz Capitulino 
1735376253ecSaliguori     monitor_printf(mon, "\n");
1736b338082bSbellard }
1737d15e5465SLuiz Capitulino 
1738d15e5465SLuiz Capitulino void bdrv_info_print(Monitor *mon, const QObject *data)
1739d15e5465SLuiz Capitulino {
1740d15e5465SLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1741d15e5465SLuiz Capitulino }
1742d15e5465SLuiz Capitulino 
1743d15e5465SLuiz Capitulino void bdrv_info(Monitor *mon, QObject **ret_data)
1744d15e5465SLuiz Capitulino {
1745d15e5465SLuiz Capitulino     QList *bs_list;
1746d15e5465SLuiz Capitulino     BlockDriverState *bs;
1747d15e5465SLuiz Capitulino 
1748d15e5465SLuiz Capitulino     bs_list = qlist_new();
1749d15e5465SLuiz Capitulino 
17501b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1751d15e5465SLuiz Capitulino         QObject *bs_obj;
1752d15e5465SLuiz Capitulino 
1753d8aeeb31SMarkus Armbruster         bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1754d15e5465SLuiz Capitulino                                     "'removable': %i, 'locked': %i }",
1755d8aeeb31SMarkus Armbruster                                     bs->device_name, bs->removable,
1756d15e5465SLuiz Capitulino                                     bs->locked);
1757d15e5465SLuiz Capitulino 
1758d15e5465SLuiz Capitulino         if (bs->drv) {
1759d15e5465SLuiz Capitulino             QObject *obj;
1760d15e5465SLuiz Capitulino             QDict *bs_dict = qobject_to_qdict(bs_obj);
1761d15e5465SLuiz Capitulino 
1762d15e5465SLuiz Capitulino             obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1763d15e5465SLuiz Capitulino                                      "'encrypted': %i }",
1764d15e5465SLuiz Capitulino                                      bs->filename, bs->read_only,
1765d15e5465SLuiz Capitulino                                      bs->drv->format_name,
1766d15e5465SLuiz Capitulino                                      bdrv_is_encrypted(bs));
1767d15e5465SLuiz Capitulino             if (bs->backing_file[0] != '\0') {
1768d15e5465SLuiz Capitulino                 QDict *qdict = qobject_to_qdict(obj);
1769d15e5465SLuiz Capitulino                 qdict_put(qdict, "backing_file",
1770d15e5465SLuiz Capitulino                           qstring_from_str(bs->backing_file));
1771d15e5465SLuiz Capitulino             }
1772d15e5465SLuiz Capitulino 
1773d15e5465SLuiz Capitulino             qdict_put_obj(bs_dict, "inserted", obj);
1774d15e5465SLuiz Capitulino         }
1775d15e5465SLuiz Capitulino         qlist_append_obj(bs_list, bs_obj);
1776d15e5465SLuiz Capitulino     }
1777d15e5465SLuiz Capitulino 
1778d15e5465SLuiz Capitulino     *ret_data = QOBJECT(bs_list);
1779b338082bSbellard }
1780a36e69ddSths 
1781218a536aSLuiz Capitulino static void bdrv_stats_iter(QObject *data, void *opaque)
1782a36e69ddSths {
1783218a536aSLuiz Capitulino     QDict *qdict;
1784218a536aSLuiz Capitulino     Monitor *mon = opaque;
1785218a536aSLuiz Capitulino 
1786218a536aSLuiz Capitulino     qdict = qobject_to_qdict(data);
1787218a536aSLuiz Capitulino     monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1788218a536aSLuiz Capitulino 
1789218a536aSLuiz Capitulino     qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1790218a536aSLuiz Capitulino     monitor_printf(mon, " rd_bytes=%" PRId64
1791218a536aSLuiz Capitulino                         " wr_bytes=%" PRId64
1792218a536aSLuiz Capitulino                         " rd_operations=%" PRId64
1793218a536aSLuiz Capitulino                         " wr_operations=%" PRId64
1794218a536aSLuiz Capitulino                         "\n",
1795218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_bytes"),
1796218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_bytes"),
1797218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_operations"),
1798218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_operations"));
1799218a536aSLuiz Capitulino }
1800218a536aSLuiz Capitulino 
1801218a536aSLuiz Capitulino void bdrv_stats_print(Monitor *mon, const QObject *data)
1802218a536aSLuiz Capitulino {
1803218a536aSLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1804218a536aSLuiz Capitulino }
1805218a536aSLuiz Capitulino 
1806294cc35fSKevin Wolf static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1807294cc35fSKevin Wolf {
1808294cc35fSKevin Wolf     QObject *res;
1809294cc35fSKevin Wolf     QDict *dict;
1810294cc35fSKevin Wolf 
1811294cc35fSKevin Wolf     res = qobject_from_jsonf("{ 'stats': {"
1812294cc35fSKevin Wolf                              "'rd_bytes': %" PRId64 ","
1813294cc35fSKevin Wolf                              "'wr_bytes': %" PRId64 ","
1814294cc35fSKevin Wolf                              "'rd_operations': %" PRId64 ","
1815294cc35fSKevin Wolf                              "'wr_operations': %" PRId64 ","
1816294cc35fSKevin Wolf                              "'wr_highest_offset': %" PRId64
1817294cc35fSKevin Wolf                              "} }",
1818294cc35fSKevin Wolf                              bs->rd_bytes, bs->wr_bytes,
1819294cc35fSKevin Wolf                              bs->rd_ops, bs->wr_ops,
18205ffbbc67SBlue Swirl                              bs->wr_highest_sector *
18215ffbbc67SBlue Swirl                              (uint64_t)BDRV_SECTOR_SIZE);
1822294cc35fSKevin Wolf     dict  = qobject_to_qdict(res);
1823294cc35fSKevin Wolf 
1824294cc35fSKevin Wolf     if (*bs->device_name) {
1825294cc35fSKevin Wolf         qdict_put(dict, "device", qstring_from_str(bs->device_name));
1826294cc35fSKevin Wolf     }
1827294cc35fSKevin Wolf 
1828294cc35fSKevin Wolf     if (bs->file) {
1829294cc35fSKevin Wolf         QObject *parent = bdrv_info_stats_bs(bs->file);
1830294cc35fSKevin Wolf         qdict_put_obj(dict, "parent", parent);
1831294cc35fSKevin Wolf     }
1832294cc35fSKevin Wolf 
1833294cc35fSKevin Wolf     return res;
1834294cc35fSKevin Wolf }
1835294cc35fSKevin Wolf 
1836218a536aSLuiz Capitulino void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1837218a536aSLuiz Capitulino {
1838218a536aSLuiz Capitulino     QObject *obj;
1839218a536aSLuiz Capitulino     QList *devices;
1840a36e69ddSths     BlockDriverState *bs;
1841a36e69ddSths 
1842218a536aSLuiz Capitulino     devices = qlist_new();
1843218a536aSLuiz Capitulino 
18441b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1845294cc35fSKevin Wolf         obj = bdrv_info_stats_bs(bs);
1846218a536aSLuiz Capitulino         qlist_append_obj(devices, obj);
1847a36e69ddSths     }
1848218a536aSLuiz Capitulino 
1849218a536aSLuiz Capitulino     *ret_data = QOBJECT(devices);
1850a36e69ddSths }
1851ea2384d3Sbellard 
1852045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1853045df330Saliguori {
1854045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
1855045df330Saliguori         return bs->backing_file;
1856045df330Saliguori     else if (bs->encrypted)
1857045df330Saliguori         return bs->filename;
1858045df330Saliguori     else
1859045df330Saliguori         return NULL;
1860045df330Saliguori }
1861045df330Saliguori 
186283f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
186383f64091Sbellard                                char *filename, int filename_size)
186483f64091Sbellard {
1865b783e409SKevin Wolf     if (!bs->backing_file) {
186683f64091Sbellard         pstrcpy(filename, filename_size, "");
186783f64091Sbellard     } else {
186883f64091Sbellard         pstrcpy(filename, filename_size, bs->backing_file);
186983f64091Sbellard     }
187083f64091Sbellard }
187183f64091Sbellard 
1872faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1873faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
1874faea38e7Sbellard {
1875faea38e7Sbellard     BlockDriver *drv = bs->drv;
1876faea38e7Sbellard     if (!drv)
187719cb3738Sbellard         return -ENOMEDIUM;
1878faea38e7Sbellard     if (!drv->bdrv_write_compressed)
1879faea38e7Sbellard         return -ENOTSUP;
1880fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
1881fbb7b4e0SKevin Wolf         return -EIO;
18827cd1e32aSlirans@il.ibm.com 
1883c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
18847cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
18857cd1e32aSlirans@il.ibm.com     }
18867cd1e32aSlirans@il.ibm.com 
1887faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1888faea38e7Sbellard }
1889faea38e7Sbellard 
1890faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1891faea38e7Sbellard {
1892faea38e7Sbellard     BlockDriver *drv = bs->drv;
1893faea38e7Sbellard     if (!drv)
189419cb3738Sbellard         return -ENOMEDIUM;
1895faea38e7Sbellard     if (!drv->bdrv_get_info)
1896faea38e7Sbellard         return -ENOTSUP;
1897faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
1898faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
1899faea38e7Sbellard }
1900faea38e7Sbellard 
190145566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
190245566e9cSChristoph Hellwig                       int64_t pos, int size)
1903178e08a5Saliguori {
1904178e08a5Saliguori     BlockDriver *drv = bs->drv;
1905178e08a5Saliguori     if (!drv)
1906178e08a5Saliguori         return -ENOMEDIUM;
19077cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
190845566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
19097cdb1f6dSMORITA Kazutaka     if (bs->file)
19107cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
19117cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1912178e08a5Saliguori }
1913178e08a5Saliguori 
191445566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
191545566e9cSChristoph Hellwig                       int64_t pos, int size)
1916178e08a5Saliguori {
1917178e08a5Saliguori     BlockDriver *drv = bs->drv;
1918178e08a5Saliguori     if (!drv)
1919178e08a5Saliguori         return -ENOMEDIUM;
19207cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
192145566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
19227cdb1f6dSMORITA Kazutaka     if (bs->file)
19237cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
19247cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1925178e08a5Saliguori }
1926178e08a5Saliguori 
19278b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
19288b9b0cc2SKevin Wolf {
19298b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
19308b9b0cc2SKevin Wolf 
19318b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
19328b9b0cc2SKevin Wolf         return;
19338b9b0cc2SKevin Wolf     }
19348b9b0cc2SKevin Wolf 
19358b9b0cc2SKevin Wolf     return drv->bdrv_debug_event(bs, event);
19368b9b0cc2SKevin Wolf 
19378b9b0cc2SKevin Wolf }
19388b9b0cc2SKevin Wolf 
1939faea38e7Sbellard /**************************************************************/
1940faea38e7Sbellard /* handling of snapshots */
1941faea38e7Sbellard 
1942feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
1943feeee5acSMiguel Di Ciurcio Filho {
1944feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
1945feeee5acSMiguel Di Ciurcio Filho     if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1946feeee5acSMiguel Di Ciurcio Filho         return 0;
1947feeee5acSMiguel Di Ciurcio Filho     }
1948feeee5acSMiguel Di Ciurcio Filho 
1949feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
1950feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
1951feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
1952feeee5acSMiguel Di Ciurcio Filho         }
1953feeee5acSMiguel Di Ciurcio Filho         return 0;
1954feeee5acSMiguel Di Ciurcio Filho     }
1955feeee5acSMiguel Di Ciurcio Filho 
1956feeee5acSMiguel Di Ciurcio Filho     return 1;
1957feeee5acSMiguel Di Ciurcio Filho }
1958feeee5acSMiguel Di Ciurcio Filho 
1959199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
1960199630b6SBlue Swirl {
1961199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
1962199630b6SBlue Swirl }
1963199630b6SBlue Swirl 
1964f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
1965f9092b10SMarkus Armbruster {
1966f9092b10SMarkus Armbruster     BlockDriverState *bs;
1967f9092b10SMarkus Armbruster 
19683ac906f7SMarkus Armbruster     if (bs_snapshots) {
1969f9092b10SMarkus Armbruster         return bs_snapshots;
19703ac906f7SMarkus Armbruster     }
1971f9092b10SMarkus Armbruster 
1972f9092b10SMarkus Armbruster     bs = NULL;
1973f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
1974f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
19753ac906f7SMarkus Armbruster             bs_snapshots = bs;
19763ac906f7SMarkus Armbruster             return bs;
1977f9092b10SMarkus Armbruster         }
1978f9092b10SMarkus Armbruster     }
1979f9092b10SMarkus Armbruster     return NULL;
1980f9092b10SMarkus Armbruster }
1981f9092b10SMarkus Armbruster 
1982faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
1983faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
1984faea38e7Sbellard {
1985faea38e7Sbellard     BlockDriver *drv = bs->drv;
1986faea38e7Sbellard     if (!drv)
198719cb3738Sbellard         return -ENOMEDIUM;
19887cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
1989faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
19907cdb1f6dSMORITA Kazutaka     if (bs->file)
19917cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
19927cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1993faea38e7Sbellard }
1994faea38e7Sbellard 
1995faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
1996faea38e7Sbellard                        const char *snapshot_id)
1997faea38e7Sbellard {
1998faea38e7Sbellard     BlockDriver *drv = bs->drv;
19997cdb1f6dSMORITA Kazutaka     int ret, open_ret;
20007cdb1f6dSMORITA Kazutaka 
2001faea38e7Sbellard     if (!drv)
200219cb3738Sbellard         return -ENOMEDIUM;
20037cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
2004faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
20057cdb1f6dSMORITA Kazutaka 
20067cdb1f6dSMORITA Kazutaka     if (bs->file) {
20077cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
20087cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
20097cdb1f6dSMORITA Kazutaka         open_ret = drv->bdrv_open(bs, bs->open_flags);
20107cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
20117cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
20127cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
20137cdb1f6dSMORITA Kazutaka             return open_ret;
20147cdb1f6dSMORITA Kazutaka         }
20157cdb1f6dSMORITA Kazutaka         return ret;
20167cdb1f6dSMORITA Kazutaka     }
20177cdb1f6dSMORITA Kazutaka 
20187cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2019faea38e7Sbellard }
2020faea38e7Sbellard 
2021faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2022faea38e7Sbellard {
2023faea38e7Sbellard     BlockDriver *drv = bs->drv;
2024faea38e7Sbellard     if (!drv)
202519cb3738Sbellard         return -ENOMEDIUM;
20267cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
2027faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
20287cdb1f6dSMORITA Kazutaka     if (bs->file)
20297cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
20307cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2031faea38e7Sbellard }
2032faea38e7Sbellard 
2033faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
2034faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
2035faea38e7Sbellard {
2036faea38e7Sbellard     BlockDriver *drv = bs->drv;
2037faea38e7Sbellard     if (!drv)
203819cb3738Sbellard         return -ENOMEDIUM;
20397cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
2040faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
20417cdb1f6dSMORITA Kazutaka     if (bs->file)
20427cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
20437cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2044faea38e7Sbellard }
2045faea38e7Sbellard 
204651ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
204751ef6727Sedison         const char *snapshot_name)
204851ef6727Sedison {
204951ef6727Sedison     BlockDriver *drv = bs->drv;
205051ef6727Sedison     if (!drv) {
205151ef6727Sedison         return -ENOMEDIUM;
205251ef6727Sedison     }
205351ef6727Sedison     if (!bs->read_only) {
205451ef6727Sedison         return -EINVAL;
205551ef6727Sedison     }
205651ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
205751ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
205851ef6727Sedison     }
205951ef6727Sedison     return -ENOTSUP;
206051ef6727Sedison }
206151ef6727Sedison 
2062faea38e7Sbellard #define NB_SUFFIXES 4
2063faea38e7Sbellard 
2064faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2065faea38e7Sbellard {
2066faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
2067faea38e7Sbellard     int64_t base;
2068faea38e7Sbellard     int i;
2069faea38e7Sbellard 
2070faea38e7Sbellard     if (size <= 999) {
2071faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
2072faea38e7Sbellard     } else {
2073faea38e7Sbellard         base = 1024;
2074faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
2075faea38e7Sbellard             if (size < (10 * base)) {
2076faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
2077faea38e7Sbellard                          (double)size / base,
2078faea38e7Sbellard                          suffixes[i]);
2079faea38e7Sbellard                 break;
2080faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2081faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
2082faea38e7Sbellard                          ((size + (base >> 1)) / base),
2083faea38e7Sbellard                          suffixes[i]);
2084faea38e7Sbellard                 break;
2085faea38e7Sbellard             }
2086faea38e7Sbellard             base = base * 1024;
2087faea38e7Sbellard         }
2088faea38e7Sbellard     }
2089faea38e7Sbellard     return buf;
2090faea38e7Sbellard }
2091faea38e7Sbellard 
2092faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2093faea38e7Sbellard {
2094faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
20953b9f94e1Sbellard #ifdef _WIN32
20963b9f94e1Sbellard     struct tm *ptm;
20973b9f94e1Sbellard #else
2098faea38e7Sbellard     struct tm tm;
20993b9f94e1Sbellard #endif
2100faea38e7Sbellard     time_t ti;
2101faea38e7Sbellard     int64_t secs;
2102faea38e7Sbellard 
2103faea38e7Sbellard     if (!sn) {
2104faea38e7Sbellard         snprintf(buf, buf_size,
2105faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2106faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2107faea38e7Sbellard     } else {
2108faea38e7Sbellard         ti = sn->date_sec;
21093b9f94e1Sbellard #ifdef _WIN32
21103b9f94e1Sbellard         ptm = localtime(&ti);
21113b9f94e1Sbellard         strftime(date_buf, sizeof(date_buf),
21123b9f94e1Sbellard                  "%Y-%m-%d %H:%M:%S", ptm);
21133b9f94e1Sbellard #else
2114faea38e7Sbellard         localtime_r(&ti, &tm);
2115faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
2116faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
21173b9f94e1Sbellard #endif
2118faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
2119faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
2120faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
2121faea38e7Sbellard                  (int)(secs / 3600),
2122faea38e7Sbellard                  (int)((secs / 60) % 60),
2123faea38e7Sbellard                  (int)(secs % 60),
2124faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
2125faea38e7Sbellard         snprintf(buf, buf_size,
2126faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2127faea38e7Sbellard                  sn->id_str, sn->name,
2128faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2129faea38e7Sbellard                  date_buf,
2130faea38e7Sbellard                  clock_buf);
2131faea38e7Sbellard     }
2132faea38e7Sbellard     return buf;
2133faea38e7Sbellard }
2134faea38e7Sbellard 
213583f64091Sbellard 
2136ea2384d3Sbellard /**************************************************************/
213783f64091Sbellard /* async I/Os */
2138ea2384d3Sbellard 
21393b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2140f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
214183f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
2142ea2384d3Sbellard {
214383f64091Sbellard     BlockDriver *drv = bs->drv;
2144a36e69ddSths     BlockDriverAIOCB *ret;
2145ea2384d3Sbellard 
2146bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2147bbf0a440SStefan Hajnoczi 
214819cb3738Sbellard     if (!drv)
2149ce1a14dcSpbrook         return NULL;
215071d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
215171d0770cSaliguori         return NULL;
215283f64091Sbellard 
2153f141eafeSaliguori     ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2154f141eafeSaliguori                               cb, opaque);
2155a36e69ddSths 
2156a36e69ddSths     if (ret) {
2157a36e69ddSths 	/* Update stats even though technically transfer has not happened. */
21586ea44308SJan Kiszka 	bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2159a36e69ddSths 	bs->rd_ops ++;
2160a36e69ddSths     }
2161a36e69ddSths 
2162a36e69ddSths     return ret;
216383f64091Sbellard }
216483f64091Sbellard 
21654dcafbb1SMarcelo Tosatti typedef struct BlockCompleteData {
21664dcafbb1SMarcelo Tosatti     BlockDriverCompletionFunc *cb;
21674dcafbb1SMarcelo Tosatti     void *opaque;
21684dcafbb1SMarcelo Tosatti     BlockDriverState *bs;
21694dcafbb1SMarcelo Tosatti     int64_t sector_num;
21704dcafbb1SMarcelo Tosatti     int nb_sectors;
21714dcafbb1SMarcelo Tosatti } BlockCompleteData;
21724dcafbb1SMarcelo Tosatti 
21734dcafbb1SMarcelo Tosatti static void block_complete_cb(void *opaque, int ret)
21744dcafbb1SMarcelo Tosatti {
21754dcafbb1SMarcelo Tosatti     BlockCompleteData *b = opaque;
21764dcafbb1SMarcelo Tosatti 
21774dcafbb1SMarcelo Tosatti     if (b->bs->dirty_bitmap) {
21784dcafbb1SMarcelo Tosatti         set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
21794dcafbb1SMarcelo Tosatti     }
21804dcafbb1SMarcelo Tosatti     b->cb(b->opaque, ret);
21814dcafbb1SMarcelo Tosatti     qemu_free(b);
21824dcafbb1SMarcelo Tosatti }
21834dcafbb1SMarcelo Tosatti 
21844dcafbb1SMarcelo Tosatti static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
21854dcafbb1SMarcelo Tosatti                                              int64_t sector_num,
21864dcafbb1SMarcelo Tosatti                                              int nb_sectors,
21874dcafbb1SMarcelo Tosatti                                              BlockDriverCompletionFunc *cb,
21884dcafbb1SMarcelo Tosatti                                              void *opaque)
21894dcafbb1SMarcelo Tosatti {
21904dcafbb1SMarcelo Tosatti     BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
21914dcafbb1SMarcelo Tosatti 
21924dcafbb1SMarcelo Tosatti     blkdata->bs = bs;
21934dcafbb1SMarcelo Tosatti     blkdata->cb = cb;
21944dcafbb1SMarcelo Tosatti     blkdata->opaque = opaque;
21954dcafbb1SMarcelo Tosatti     blkdata->sector_num = sector_num;
21964dcafbb1SMarcelo Tosatti     blkdata->nb_sectors = nb_sectors;
21974dcafbb1SMarcelo Tosatti 
21984dcafbb1SMarcelo Tosatti     return blkdata;
21994dcafbb1SMarcelo Tosatti }
22004dcafbb1SMarcelo Tosatti 
2201f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2202f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
220383f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
22047674e7bfSbellard {
220583f64091Sbellard     BlockDriver *drv = bs->drv;
2206a36e69ddSths     BlockDriverAIOCB *ret;
22074dcafbb1SMarcelo Tosatti     BlockCompleteData *blk_cb_data;
220883f64091Sbellard 
2209bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2210bbf0a440SStefan Hajnoczi 
221119cb3738Sbellard     if (!drv)
2212ce1a14dcSpbrook         return NULL;
221383f64091Sbellard     if (bs->read_only)
2214ce1a14dcSpbrook         return NULL;
221571d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
221671d0770cSaliguori         return NULL;
221783f64091Sbellard 
2218c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
22194dcafbb1SMarcelo Tosatti         blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
22204dcafbb1SMarcelo Tosatti                                          opaque);
22214dcafbb1SMarcelo Tosatti         cb = &block_complete_cb;
22224dcafbb1SMarcelo Tosatti         opaque = blk_cb_data;
22237cd1e32aSlirans@il.ibm.com     }
22247cd1e32aSlirans@il.ibm.com 
2225f141eafeSaliguori     ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2226f141eafeSaliguori                                cb, opaque);
2227a36e69ddSths 
2228a36e69ddSths     if (ret) {
2229a36e69ddSths         /* Update stats even though technically transfer has not happened. */
22306ea44308SJan Kiszka         bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2231a36e69ddSths         bs->wr_ops ++;
2232294cc35fSKevin Wolf         if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2233294cc35fSKevin Wolf             bs->wr_highest_sector = sector_num + nb_sectors - 1;
2234294cc35fSKevin Wolf         }
2235a36e69ddSths     }
2236a36e69ddSths 
2237a36e69ddSths     return ret;
223883f64091Sbellard }
223983f64091Sbellard 
224040b4f539SKevin Wolf 
224140b4f539SKevin Wolf typedef struct MultiwriteCB {
224240b4f539SKevin Wolf     int error;
224340b4f539SKevin Wolf     int num_requests;
224440b4f539SKevin Wolf     int num_callbacks;
224540b4f539SKevin Wolf     struct {
224640b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
224740b4f539SKevin Wolf         void *opaque;
224840b4f539SKevin Wolf         QEMUIOVector *free_qiov;
224940b4f539SKevin Wolf         void *free_buf;
225040b4f539SKevin Wolf     } callbacks[];
225140b4f539SKevin Wolf } MultiwriteCB;
225240b4f539SKevin Wolf 
225340b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
225440b4f539SKevin Wolf {
225540b4f539SKevin Wolf     int i;
225640b4f539SKevin Wolf 
225740b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
225840b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
22591e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
22601e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
22611e1ea48dSStefan Hajnoczi         }
226240b4f539SKevin Wolf         qemu_free(mcb->callbacks[i].free_qiov);
2263f8a83245SHerve Poussineau         qemu_vfree(mcb->callbacks[i].free_buf);
226440b4f539SKevin Wolf     }
226540b4f539SKevin Wolf }
226640b4f539SKevin Wolf 
226740b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
226840b4f539SKevin Wolf {
226940b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
227040b4f539SKevin Wolf 
22716d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
22726d519a5fSStefan Hajnoczi 
2273cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
227440b4f539SKevin Wolf         mcb->error = ret;
227540b4f539SKevin Wolf     }
227640b4f539SKevin Wolf 
227740b4f539SKevin Wolf     mcb->num_requests--;
227840b4f539SKevin Wolf     if (mcb->num_requests == 0) {
227940b4f539SKevin Wolf         multiwrite_user_cb(mcb);
228040b4f539SKevin Wolf         qemu_free(mcb);
228140b4f539SKevin Wolf     }
228240b4f539SKevin Wolf }
228340b4f539SKevin Wolf 
228440b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
228540b4f539SKevin Wolf {
228677be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
228777be4366SChristoph Hellwig 
228877be4366SChristoph Hellwig     /*
228977be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
229077be4366SChristoph Hellwig      * here as that could overflow the return value.
229177be4366SChristoph Hellwig      */
229277be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
229377be4366SChristoph Hellwig         return 1;
229477be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
229577be4366SChristoph Hellwig         return -1;
229677be4366SChristoph Hellwig     } else {
229777be4366SChristoph Hellwig         return 0;
229877be4366SChristoph Hellwig     }
229940b4f539SKevin Wolf }
230040b4f539SKevin Wolf 
230140b4f539SKevin Wolf /*
230240b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
230340b4f539SKevin Wolf  * requests that remain after merging.
230440b4f539SKevin Wolf  */
230540b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
230640b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
230740b4f539SKevin Wolf {
230840b4f539SKevin Wolf     int i, outidx;
230940b4f539SKevin Wolf 
231040b4f539SKevin Wolf     // Sort requests by start sector
231140b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
231240b4f539SKevin Wolf 
231340b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
231440b4f539SKevin Wolf     // filling up gaps with zero sectors.
231540b4f539SKevin Wolf     outidx = 0;
231640b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
231740b4f539SKevin Wolf         int merge = 0;
231840b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
231940b4f539SKevin Wolf 
232040b4f539SKevin Wolf         // This handles the cases that are valid for all block drivers, namely
232140b4f539SKevin Wolf         // exactly sequential writes and overlapping writes.
232240b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
232340b4f539SKevin Wolf             merge = 1;
232440b4f539SKevin Wolf         }
232540b4f539SKevin Wolf 
232640b4f539SKevin Wolf         // The block driver may decide that it makes sense to combine requests
232740b4f539SKevin Wolf         // even if there is a gap of some sectors between them. In this case,
232840b4f539SKevin Wolf         // the gap is filled with zeros (therefore only applicable for yet
232940b4f539SKevin Wolf         // unused space in format like qcow2).
233040b4f539SKevin Wolf         if (!merge && bs->drv->bdrv_merge_requests) {
233140b4f539SKevin Wolf             merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
233240b4f539SKevin Wolf         }
233340b4f539SKevin Wolf 
2334e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2335e2a305fbSChristoph Hellwig             merge = 0;
2336e2a305fbSChristoph Hellwig         }
2337e2a305fbSChristoph Hellwig 
233840b4f539SKevin Wolf         if (merge) {
233940b4f539SKevin Wolf             size_t size;
234040b4f539SKevin Wolf             QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
234140b4f539SKevin Wolf             qemu_iovec_init(qiov,
234240b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
234340b4f539SKevin Wolf 
234440b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
234540b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
234640b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
234740b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
234840b4f539SKevin Wolf 
234940b4f539SKevin Wolf             // We might need to add some zeros between the two requests
235040b4f539SKevin Wolf             if (reqs[i].sector > oldreq_last) {
235140b4f539SKevin Wolf                 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
235240b4f539SKevin Wolf                 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
235340b4f539SKevin Wolf                 memset(buf, 0, zero_bytes);
235440b4f539SKevin Wolf                 qemu_iovec_add(qiov, buf, zero_bytes);
235540b4f539SKevin Wolf                 mcb->callbacks[i].free_buf = buf;
235640b4f539SKevin Wolf             }
235740b4f539SKevin Wolf 
235840b4f539SKevin Wolf             // Add the second request
235940b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
236040b4f539SKevin Wolf 
2361cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
236240b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
236340b4f539SKevin Wolf 
236440b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
236540b4f539SKevin Wolf         } else {
236640b4f539SKevin Wolf             outidx++;
236740b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
236840b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
236940b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
237040b4f539SKevin Wolf         }
237140b4f539SKevin Wolf     }
237240b4f539SKevin Wolf 
237340b4f539SKevin Wolf     return outidx + 1;
237440b4f539SKevin Wolf }
237540b4f539SKevin Wolf 
237640b4f539SKevin Wolf /*
237740b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
237840b4f539SKevin Wolf  *
237940b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
238040b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
238140b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
238240b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
238340b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
238440b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
238540b4f539SKevin Wolf  *
238640b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
238740b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
238840b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
238940b4f539SKevin Wolf  */
239040b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
239140b4f539SKevin Wolf {
239240b4f539SKevin Wolf     BlockDriverAIOCB *acb;
239340b4f539SKevin Wolf     MultiwriteCB *mcb;
239440b4f539SKevin Wolf     int i;
239540b4f539SKevin Wolf 
2396301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
2397301db7c2SRyan Harper     if (bs->drv == NULL) {
2398301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
2399301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
2400301db7c2SRyan Harper         }
2401301db7c2SRyan Harper         return -1;
2402301db7c2SRyan Harper     }
2403301db7c2SRyan Harper 
240440b4f539SKevin Wolf     if (num_reqs == 0) {
240540b4f539SKevin Wolf         return 0;
240640b4f539SKevin Wolf     }
240740b4f539SKevin Wolf 
240840b4f539SKevin Wolf     // Create MultiwriteCB structure
240940b4f539SKevin Wolf     mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
241040b4f539SKevin Wolf     mcb->num_requests = 0;
241140b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
241240b4f539SKevin Wolf 
241340b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
241440b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
241540b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
241640b4f539SKevin Wolf     }
241740b4f539SKevin Wolf 
241840b4f539SKevin Wolf     // Check for mergable requests
241940b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
242040b4f539SKevin Wolf 
24216d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
24226d519a5fSStefan Hajnoczi 
2423453f9a16SKevin Wolf     /*
2424453f9a16SKevin Wolf      * Run the aio requests. As soon as one request can't be submitted
2425453f9a16SKevin Wolf      * successfully, fail all requests that are not yet submitted (we must
2426453f9a16SKevin Wolf      * return failure for all requests anyway)
2427453f9a16SKevin Wolf      *
2428453f9a16SKevin Wolf      * num_requests cannot be set to the right value immediately: If
2429453f9a16SKevin Wolf      * bdrv_aio_writev fails for some request, num_requests would be too high
2430453f9a16SKevin Wolf      * and therefore multiwrite_cb() would never recognize the multiwrite
2431453f9a16SKevin Wolf      * request as completed. We also cannot use the loop variable i to set it
2432453f9a16SKevin Wolf      * when the first request fails because the callback may already have been
2433453f9a16SKevin Wolf      * called for previously submitted requests. Thus, num_requests must be
2434453f9a16SKevin Wolf      * incremented for each request that is submitted.
2435453f9a16SKevin Wolf      *
2436453f9a16SKevin Wolf      * The problem that callbacks may be called early also means that we need
2437453f9a16SKevin Wolf      * to take care that num_requests doesn't become 0 before all requests are
2438453f9a16SKevin Wolf      * submitted - multiwrite_cb() would consider the multiwrite request
2439453f9a16SKevin Wolf      * completed. A dummy request that is "completed" by a manual call to
2440453f9a16SKevin Wolf      * multiwrite_cb() takes care of this.
2441453f9a16SKevin Wolf      */
2442453f9a16SKevin Wolf     mcb->num_requests = 1;
2443453f9a16SKevin Wolf 
24446d519a5fSStefan Hajnoczi     // Run the aio requests
244540b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
2446453f9a16SKevin Wolf         mcb->num_requests++;
244740b4f539SKevin Wolf         acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
244840b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
244940b4f539SKevin Wolf 
245040b4f539SKevin Wolf         if (acb == NULL) {
245140b4f539SKevin Wolf             // We can only fail the whole thing if no request has been
245240b4f539SKevin Wolf             // submitted yet. Otherwise we'll wait for the submitted AIOs to
245340b4f539SKevin Wolf             // complete and report the error in the callback.
2454453f9a16SKevin Wolf             if (i == 0) {
24556d519a5fSStefan Hajnoczi                 trace_bdrv_aio_multiwrite_earlyfail(mcb);
245640b4f539SKevin Wolf                 goto fail;
245740b4f539SKevin Wolf             } else {
24586d519a5fSStefan Hajnoczi                 trace_bdrv_aio_multiwrite_latefail(mcb, i);
24597eb58a6cSKevin Wolf                 multiwrite_cb(mcb, -EIO);
246040b4f539SKevin Wolf                 break;
246140b4f539SKevin Wolf             }
246240b4f539SKevin Wolf         }
246340b4f539SKevin Wolf     }
246440b4f539SKevin Wolf 
2465453f9a16SKevin Wolf     /* Complete the dummy request */
2466453f9a16SKevin Wolf     multiwrite_cb(mcb, 0);
2467453f9a16SKevin Wolf 
246840b4f539SKevin Wolf     return 0;
246940b4f539SKevin Wolf 
247040b4f539SKevin Wolf fail:
2471453f9a16SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
2472453f9a16SKevin Wolf         reqs[i].error = -EIO;
2473453f9a16SKevin Wolf     }
2474af474591SBruce Rogers     qemu_free(mcb);
247540b4f539SKevin Wolf     return -1;
247640b4f539SKevin Wolf }
247740b4f539SKevin Wolf 
2478b2e12bc6SChristoph Hellwig BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2479b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2480b2e12bc6SChristoph Hellwig {
2481b2e12bc6SChristoph Hellwig     BlockDriver *drv = bs->drv;
2482b2e12bc6SChristoph Hellwig 
2483a13aac04SStefan Hajnoczi     trace_bdrv_aio_flush(bs, opaque);
2484a13aac04SStefan Hajnoczi 
2485016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2486016f5cf6SAlexander Graf         return bdrv_aio_noop_em(bs, cb, opaque);
2487016f5cf6SAlexander Graf     }
2488016f5cf6SAlexander Graf 
2489b2e12bc6SChristoph Hellwig     if (!drv)
2490b2e12bc6SChristoph Hellwig         return NULL;
2491b2e12bc6SChristoph Hellwig     return drv->bdrv_aio_flush(bs, cb, opaque);
2492b2e12bc6SChristoph Hellwig }
2493b2e12bc6SChristoph Hellwig 
249483f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
249583f64091Sbellard {
24966bbff9a0Saliguori     acb->pool->cancel(acb);
249783f64091Sbellard }
249883f64091Sbellard 
249983f64091Sbellard 
250083f64091Sbellard /**************************************************************/
250183f64091Sbellard /* async block device emulation */
250283f64091Sbellard 
2503c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
2504c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
2505c16b5a2cSChristoph Hellwig     QEMUBH *bh;
2506c16b5a2cSChristoph Hellwig     int ret;
2507c16b5a2cSChristoph Hellwig     /* vector translation state */
2508c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
2509c16b5a2cSChristoph Hellwig     uint8_t *bounce;
2510c16b5a2cSChristoph Hellwig     int is_write;
2511c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
2512c16b5a2cSChristoph Hellwig 
2513c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2514c16b5a2cSChristoph Hellwig {
2515b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
2516b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
25176a7ad299SDor Laor     qemu_bh_delete(acb->bh);
251836afc451SAvi Kivity     acb->bh = NULL;
2519c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
2520c16b5a2cSChristoph Hellwig }
2521c16b5a2cSChristoph Hellwig 
2522c16b5a2cSChristoph Hellwig static AIOPool bdrv_em_aio_pool = {
2523c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2524c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
2525c16b5a2cSChristoph Hellwig };
2526c16b5a2cSChristoph Hellwig 
252783f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
2528beac80cdSbellard {
2529ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
2530f141eafeSaliguori 
2531f141eafeSaliguori     if (!acb->is_write)
2532f141eafeSaliguori         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2533ceb42de8Saliguori     qemu_vfree(acb->bounce);
2534ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
25356a7ad299SDor Laor     qemu_bh_delete(acb->bh);
253636afc451SAvi Kivity     acb->bh = NULL;
2537ce1a14dcSpbrook     qemu_aio_release(acb);
2538beac80cdSbellard }
2539beac80cdSbellard 
2540f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2541f141eafeSaliguori                                             int64_t sector_num,
2542f141eafeSaliguori                                             QEMUIOVector *qiov,
2543f141eafeSaliguori                                             int nb_sectors,
2544f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
2545f141eafeSaliguori                                             void *opaque,
2546f141eafeSaliguori                                             int is_write)
2547f141eafeSaliguori 
2548ea2384d3Sbellard {
2549ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
255083f64091Sbellard 
2551c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2552f141eafeSaliguori     acb->is_write = is_write;
2553f141eafeSaliguori     acb->qiov = qiov;
2554e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
2555f141eafeSaliguori 
2556ce1a14dcSpbrook     if (!acb->bh)
2557ce1a14dcSpbrook         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2558f141eafeSaliguori 
2559f141eafeSaliguori     if (is_write) {
2560f141eafeSaliguori         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2561f141eafeSaliguori         acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2562f141eafeSaliguori     } else {
2563f141eafeSaliguori         acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2564f141eafeSaliguori     }
2565f141eafeSaliguori 
2566ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
2567f141eafeSaliguori 
2568ce1a14dcSpbrook     return &acb->common;
25697a6cba61Spbrook }
25707a6cba61Spbrook 
2571f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2572f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2573ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
257483f64091Sbellard {
2575f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
257683f64091Sbellard }
257783f64091Sbellard 
2578f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2579f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2580f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
2581f141eafeSaliguori {
2582f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2583f141eafeSaliguori }
2584f141eafeSaliguori 
2585b2e12bc6SChristoph Hellwig static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2586b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2587b2e12bc6SChristoph Hellwig {
2588b2e12bc6SChristoph Hellwig     BlockDriverAIOCBSync *acb;
2589b2e12bc6SChristoph Hellwig 
2590b2e12bc6SChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2591b2e12bc6SChristoph Hellwig     acb->is_write = 1; /* don't bounce in the completion hadler */
2592b2e12bc6SChristoph Hellwig     acb->qiov = NULL;
2593b2e12bc6SChristoph Hellwig     acb->bounce = NULL;
2594b2e12bc6SChristoph Hellwig     acb->ret = 0;
2595b2e12bc6SChristoph Hellwig 
2596b2e12bc6SChristoph Hellwig     if (!acb->bh)
2597b2e12bc6SChristoph Hellwig         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2598b2e12bc6SChristoph Hellwig 
2599b2e12bc6SChristoph Hellwig     bdrv_flush(bs);
2600b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
2601b2e12bc6SChristoph Hellwig     return &acb->common;
2602b2e12bc6SChristoph Hellwig }
2603b2e12bc6SChristoph Hellwig 
2604016f5cf6SAlexander Graf static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2605016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
2606016f5cf6SAlexander Graf {
2607016f5cf6SAlexander Graf     BlockDriverAIOCBSync *acb;
2608016f5cf6SAlexander Graf 
2609016f5cf6SAlexander Graf     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2610016f5cf6SAlexander Graf     acb->is_write = 1; /* don't bounce in the completion handler */
2611016f5cf6SAlexander Graf     acb->qiov = NULL;
2612016f5cf6SAlexander Graf     acb->bounce = NULL;
2613016f5cf6SAlexander Graf     acb->ret = 0;
2614016f5cf6SAlexander Graf 
2615016f5cf6SAlexander Graf     if (!acb->bh) {
2616016f5cf6SAlexander Graf         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2617016f5cf6SAlexander Graf     }
2618016f5cf6SAlexander Graf 
2619016f5cf6SAlexander Graf     qemu_bh_schedule(acb->bh);
2620016f5cf6SAlexander Graf     return &acb->common;
2621016f5cf6SAlexander Graf }
2622016f5cf6SAlexander Graf 
262383f64091Sbellard /**************************************************************/
262483f64091Sbellard /* sync block device emulation */
262583f64091Sbellard 
262683f64091Sbellard static void bdrv_rw_em_cb(void *opaque, int ret)
262783f64091Sbellard {
262883f64091Sbellard     *(int *)opaque = ret;
262983f64091Sbellard }
263083f64091Sbellard 
263183f64091Sbellard #define NOT_DONE 0x7fffffff
263283f64091Sbellard 
263383f64091Sbellard static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
263483f64091Sbellard                         uint8_t *buf, int nb_sectors)
263583f64091Sbellard {
2636ce1a14dcSpbrook     int async_ret;
2637ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2638f141eafeSaliguori     struct iovec iov;
2639f141eafeSaliguori     QEMUIOVector qiov;
264083f64091Sbellard 
264165d6b3d8SKevin Wolf     async_context_push();
264265d6b3d8SKevin Wolf 
264383f64091Sbellard     async_ret = NOT_DONE;
26443f4cb3d3Sblueswir1     iov.iov_base = (void *)buf;
2645eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2646f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2647f141eafeSaliguori     acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
264883f64091Sbellard         bdrv_rw_em_cb, &async_ret);
264965d6b3d8SKevin Wolf     if (acb == NULL) {
265065d6b3d8SKevin Wolf         async_ret = -1;
265165d6b3d8SKevin Wolf         goto fail;
265265d6b3d8SKevin Wolf     }
2653baf35cb9Saliguori 
265483f64091Sbellard     while (async_ret == NOT_DONE) {
265583f64091Sbellard         qemu_aio_wait();
265683f64091Sbellard     }
2657baf35cb9Saliguori 
265865d6b3d8SKevin Wolf 
265965d6b3d8SKevin Wolf fail:
266065d6b3d8SKevin Wolf     async_context_pop();
266183f64091Sbellard     return async_ret;
266283f64091Sbellard }
266383f64091Sbellard 
266483f64091Sbellard static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
266583f64091Sbellard                          const uint8_t *buf, int nb_sectors)
266683f64091Sbellard {
2667ce1a14dcSpbrook     int async_ret;
2668ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2669f141eafeSaliguori     struct iovec iov;
2670f141eafeSaliguori     QEMUIOVector qiov;
267183f64091Sbellard 
267265d6b3d8SKevin Wolf     async_context_push();
267365d6b3d8SKevin Wolf 
267483f64091Sbellard     async_ret = NOT_DONE;
2675f141eafeSaliguori     iov.iov_base = (void *)buf;
2676eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2677f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2678f141eafeSaliguori     acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
267983f64091Sbellard         bdrv_rw_em_cb, &async_ret);
268065d6b3d8SKevin Wolf     if (acb == NULL) {
268165d6b3d8SKevin Wolf         async_ret = -1;
268265d6b3d8SKevin Wolf         goto fail;
268365d6b3d8SKevin Wolf     }
268483f64091Sbellard     while (async_ret == NOT_DONE) {
268583f64091Sbellard         qemu_aio_wait();
268683f64091Sbellard     }
268765d6b3d8SKevin Wolf 
268865d6b3d8SKevin Wolf fail:
268965d6b3d8SKevin Wolf     async_context_pop();
269083f64091Sbellard     return async_ret;
269183f64091Sbellard }
2692ea2384d3Sbellard 
2693ea2384d3Sbellard void bdrv_init(void)
2694ea2384d3Sbellard {
26955efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
2696ea2384d3Sbellard }
2697ce1a14dcSpbrook 
2698eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
2699eb852011SMarkus Armbruster {
2700eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
2701eb852011SMarkus Armbruster     bdrv_init();
2702eb852011SMarkus Armbruster }
2703eb852011SMarkus Armbruster 
2704c16b5a2cSChristoph Hellwig void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
27056bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
27066bbff9a0Saliguori {
2707ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2708ce1a14dcSpbrook 
27096bbff9a0Saliguori     if (pool->free_aiocb) {
27106bbff9a0Saliguori         acb = pool->free_aiocb;
27116bbff9a0Saliguori         pool->free_aiocb = acb->next;
2712ce1a14dcSpbrook     } else {
27136bbff9a0Saliguori         acb = qemu_mallocz(pool->aiocb_size);
27146bbff9a0Saliguori         acb->pool = pool;
2715ce1a14dcSpbrook     }
2716ce1a14dcSpbrook     acb->bs = bs;
2717ce1a14dcSpbrook     acb->cb = cb;
2718ce1a14dcSpbrook     acb->opaque = opaque;
2719ce1a14dcSpbrook     return acb;
2720ce1a14dcSpbrook }
2721ce1a14dcSpbrook 
2722ce1a14dcSpbrook void qemu_aio_release(void *p)
2723ce1a14dcSpbrook {
27246bbff9a0Saliguori     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
27256bbff9a0Saliguori     AIOPool *pool = acb->pool;
27266bbff9a0Saliguori     acb->next = pool->free_aiocb;
27276bbff9a0Saliguori     pool->free_aiocb = acb;
2728ce1a14dcSpbrook }
272919cb3738Sbellard 
273019cb3738Sbellard /**************************************************************/
273119cb3738Sbellard /* removable device support */
273219cb3738Sbellard 
273319cb3738Sbellard /**
273419cb3738Sbellard  * Return TRUE if the media is present
273519cb3738Sbellard  */
273619cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
273719cb3738Sbellard {
273819cb3738Sbellard     BlockDriver *drv = bs->drv;
273919cb3738Sbellard     int ret;
274019cb3738Sbellard     if (!drv)
274119cb3738Sbellard         return 0;
274219cb3738Sbellard     if (!drv->bdrv_is_inserted)
27434be9762aSMarkus Armbruster         return !bs->tray_open;
274419cb3738Sbellard     ret = drv->bdrv_is_inserted(bs);
274519cb3738Sbellard     return ret;
274619cb3738Sbellard }
274719cb3738Sbellard 
274819cb3738Sbellard /**
274919cb3738Sbellard  * Return TRUE if the media changed since the last call to this
275019cb3738Sbellard  * function. It is currently only used for floppy disks
275119cb3738Sbellard  */
275219cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
275319cb3738Sbellard {
275419cb3738Sbellard     BlockDriver *drv = bs->drv;
275519cb3738Sbellard     int ret;
275619cb3738Sbellard 
275719cb3738Sbellard     if (!drv || !drv->bdrv_media_changed)
275819cb3738Sbellard         ret = -ENOTSUP;
275919cb3738Sbellard     else
276019cb3738Sbellard         ret = drv->bdrv_media_changed(bs);
276119cb3738Sbellard     if (ret == -ENOTSUP)
276219cb3738Sbellard         ret = bs->media_changed;
276319cb3738Sbellard     bs->media_changed = 0;
276419cb3738Sbellard     return ret;
276519cb3738Sbellard }
276619cb3738Sbellard 
276719cb3738Sbellard /**
276819cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
276919cb3738Sbellard  */
2770aea2a33cSMark McLoughlin int bdrv_eject(BlockDriverState *bs, int eject_flag)
277119cb3738Sbellard {
277219cb3738Sbellard     BlockDriver *drv = bs->drv;
277319cb3738Sbellard 
2774*49aa46bbSMarkus Armbruster     if (eject_flag && bs->locked) {
2775aea2a33cSMark McLoughlin         return -EBUSY;
2776aea2a33cSMark McLoughlin     }
2777aea2a33cSMark McLoughlin 
2778822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
2779822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
278019cb3738Sbellard     }
27814be9762aSMarkus Armbruster     bs->tray_open = eject_flag;
2782822e1cd1SMarkus Armbruster     return 0;
278319cb3738Sbellard }
278419cb3738Sbellard 
278519cb3738Sbellard int bdrv_is_locked(BlockDriverState *bs)
278619cb3738Sbellard {
278719cb3738Sbellard     return bs->locked;
278819cb3738Sbellard }
278919cb3738Sbellard 
279019cb3738Sbellard /**
279119cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
279219cb3738Sbellard  * to eject it manually).
279319cb3738Sbellard  */
279419cb3738Sbellard void bdrv_set_locked(BlockDriverState *bs, int locked)
279519cb3738Sbellard {
279619cb3738Sbellard     BlockDriver *drv = bs->drv;
279719cb3738Sbellard 
2798b8c6d095SStefan Hajnoczi     trace_bdrv_set_locked(bs, locked);
2799b8c6d095SStefan Hajnoczi 
280019cb3738Sbellard     bs->locked = locked;
280119cb3738Sbellard     if (drv && drv->bdrv_set_locked) {
280219cb3738Sbellard         drv->bdrv_set_locked(bs, locked);
280319cb3738Sbellard     }
280419cb3738Sbellard }
2805985a03b0Sths 
2806985a03b0Sths /* needed for generic scsi interface */
2807985a03b0Sths 
2808985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2809985a03b0Sths {
2810985a03b0Sths     BlockDriver *drv = bs->drv;
2811985a03b0Sths 
2812985a03b0Sths     if (drv && drv->bdrv_ioctl)
2813985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
2814985a03b0Sths     return -ENOTSUP;
2815985a03b0Sths }
28167d780669Saliguori 
2817221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2818221f715dSaliguori         unsigned long int req, void *buf,
28197d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
28207d780669Saliguori {
2821221f715dSaliguori     BlockDriver *drv = bs->drv;
28227d780669Saliguori 
2823221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
2824221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2825221f715dSaliguori     return NULL;
28267d780669Saliguori }
2827e268ca52Saliguori 
28287cd1e32aSlirans@il.ibm.com 
28297cd1e32aSlirans@il.ibm.com 
2830e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
2831e268ca52Saliguori {
2832e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2833e268ca52Saliguori }
28347cd1e32aSlirans@il.ibm.com 
28357cd1e32aSlirans@il.ibm.com void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
28367cd1e32aSlirans@il.ibm.com {
28377cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
2838a55eb92cSJan Kiszka 
2839aaa0eb75SLiran Schour     bs->dirty_count = 0;
28407cd1e32aSlirans@il.ibm.com     if (enable) {
2841c6d22830SJan Kiszka         if (!bs->dirty_bitmap) {
2842c6d22830SJan Kiszka             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2843c6d22830SJan Kiszka                     BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2844c6d22830SJan Kiszka             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
28457cd1e32aSlirans@il.ibm.com 
28467cd1e32aSlirans@il.ibm.com             bs->dirty_bitmap = qemu_mallocz(bitmap_size);
28477cd1e32aSlirans@il.ibm.com         }
28487cd1e32aSlirans@il.ibm.com     } else {
2849c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
28507cd1e32aSlirans@il.ibm.com             qemu_free(bs->dirty_bitmap);
2851c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
28527cd1e32aSlirans@il.ibm.com         }
28537cd1e32aSlirans@il.ibm.com     }
28547cd1e32aSlirans@il.ibm.com }
28557cd1e32aSlirans@il.ibm.com 
28567cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
28577cd1e32aSlirans@il.ibm.com {
28586ea44308SJan Kiszka     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
28597cd1e32aSlirans@il.ibm.com 
2860c6d22830SJan Kiszka     if (bs->dirty_bitmap &&
2861c6d22830SJan Kiszka         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
28626d59fec1SMarcelo Tosatti         return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
28636d59fec1SMarcelo Tosatti             (1UL << (chunk % (sizeof(unsigned long) * 8))));
28647cd1e32aSlirans@il.ibm.com     } else {
28657cd1e32aSlirans@il.ibm.com         return 0;
28667cd1e32aSlirans@il.ibm.com     }
28677cd1e32aSlirans@il.ibm.com }
28687cd1e32aSlirans@il.ibm.com 
28697cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
28707cd1e32aSlirans@il.ibm.com                       int nr_sectors)
28717cd1e32aSlirans@il.ibm.com {
28727cd1e32aSlirans@il.ibm.com     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
28737cd1e32aSlirans@il.ibm.com }
2874aaa0eb75SLiran Schour 
2875aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2876aaa0eb75SLiran Schour {
2877aaa0eb75SLiran Schour     return bs->dirty_count;
2878aaa0eb75SLiran Schour }
2879f88e1a42SJes Sorensen 
2880db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
2881db593f25SMarcelo Tosatti {
2882db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
2883db593f25SMarcelo Tosatti     bs->in_use = in_use;
2884db593f25SMarcelo Tosatti }
2885db593f25SMarcelo Tosatti 
2886db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
2887db593f25SMarcelo Tosatti {
2888db593f25SMarcelo Tosatti     return bs->in_use;
2889db593f25SMarcelo Tosatti }
2890db593f25SMarcelo Tosatti 
2891f88e1a42SJes Sorensen int bdrv_img_create(const char *filename, const char *fmt,
2892f88e1a42SJes Sorensen                     const char *base_filename, const char *base_fmt,
2893f88e1a42SJes Sorensen                     char *options, uint64_t img_size, int flags)
2894f88e1a42SJes Sorensen {
2895f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
2896d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
2897f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
2898f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
289996df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
2900f88e1a42SJes Sorensen     int ret = 0;
2901f88e1a42SJes Sorensen 
2902f88e1a42SJes Sorensen     /* Find driver and parse its options */
2903f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
2904f88e1a42SJes Sorensen     if (!drv) {
2905f88e1a42SJes Sorensen         error_report("Unknown file format '%s'", fmt);
29064f70f249SJes Sorensen         ret = -EINVAL;
2907f88e1a42SJes Sorensen         goto out;
2908f88e1a42SJes Sorensen     }
2909f88e1a42SJes Sorensen 
2910f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
2911f88e1a42SJes Sorensen     if (!proto_drv) {
2912f88e1a42SJes Sorensen         error_report("Unknown protocol '%s'", filename);
29134f70f249SJes Sorensen         ret = -EINVAL;
2914f88e1a42SJes Sorensen         goto out;
2915f88e1a42SJes Sorensen     }
2916f88e1a42SJes Sorensen 
2917f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
2918f88e1a42SJes Sorensen                                               drv->create_options);
2919f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
2920f88e1a42SJes Sorensen                                               proto_drv->create_options);
2921f88e1a42SJes Sorensen 
2922f88e1a42SJes Sorensen     /* Create parameter list with default values */
2923f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
2924f88e1a42SJes Sorensen 
2925f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
2926f88e1a42SJes Sorensen 
2927f88e1a42SJes Sorensen     /* Parse -o options */
2928f88e1a42SJes Sorensen     if (options) {
2929f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
2930f88e1a42SJes Sorensen         if (param == NULL) {
2931f88e1a42SJes Sorensen             error_report("Invalid options for file format '%s'.", fmt);
29324f70f249SJes Sorensen             ret = -EINVAL;
2933f88e1a42SJes Sorensen             goto out;
2934f88e1a42SJes Sorensen         }
2935f88e1a42SJes Sorensen     }
2936f88e1a42SJes Sorensen 
2937f88e1a42SJes Sorensen     if (base_filename) {
2938f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
2939f88e1a42SJes Sorensen                                  base_filename)) {
2940f88e1a42SJes Sorensen             error_report("Backing file not supported for file format '%s'",
2941f88e1a42SJes Sorensen                          fmt);
29424f70f249SJes Sorensen             ret = -EINVAL;
2943f88e1a42SJes Sorensen             goto out;
2944f88e1a42SJes Sorensen         }
2945f88e1a42SJes Sorensen     }
2946f88e1a42SJes Sorensen 
2947f88e1a42SJes Sorensen     if (base_fmt) {
2948f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
2949f88e1a42SJes Sorensen             error_report("Backing file format not supported for file "
2950f88e1a42SJes Sorensen                          "format '%s'", fmt);
29514f70f249SJes Sorensen             ret = -EINVAL;
2952f88e1a42SJes Sorensen             goto out;
2953f88e1a42SJes Sorensen         }
2954f88e1a42SJes Sorensen     }
2955f88e1a42SJes Sorensen 
2956792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
2957792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
2958792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
2959792da93aSJes Sorensen             error_report("Error: Trying to create an image with the "
2960792da93aSJes Sorensen                          "same filename as the backing file");
29614f70f249SJes Sorensen             ret = -EINVAL;
2962792da93aSJes Sorensen             goto out;
2963792da93aSJes Sorensen         }
2964792da93aSJes Sorensen     }
2965792da93aSJes Sorensen 
2966f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
2967f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
296896df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
296996df67d1SStefan Hajnoczi         if (!backing_drv) {
2970f88e1a42SJes Sorensen             error_report("Unknown backing file format '%s'",
2971f88e1a42SJes Sorensen                          backing_fmt->value.s);
29724f70f249SJes Sorensen             ret = -EINVAL;
2973f88e1a42SJes Sorensen             goto out;
2974f88e1a42SJes Sorensen         }
2975f88e1a42SJes Sorensen     }
2976f88e1a42SJes Sorensen 
2977f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
2978f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
2979d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
2980d220894eSKevin Wolf     if (size && size->value.n == -1) {
2981f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
2982f88e1a42SJes Sorensen             uint64_t size;
2983f88e1a42SJes Sorensen             char buf[32];
2984f88e1a42SJes Sorensen 
2985f88e1a42SJes Sorensen             bs = bdrv_new("");
2986f88e1a42SJes Sorensen 
298796df67d1SStefan Hajnoczi             ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
2988f88e1a42SJes Sorensen             if (ret < 0) {
298996df67d1SStefan Hajnoczi                 error_report("Could not open '%s'", backing_file->value.s);
2990f88e1a42SJes Sorensen                 goto out;
2991f88e1a42SJes Sorensen             }
2992f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
2993f88e1a42SJes Sorensen             size *= 512;
2994f88e1a42SJes Sorensen 
2995f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
2996f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
2997f88e1a42SJes Sorensen         } else {
2998f88e1a42SJes Sorensen             error_report("Image creation needs a size parameter");
29994f70f249SJes Sorensen             ret = -EINVAL;
3000f88e1a42SJes Sorensen             goto out;
3001f88e1a42SJes Sorensen         }
3002f88e1a42SJes Sorensen     }
3003f88e1a42SJes Sorensen 
3004f88e1a42SJes Sorensen     printf("Formatting '%s', fmt=%s ", filename, fmt);
3005f88e1a42SJes Sorensen     print_option_parameters(param);
3006f88e1a42SJes Sorensen     puts("");
3007f88e1a42SJes Sorensen 
3008f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
3009f88e1a42SJes Sorensen 
3010f88e1a42SJes Sorensen     if (ret < 0) {
3011f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
3012f88e1a42SJes Sorensen             error_report("Formatting or formatting option not supported for "
3013f88e1a42SJes Sorensen                          "file format '%s'", fmt);
3014f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
3015f88e1a42SJes Sorensen             error_report("The image size is too large for file format '%s'",
3016f88e1a42SJes Sorensen                          fmt);
3017f88e1a42SJes Sorensen         } else {
3018f88e1a42SJes Sorensen             error_report("%s: error while creating %s: %s", filename, fmt,
3019f88e1a42SJes Sorensen                          strerror(-ret));
3020f88e1a42SJes Sorensen         }
3021f88e1a42SJes Sorensen     }
3022f88e1a42SJes Sorensen 
3023f88e1a42SJes Sorensen out:
3024f88e1a42SJes Sorensen     free_option_parameters(create_options);
3025f88e1a42SJes Sorensen     free_option_parameters(param);
3026f88e1a42SJes Sorensen 
3027f88e1a42SJes Sorensen     if (bs) {
3028f88e1a42SJes Sorensen         bdrv_delete(bs);
3029f88e1a42SJes Sorensen     }
30304f70f249SJes Sorensen 
30314f70f249SJes Sorensen     return ret;
3032f88e1a42SJes Sorensen }
3033