xref: /openbmc/qemu/block.c (revision a13aac04e13b246edab6c0c08513504ecb71bbd4)
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 
44257915332SKevin Wolf     /*
44357915332SKevin Wolf      * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
44457915332SKevin Wolf      * write cache to the guest.  We do need the fdatasync to flush
44557915332SKevin Wolf      * out transactions for block allocations, and we maybe have a
44657915332SKevin Wolf      * volatile write cache in our backing device to deal with.
44757915332SKevin Wolf      */
44857915332SKevin Wolf     if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
44957915332SKevin Wolf         bs->enable_write_cache = 1;
45057915332SKevin Wolf 
45157915332SKevin Wolf     /*
45257915332SKevin Wolf      * Clear flags that are internal to the block layer before opening the
45357915332SKevin Wolf      * image.
45457915332SKevin Wolf      */
45557915332SKevin Wolf     open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
45657915332SKevin Wolf 
45757915332SKevin Wolf     /*
45857915332SKevin Wolf      * Snapshots should be writeable.
45957915332SKevin Wolf      */
46057915332SKevin Wolf     if (bs->is_temporary) {
46157915332SKevin Wolf         open_flags |= BDRV_O_RDWR;
46257915332SKevin Wolf     }
46357915332SKevin Wolf 
46466f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
46566f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
46666f82ceeSKevin Wolf         ret = drv->bdrv_file_open(bs, filename, open_flags);
46766f82ceeSKevin Wolf     } else {
46866f82ceeSKevin Wolf         ret = bdrv_file_open(&bs->file, filename, open_flags);
46966f82ceeSKevin Wolf         if (ret >= 0) {
47066f82ceeSKevin Wolf             ret = drv->bdrv_open(bs, open_flags);
47166f82ceeSKevin Wolf         }
47266f82ceeSKevin Wolf     }
47366f82ceeSKevin Wolf 
47457915332SKevin Wolf     if (ret < 0) {
47557915332SKevin Wolf         goto free_and_fail;
47657915332SKevin Wolf     }
47757915332SKevin Wolf 
47857915332SKevin Wolf     bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
47951762288SStefan Hajnoczi 
48051762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
48151762288SStefan Hajnoczi     if (ret < 0) {
48251762288SStefan Hajnoczi         goto free_and_fail;
48357915332SKevin Wolf     }
48451762288SStefan Hajnoczi 
48557915332SKevin Wolf #ifndef _WIN32
48657915332SKevin Wolf     if (bs->is_temporary) {
48757915332SKevin Wolf         unlink(filename);
48857915332SKevin Wolf     }
48957915332SKevin Wolf #endif
49057915332SKevin Wolf     return 0;
49157915332SKevin Wolf 
49257915332SKevin Wolf free_and_fail:
49366f82ceeSKevin Wolf     if (bs->file) {
49466f82ceeSKevin Wolf         bdrv_delete(bs->file);
49566f82ceeSKevin Wolf         bs->file = NULL;
49666f82ceeSKevin Wolf     }
49757915332SKevin Wolf     qemu_free(bs->opaque);
49857915332SKevin Wolf     bs->opaque = NULL;
49957915332SKevin Wolf     bs->drv = NULL;
50057915332SKevin Wolf     return ret;
50157915332SKevin Wolf }
50257915332SKevin Wolf 
50357915332SKevin Wolf /*
504b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
505b6ce07aaSKevin Wolf  */
50683f64091Sbellard int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
507b338082bSbellard {
50883f64091Sbellard     BlockDriverState *bs;
5096db95603SChristoph Hellwig     BlockDriver *drv;
51083f64091Sbellard     int ret;
5113b0d4f61Sbellard 
512b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
5136db95603SChristoph Hellwig     if (!drv) {
5146db95603SChristoph Hellwig         return -ENOENT;
5156db95603SChristoph Hellwig     }
5166db95603SChristoph Hellwig 
51783f64091Sbellard     bs = bdrv_new("");
518b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
51983f64091Sbellard     if (ret < 0) {
52083f64091Sbellard         bdrv_delete(bs);
52183f64091Sbellard         return ret;
5223b0d4f61Sbellard     }
52371d0770cSaliguori     bs->growable = 1;
52483f64091Sbellard     *pbs = bs;
52583f64091Sbellard     return 0;
5263b0d4f61Sbellard }
5273b0d4f61Sbellard 
528b6ce07aaSKevin Wolf /*
529b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
530b6ce07aaSKevin Wolf  */
531d6e9098eSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
532ea2384d3Sbellard               BlockDriver *drv)
533ea2384d3Sbellard {
534b6ce07aaSKevin Wolf     int ret;
53533e3963eSbellard 
53683f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
537ea2384d3Sbellard         BlockDriverState *bs1;
538ea2384d3Sbellard         int64_t total_size;
5397c96d46eSaliguori         int is_protocol = 0;
54091a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
54191a073a9SKevin Wolf         QEMUOptionParameter *options;
542b6ce07aaSKevin Wolf         char tmp_filename[PATH_MAX];
543b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
54433e3963eSbellard 
545ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
546ea2384d3Sbellard            instead of opening 'filename' directly */
547ea2384d3Sbellard 
548ea2384d3Sbellard         /* if there is a backing file, use it */
549ea2384d3Sbellard         bs1 = bdrv_new("");
550d6e9098eSKevin Wolf         ret = bdrv_open(bs1, filename, 0, drv);
55151d7c00cSaliguori         if (ret < 0) {
552ea2384d3Sbellard             bdrv_delete(bs1);
55351d7c00cSaliguori             return ret;
554ea2384d3Sbellard         }
5553e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
5567c96d46eSaliguori 
5577c96d46eSaliguori         if (bs1->drv && bs1->drv->protocol_name)
5587c96d46eSaliguori             is_protocol = 1;
5597c96d46eSaliguori 
560ea2384d3Sbellard         bdrv_delete(bs1);
561ea2384d3Sbellard 
562ea2384d3Sbellard         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
5637c96d46eSaliguori 
5647c96d46eSaliguori         /* Real path is meaningless for protocols */
5657c96d46eSaliguori         if (is_protocol)
5667c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
5677c96d46eSaliguori                      "%s", filename);
568114cdfa9SKirill A. Shutemov         else if (!realpath(filename, backing_filename))
569114cdfa9SKirill A. Shutemov             return -errno;
5707c96d46eSaliguori 
57191a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
57291a073a9SKevin Wolf         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
57391a073a9SKevin Wolf 
5743e82990bSJes Sorensen         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
57591a073a9SKevin Wolf         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
57691a073a9SKevin Wolf         if (drv) {
57791a073a9SKevin Wolf             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
57891a073a9SKevin Wolf                 drv->format_name);
57991a073a9SKevin Wolf         }
58091a073a9SKevin Wolf 
58191a073a9SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
582d748768cSJan Kiszka         free_option_parameters(options);
58351d7c00cSaliguori         if (ret < 0) {
58451d7c00cSaliguori             return ret;
585ea2384d3Sbellard         }
58691a073a9SKevin Wolf 
587ea2384d3Sbellard         filename = tmp_filename;
58891a073a9SKevin Wolf         drv = bdrv_qcow2;
589ea2384d3Sbellard         bs->is_temporary = 1;
590ea2384d3Sbellard     }
591ea2384d3Sbellard 
592b6ce07aaSKevin Wolf     /* Find the right image format driver */
5936db95603SChristoph Hellwig     if (!drv) {
594c98ac35dSStefan Weil         ret = find_image_format(filename, &drv);
595ea2384d3Sbellard     }
5966987307cSChristoph Hellwig 
59751d7c00cSaliguori     if (!drv) {
59851d7c00cSaliguori         goto unlink_and_fail;
59983f64091Sbellard     }
600b6ce07aaSKevin Wolf 
601b6ce07aaSKevin Wolf     /* Open the image */
602b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
603b6ce07aaSKevin Wolf     if (ret < 0) {
6046987307cSChristoph Hellwig         goto unlink_and_fail;
6056987307cSChristoph Hellwig     }
6066987307cSChristoph Hellwig 
607b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
608b6ce07aaSKevin Wolf     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
609b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
610b6ce07aaSKevin Wolf         int back_flags;
611b6ce07aaSKevin Wolf         BlockDriver *back_drv = NULL;
612b6ce07aaSKevin Wolf 
613b6ce07aaSKevin Wolf         bs->backing_hd = bdrv_new("");
614df2dbb4aSStefan Hajnoczi 
615df2dbb4aSStefan Hajnoczi         if (path_has_protocol(bs->backing_file)) {
616df2dbb4aSStefan Hajnoczi             pstrcpy(backing_filename, sizeof(backing_filename),
617df2dbb4aSStefan Hajnoczi                     bs->backing_file);
618df2dbb4aSStefan Hajnoczi         } else {
619b6ce07aaSKevin Wolf             path_combine(backing_filename, sizeof(backing_filename),
620b6ce07aaSKevin Wolf                          filename, bs->backing_file);
621df2dbb4aSStefan Hajnoczi         }
622df2dbb4aSStefan Hajnoczi 
623df2dbb4aSStefan Hajnoczi         if (bs->backing_format[0] != '\0') {
624b6ce07aaSKevin Wolf             back_drv = bdrv_find_format(bs->backing_format);
625df2dbb4aSStefan Hajnoczi         }
626b6ce07aaSKevin Wolf 
627b6ce07aaSKevin Wolf         /* backing files always opened read-only */
628b6ce07aaSKevin Wolf         back_flags =
629b6ce07aaSKevin Wolf             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
630b6ce07aaSKevin Wolf 
631b6ce07aaSKevin Wolf         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
632b6ce07aaSKevin Wolf         if (ret < 0) {
633b6ce07aaSKevin Wolf             bdrv_close(bs);
634b6ce07aaSKevin Wolf             return ret;
635b6ce07aaSKevin Wolf         }
636b6ce07aaSKevin Wolf         if (bs->is_temporary) {
637b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
638b6ce07aaSKevin Wolf         } else {
639b6ce07aaSKevin Wolf             /* base image inherits from "parent" */
640b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = bs->keep_read_only;
641b6ce07aaSKevin Wolf         }
642b6ce07aaSKevin Wolf     }
643b6ce07aaSKevin Wolf 
644b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
645b6ce07aaSKevin Wolf         /* call the change callback */
646b6ce07aaSKevin Wolf         bs->media_changed = 1;
647b6ce07aaSKevin Wolf         if (bs->change_cb)
648db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
649b6ce07aaSKevin Wolf     }
650b6ce07aaSKevin Wolf 
651b6ce07aaSKevin Wolf     return 0;
652b6ce07aaSKevin Wolf 
653b6ce07aaSKevin Wolf unlink_and_fail:
654b6ce07aaSKevin Wolf     if (bs->is_temporary) {
655b6ce07aaSKevin Wolf         unlink(filename);
656b6ce07aaSKevin Wolf     }
657b6ce07aaSKevin Wolf     return ret;
658b6ce07aaSKevin Wolf }
659b6ce07aaSKevin Wolf 
660fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
661fc01f7e7Sbellard {
66219cb3738Sbellard     if (bs->drv) {
663f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
664f9092b10SMarkus Armbruster             bs_snapshots = NULL;
665f9092b10SMarkus Armbruster         }
666557df6acSStefan Hajnoczi         if (bs->backing_hd) {
667ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
668557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
669557df6acSStefan Hajnoczi         }
670ea2384d3Sbellard         bs->drv->bdrv_close(bs);
671ea2384d3Sbellard         qemu_free(bs->opaque);
672ea2384d3Sbellard #ifdef _WIN32
673ea2384d3Sbellard         if (bs->is_temporary) {
674ea2384d3Sbellard             unlink(bs->filename);
675ea2384d3Sbellard         }
67667b915a5Sbellard #endif
677ea2384d3Sbellard         bs->opaque = NULL;
678ea2384d3Sbellard         bs->drv = NULL;
679b338082bSbellard 
68066f82ceeSKevin Wolf         if (bs->file != NULL) {
68166f82ceeSKevin Wolf             bdrv_close(bs->file);
68266f82ceeSKevin Wolf         }
68366f82ceeSKevin Wolf 
684b338082bSbellard         /* call the change callback */
68519cb3738Sbellard         bs->media_changed = 1;
686b338082bSbellard         if (bs->change_cb)
687db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
688b338082bSbellard     }
689b338082bSbellard }
690b338082bSbellard 
6912bc93fedSMORITA Kazutaka void bdrv_close_all(void)
6922bc93fedSMORITA Kazutaka {
6932bc93fedSMORITA Kazutaka     BlockDriverState *bs;
6942bc93fedSMORITA Kazutaka 
6952bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
6962bc93fedSMORITA Kazutaka         bdrv_close(bs);
6972bc93fedSMORITA Kazutaka     }
6982bc93fedSMORITA Kazutaka }
6992bc93fedSMORITA Kazutaka 
700b338082bSbellard void bdrv_delete(BlockDriverState *bs)
701b338082bSbellard {
70218846deeSMarkus Armbruster     assert(!bs->peer);
70318846deeSMarkus Armbruster 
7041b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
7051b7bdbc1SStefan Hajnoczi     if (bs->device_name[0] != '\0') {
7061b7bdbc1SStefan Hajnoczi         QTAILQ_REMOVE(&bdrv_states, bs, list);
7071b7bdbc1SStefan Hajnoczi     }
70834c6f050Saurel32 
709b338082bSbellard     bdrv_close(bs);
71066f82ceeSKevin Wolf     if (bs->file != NULL) {
71166f82ceeSKevin Wolf         bdrv_delete(bs->file);
71266f82ceeSKevin Wolf     }
71366f82ceeSKevin Wolf 
714f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
715b338082bSbellard     qemu_free(bs);
716fc01f7e7Sbellard }
717fc01f7e7Sbellard 
71818846deeSMarkus Armbruster int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
71918846deeSMarkus Armbruster {
72018846deeSMarkus Armbruster     if (bs->peer) {
72118846deeSMarkus Armbruster         return -EBUSY;
72218846deeSMarkus Armbruster     }
72318846deeSMarkus Armbruster     bs->peer = qdev;
72418846deeSMarkus Armbruster     return 0;
72518846deeSMarkus Armbruster }
72618846deeSMarkus Armbruster 
72718846deeSMarkus Armbruster void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
72818846deeSMarkus Armbruster {
72918846deeSMarkus Armbruster     assert(bs->peer == qdev);
73018846deeSMarkus Armbruster     bs->peer = NULL;
73118846deeSMarkus Armbruster }
73218846deeSMarkus Armbruster 
73318846deeSMarkus Armbruster DeviceState *bdrv_get_attached(BlockDriverState *bs)
73418846deeSMarkus Armbruster {
73518846deeSMarkus Armbruster     return bs->peer;
73618846deeSMarkus Armbruster }
73718846deeSMarkus Armbruster 
738e97fc193Saliguori /*
739e97fc193Saliguori  * Run consistency checks on an image
740e97fc193Saliguori  *
741e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
742e076f338SKevin Wolf  * free of errors) or -errno when an internal error occured. The results of the
743e076f338SKevin Wolf  * check are stored in res.
744e97fc193Saliguori  */
745e076f338SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
746e97fc193Saliguori {
747e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
748e97fc193Saliguori         return -ENOTSUP;
749e97fc193Saliguori     }
750e97fc193Saliguori 
751e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
7529ac228e0SKevin Wolf     return bs->drv->bdrv_check(bs, res);
753e97fc193Saliguori }
754e97fc193Saliguori 
7558a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
7568a426614SKevin Wolf 
75733e3963eSbellard /* commit COW file into the raw image */
75833e3963eSbellard int bdrv_commit(BlockDriverState *bs)
75933e3963eSbellard {
76019cb3738Sbellard     BlockDriver *drv = bs->drv;
761ee181196SKevin Wolf     BlockDriver *backing_drv;
7628a426614SKevin Wolf     int64_t sector, total_sectors;
7638a426614SKevin Wolf     int n, ro, open_flags;
7644dca4b63SNaphtali Sprei     int ret = 0, rw_ret = 0;
7658a426614SKevin Wolf     uint8_t *buf;
7664dca4b63SNaphtali Sprei     char filename[1024];
7674dca4b63SNaphtali Sprei     BlockDriverState *bs_rw, *bs_ro;
76833e3963eSbellard 
76919cb3738Sbellard     if (!drv)
77019cb3738Sbellard         return -ENOMEDIUM;
77133e3963eSbellard 
7724dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
7734dca4b63SNaphtali Sprei         return -ENOTSUP;
7744dca4b63SNaphtali Sprei     }
7754dca4b63SNaphtali Sprei 
7764dca4b63SNaphtali Sprei     if (bs->backing_hd->keep_read_only) {
777ea2384d3Sbellard         return -EACCES;
77833e3963eSbellard     }
77933e3963eSbellard 
780ee181196SKevin Wolf     backing_drv = bs->backing_hd->drv;
7814dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
7824dca4b63SNaphtali Sprei     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
7834dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
7844dca4b63SNaphtali Sprei 
7854dca4b63SNaphtali Sprei     if (ro) {
7864dca4b63SNaphtali Sprei         /* re-open as RW */
7874dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
7884dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
7894dca4b63SNaphtali Sprei         bs_rw = bdrv_new("");
790ee181196SKevin Wolf         rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
791ee181196SKevin Wolf             backing_drv);
7924dca4b63SNaphtali Sprei         if (rw_ret < 0) {
7934dca4b63SNaphtali Sprei             bdrv_delete(bs_rw);
7944dca4b63SNaphtali Sprei             /* try to re-open read-only */
7954dca4b63SNaphtali Sprei             bs_ro = bdrv_new("");
796ee181196SKevin Wolf             ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
797ee181196SKevin Wolf                 backing_drv);
7984dca4b63SNaphtali Sprei             if (ret < 0) {
7994dca4b63SNaphtali Sprei                 bdrv_delete(bs_ro);
8004dca4b63SNaphtali Sprei                 /* drive not functional anymore */
8014dca4b63SNaphtali Sprei                 bs->drv = NULL;
8024dca4b63SNaphtali Sprei                 return ret;
8034dca4b63SNaphtali Sprei             }
8044dca4b63SNaphtali Sprei             bs->backing_hd = bs_ro;
8054dca4b63SNaphtali Sprei             return rw_ret;
8064dca4b63SNaphtali Sprei         }
8074dca4b63SNaphtali Sprei         bs->backing_hd = bs_rw;
808ea2384d3Sbellard     }
809ea2384d3Sbellard 
8106ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
8118a426614SKevin Wolf     buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
8128a426614SKevin Wolf 
8138a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
8148a426614SKevin Wolf         if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
8158a426614SKevin Wolf 
8168a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
8174dca4b63SNaphtali Sprei                 ret = -EIO;
8184dca4b63SNaphtali Sprei                 goto ro_cleanup;
81933e3963eSbellard             }
82033e3963eSbellard 
8218a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
8224dca4b63SNaphtali Sprei                 ret = -EIO;
8234dca4b63SNaphtali Sprei                 goto ro_cleanup;
82433e3963eSbellard             }
82533e3963eSbellard         }
82633e3963eSbellard     }
82795389c86Sbellard 
8281d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
8291d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
8301d44952fSChristoph Hellwig         bdrv_flush(bs);
8311d44952fSChristoph Hellwig     }
83295389c86Sbellard 
8333f5075aeSChristoph Hellwig     /*
8343f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
8353f5075aeSChristoph Hellwig      * stable on disk.
8363f5075aeSChristoph Hellwig      */
8373f5075aeSChristoph Hellwig     if (bs->backing_hd)
8383f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
8394dca4b63SNaphtali Sprei 
8404dca4b63SNaphtali Sprei ro_cleanup:
8418a426614SKevin Wolf     qemu_free(buf);
8424dca4b63SNaphtali Sprei 
8434dca4b63SNaphtali Sprei     if (ro) {
8444dca4b63SNaphtali Sprei         /* re-open as RO */
8454dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
8464dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
8474dca4b63SNaphtali Sprei         bs_ro = bdrv_new("");
848ee181196SKevin Wolf         ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
849ee181196SKevin Wolf             backing_drv);
8504dca4b63SNaphtali Sprei         if (ret < 0) {
8514dca4b63SNaphtali Sprei             bdrv_delete(bs_ro);
8524dca4b63SNaphtali Sprei             /* drive not functional anymore */
8534dca4b63SNaphtali Sprei             bs->drv = NULL;
8544dca4b63SNaphtali Sprei             return ret;
8554dca4b63SNaphtali Sprei         }
8564dca4b63SNaphtali Sprei         bs->backing_hd = bs_ro;
8574dca4b63SNaphtali Sprei         bs->backing_hd->keep_read_only = 0;
8584dca4b63SNaphtali Sprei     }
8594dca4b63SNaphtali Sprei 
8601d44952fSChristoph Hellwig     return ret;
86133e3963eSbellard }
86233e3963eSbellard 
8636ab4b5abSMarkus Armbruster void bdrv_commit_all(void)
8646ab4b5abSMarkus Armbruster {
8656ab4b5abSMarkus Armbruster     BlockDriverState *bs;
8666ab4b5abSMarkus Armbruster 
8676ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
8686ab4b5abSMarkus Armbruster         bdrv_commit(bs);
8696ab4b5abSMarkus Armbruster     }
8706ab4b5abSMarkus Armbruster }
8716ab4b5abSMarkus Armbruster 
872756e6736SKevin Wolf /*
873756e6736SKevin Wolf  * Return values:
874756e6736SKevin Wolf  * 0        - success
875756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
876756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
877756e6736SKevin Wolf  *            image file header
878756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
879756e6736SKevin Wolf  */
880756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
881756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
882756e6736SKevin Wolf {
883756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
884756e6736SKevin Wolf 
885756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
886756e6736SKevin Wolf         return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
887756e6736SKevin Wolf     } else {
888756e6736SKevin Wolf         return -ENOTSUP;
889756e6736SKevin Wolf     }
890756e6736SKevin Wolf }
891756e6736SKevin Wolf 
89271d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
89371d0770cSaliguori                                    size_t size)
89471d0770cSaliguori {
89571d0770cSaliguori     int64_t len;
89671d0770cSaliguori 
89771d0770cSaliguori     if (!bdrv_is_inserted(bs))
89871d0770cSaliguori         return -ENOMEDIUM;
89971d0770cSaliguori 
90071d0770cSaliguori     if (bs->growable)
90171d0770cSaliguori         return 0;
90271d0770cSaliguori 
90371d0770cSaliguori     len = bdrv_getlength(bs);
90471d0770cSaliguori 
905fbb7b4e0SKevin Wolf     if (offset < 0)
906fbb7b4e0SKevin Wolf         return -EIO;
907fbb7b4e0SKevin Wolf 
908fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
90971d0770cSaliguori         return -EIO;
91071d0770cSaliguori 
91171d0770cSaliguori     return 0;
91271d0770cSaliguori }
91371d0770cSaliguori 
91471d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
91571d0770cSaliguori                               int nb_sectors)
91671d0770cSaliguori {
917eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
918eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
91971d0770cSaliguori }
92071d0770cSaliguori 
92119cb3738Sbellard /* return < 0 if error. See bdrv_write() for the return codes */
922fc01f7e7Sbellard int bdrv_read(BlockDriverState *bs, int64_t sector_num,
923fc01f7e7Sbellard               uint8_t *buf, int nb_sectors)
924fc01f7e7Sbellard {
925ea2384d3Sbellard     BlockDriver *drv = bs->drv;
926fc01f7e7Sbellard 
92719cb3738Sbellard     if (!drv)
92819cb3738Sbellard         return -ENOMEDIUM;
92971d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
93071d0770cSaliguori         return -EIO;
931b338082bSbellard 
93283f64091Sbellard     return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
93383f64091Sbellard }
934fc01f7e7Sbellard 
9357cd1e32aSlirans@il.ibm.com static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
9367cd1e32aSlirans@il.ibm.com                              int nb_sectors, int dirty)
9377cd1e32aSlirans@il.ibm.com {
9387cd1e32aSlirans@il.ibm.com     int64_t start, end;
939c6d22830SJan Kiszka     unsigned long val, idx, bit;
940a55eb92cSJan Kiszka 
9416ea44308SJan Kiszka     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
942c6d22830SJan Kiszka     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
9437cd1e32aSlirans@il.ibm.com 
9447cd1e32aSlirans@il.ibm.com     for (; start <= end; start++) {
945c6d22830SJan Kiszka         idx = start / (sizeof(unsigned long) * 8);
946c6d22830SJan Kiszka         bit = start % (sizeof(unsigned long) * 8);
947c6d22830SJan Kiszka         val = bs->dirty_bitmap[idx];
948c6d22830SJan Kiszka         if (dirty) {
9496d59fec1SMarcelo Tosatti             if (!(val & (1UL << bit))) {
950aaa0eb75SLiran Schour                 bs->dirty_count++;
9516d59fec1SMarcelo Tosatti                 val |= 1UL << bit;
952aaa0eb75SLiran Schour             }
953c6d22830SJan Kiszka         } else {
9546d59fec1SMarcelo Tosatti             if (val & (1UL << bit)) {
955aaa0eb75SLiran Schour                 bs->dirty_count--;
9566d59fec1SMarcelo Tosatti                 val &= ~(1UL << bit);
957c6d22830SJan Kiszka             }
958aaa0eb75SLiran Schour         }
959c6d22830SJan Kiszka         bs->dirty_bitmap[idx] = val;
9607cd1e32aSlirans@il.ibm.com     }
9617cd1e32aSlirans@il.ibm.com }
9627cd1e32aSlirans@il.ibm.com 
96319cb3738Sbellard /* Return < 0 if error. Important errors are:
96419cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
96519cb3738Sbellard   -ENOMEDIUM   No media inserted.
96619cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
96719cb3738Sbellard   -EACCES      Trying to write a read-only device
96819cb3738Sbellard */
969fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
970fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
971fc01f7e7Sbellard {
97283f64091Sbellard     BlockDriver *drv = bs->drv;
97319cb3738Sbellard     if (!bs->drv)
97419cb3738Sbellard         return -ENOMEDIUM;
9750849bf08Sbellard     if (bs->read_only)
97619cb3738Sbellard         return -EACCES;
97771d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
97871d0770cSaliguori         return -EIO;
97971d0770cSaliguori 
980c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
9817cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
9827cd1e32aSlirans@il.ibm.com     }
9837cd1e32aSlirans@il.ibm.com 
984294cc35fSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
985294cc35fSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
986294cc35fSKevin Wolf     }
987294cc35fSKevin Wolf 
98883f64091Sbellard     return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
98983f64091Sbellard }
99083f64091Sbellard 
991eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
992eda578e5Saliguori                void *buf, int count1)
99383f64091Sbellard {
9946ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
99583f64091Sbellard     int len, nb_sectors, count;
99683f64091Sbellard     int64_t sector_num;
9979a8c4cceSKevin Wolf     int ret;
99883f64091Sbellard 
99983f64091Sbellard     count = count1;
100083f64091Sbellard     /* first read to align to sector start */
10016ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
100283f64091Sbellard     if (len > count)
100383f64091Sbellard         len = count;
10046ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
100583f64091Sbellard     if (len > 0) {
10069a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10079a8c4cceSKevin Wolf             return ret;
10086ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
100983f64091Sbellard         count -= len;
101083f64091Sbellard         if (count == 0)
101183f64091Sbellard             return count1;
101283f64091Sbellard         sector_num++;
101383f64091Sbellard         buf += len;
101483f64091Sbellard     }
101583f64091Sbellard 
101683f64091Sbellard     /* read the sectors "in place" */
10176ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
101883f64091Sbellard     if (nb_sectors > 0) {
10199a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
10209a8c4cceSKevin Wolf             return ret;
102183f64091Sbellard         sector_num += nb_sectors;
10226ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
102383f64091Sbellard         buf += len;
102483f64091Sbellard         count -= len;
102583f64091Sbellard     }
102683f64091Sbellard 
102783f64091Sbellard     /* add data from the last sector */
102883f64091Sbellard     if (count > 0) {
10299a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10309a8c4cceSKevin Wolf             return ret;
103183f64091Sbellard         memcpy(buf, tmp_buf, count);
103283f64091Sbellard     }
103383f64091Sbellard     return count1;
103483f64091Sbellard }
103583f64091Sbellard 
1036eda578e5Saliguori int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1037eda578e5Saliguori                 const void *buf, int count1)
103883f64091Sbellard {
10396ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
104083f64091Sbellard     int len, nb_sectors, count;
104183f64091Sbellard     int64_t sector_num;
10429a8c4cceSKevin Wolf     int ret;
104383f64091Sbellard 
104483f64091Sbellard     count = count1;
104583f64091Sbellard     /* first write to align to sector start */
10466ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
104783f64091Sbellard     if (len > count)
104883f64091Sbellard         len = count;
10496ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
105083f64091Sbellard     if (len > 0) {
10519a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10529a8c4cceSKevin Wolf             return ret;
10536ea44308SJan Kiszka         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
10549a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
10559a8c4cceSKevin Wolf             return ret;
105683f64091Sbellard         count -= len;
105783f64091Sbellard         if (count == 0)
105883f64091Sbellard             return count1;
105983f64091Sbellard         sector_num++;
106083f64091Sbellard         buf += len;
106183f64091Sbellard     }
106283f64091Sbellard 
106383f64091Sbellard     /* write the sectors "in place" */
10646ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
106583f64091Sbellard     if (nb_sectors > 0) {
10669a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
10679a8c4cceSKevin Wolf             return ret;
106883f64091Sbellard         sector_num += nb_sectors;
10696ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
107083f64091Sbellard         buf += len;
107183f64091Sbellard         count -= len;
107283f64091Sbellard     }
107383f64091Sbellard 
107483f64091Sbellard     /* add data from the last sector */
107583f64091Sbellard     if (count > 0) {
10769a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10779a8c4cceSKevin Wolf             return ret;
107883f64091Sbellard         memcpy(tmp_buf, buf, count);
10799a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
10809a8c4cceSKevin Wolf             return ret;
108183f64091Sbellard     }
108283f64091Sbellard     return count1;
108383f64091Sbellard }
108483f64091Sbellard 
1085f08145feSKevin Wolf /*
1086f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1087f08145feSKevin Wolf  * request (acts as a barrier)
1088f08145feSKevin Wolf  *
1089f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1090f08145feSKevin Wolf  */
1091f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1092f08145feSKevin Wolf     const void *buf, int count)
1093f08145feSKevin Wolf {
1094f08145feSKevin Wolf     int ret;
1095f08145feSKevin Wolf 
1096f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
1097f08145feSKevin Wolf     if (ret < 0) {
1098f08145feSKevin Wolf         return ret;
1099f08145feSKevin Wolf     }
1100f08145feSKevin Wolf 
1101f08145feSKevin Wolf     /* No flush needed for cache=writethrough, it uses O_DSYNC */
1102f08145feSKevin Wolf     if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1103f08145feSKevin Wolf         bdrv_flush(bs);
1104f08145feSKevin Wolf     }
1105f08145feSKevin Wolf 
1106f08145feSKevin Wolf     return 0;
1107f08145feSKevin Wolf }
1108f08145feSKevin Wolf 
1109f08145feSKevin Wolf /*
1110f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1111f08145feSKevin Wolf  * request (acts as a barrier)
1112f08145feSKevin Wolf  *
1113f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1114f08145feSKevin Wolf  */
1115f08145feSKevin Wolf int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1116f08145feSKevin Wolf     const uint8_t *buf, int nb_sectors)
1117f08145feSKevin Wolf {
1118f08145feSKevin Wolf     return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1119f08145feSKevin Wolf         buf, BDRV_SECTOR_SIZE * nb_sectors);
1120f08145feSKevin Wolf }
1121f08145feSKevin Wolf 
112283f64091Sbellard /**
112383f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
112483f64091Sbellard  */
112583f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
112683f64091Sbellard {
112783f64091Sbellard     BlockDriver *drv = bs->drv;
112851762288SStefan Hajnoczi     int ret;
112983f64091Sbellard     if (!drv)
113019cb3738Sbellard         return -ENOMEDIUM;
113183f64091Sbellard     if (!drv->bdrv_truncate)
113283f64091Sbellard         return -ENOTSUP;
113359f2689dSNaphtali Sprei     if (bs->read_only)
113459f2689dSNaphtali Sprei         return -EACCES;
11358591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
11368591675fSMarcelo Tosatti         return -EBUSY;
113751762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
113851762288SStefan Hajnoczi     if (ret == 0) {
113951762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1140db97ee6aSChristoph Hellwig         if (bs->change_cb) {
1141db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1142db97ee6aSChristoph Hellwig         }
114351762288SStefan Hajnoczi     }
114451762288SStefan Hajnoczi     return ret;
114583f64091Sbellard }
114683f64091Sbellard 
114783f64091Sbellard /**
114883f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
114983f64091Sbellard  */
115083f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
115183f64091Sbellard {
115283f64091Sbellard     BlockDriver *drv = bs->drv;
115383f64091Sbellard     if (!drv)
115419cb3738Sbellard         return -ENOMEDIUM;
115551762288SStefan Hajnoczi 
115651762288SStefan Hajnoczi     /* Fixed size devices use the total_sectors value for speed instead of
115751762288SStefan Hajnoczi        issuing a length query (like lseek) on each call.  Also, legacy block
115851762288SStefan Hajnoczi        drivers don't provide a bdrv_getlength function and must use
115951762288SStefan Hajnoczi        total_sectors. */
116051762288SStefan Hajnoczi     if (!bs->growable || !drv->bdrv_getlength) {
11616ea44308SJan Kiszka         return bs->total_sectors * BDRV_SECTOR_SIZE;
116283f64091Sbellard     }
116383f64091Sbellard     return drv->bdrv_getlength(bs);
1164fc01f7e7Sbellard }
1165fc01f7e7Sbellard 
116619cb3738Sbellard /* return 0 as number of sectors if no device present or error */
116796b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1168fc01f7e7Sbellard {
116919cb3738Sbellard     int64_t length;
117019cb3738Sbellard     length = bdrv_getlength(bs);
117119cb3738Sbellard     if (length < 0)
117219cb3738Sbellard         length = 0;
117319cb3738Sbellard     else
11746ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
117519cb3738Sbellard     *nb_sectors_ptr = length;
1176fc01f7e7Sbellard }
1177cf98951bSbellard 
1178f3d54fc4Saliguori struct partition {
1179f3d54fc4Saliguori         uint8_t boot_ind;           /* 0x80 - active */
1180f3d54fc4Saliguori         uint8_t head;               /* starting head */
1181f3d54fc4Saliguori         uint8_t sector;             /* starting sector */
1182f3d54fc4Saliguori         uint8_t cyl;                /* starting cylinder */
1183f3d54fc4Saliguori         uint8_t sys_ind;            /* What partition type */
1184f3d54fc4Saliguori         uint8_t end_head;           /* end head */
1185f3d54fc4Saliguori         uint8_t end_sector;         /* end sector */
1186f3d54fc4Saliguori         uint8_t end_cyl;            /* end cylinder */
1187f3d54fc4Saliguori         uint32_t start_sect;        /* starting sector counting from 0 */
1188f3d54fc4Saliguori         uint32_t nr_sects;          /* nr of sectors in partition */
1189f3d54fc4Saliguori } __attribute__((packed));
1190f3d54fc4Saliguori 
1191f3d54fc4Saliguori /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1192f3d54fc4Saliguori static int guess_disk_lchs(BlockDriverState *bs,
1193f3d54fc4Saliguori                            int *pcylinders, int *pheads, int *psectors)
1194f3d54fc4Saliguori {
1195eb5a3165SJes Sorensen     uint8_t buf[BDRV_SECTOR_SIZE];
1196f3d54fc4Saliguori     int ret, i, heads, sectors, cylinders;
1197f3d54fc4Saliguori     struct partition *p;
1198f3d54fc4Saliguori     uint32_t nr_sects;
1199a38131b6Sblueswir1     uint64_t nb_sectors;
1200f3d54fc4Saliguori 
1201f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1202f3d54fc4Saliguori 
1203f3d54fc4Saliguori     ret = bdrv_read(bs, 0, buf, 1);
1204f3d54fc4Saliguori     if (ret < 0)
1205f3d54fc4Saliguori         return -1;
1206f3d54fc4Saliguori     /* test msdos magic */
1207f3d54fc4Saliguori     if (buf[510] != 0x55 || buf[511] != 0xaa)
1208f3d54fc4Saliguori         return -1;
1209f3d54fc4Saliguori     for(i = 0; i < 4; i++) {
1210f3d54fc4Saliguori         p = ((struct partition *)(buf + 0x1be)) + i;
1211f3d54fc4Saliguori         nr_sects = le32_to_cpu(p->nr_sects);
1212f3d54fc4Saliguori         if (nr_sects && p->end_head) {
1213f3d54fc4Saliguori             /* We make the assumption that the partition terminates on
1214f3d54fc4Saliguori                a cylinder boundary */
1215f3d54fc4Saliguori             heads = p->end_head + 1;
1216f3d54fc4Saliguori             sectors = p->end_sector & 63;
1217f3d54fc4Saliguori             if (sectors == 0)
1218f3d54fc4Saliguori                 continue;
1219f3d54fc4Saliguori             cylinders = nb_sectors / (heads * sectors);
1220f3d54fc4Saliguori             if (cylinders < 1 || cylinders > 16383)
1221f3d54fc4Saliguori                 continue;
1222f3d54fc4Saliguori             *pheads = heads;
1223f3d54fc4Saliguori             *psectors = sectors;
1224f3d54fc4Saliguori             *pcylinders = cylinders;
1225f3d54fc4Saliguori #if 0
1226f3d54fc4Saliguori             printf("guessed geometry: LCHS=%d %d %d\n",
1227f3d54fc4Saliguori                    cylinders, heads, sectors);
1228f3d54fc4Saliguori #endif
1229f3d54fc4Saliguori             return 0;
1230f3d54fc4Saliguori         }
1231f3d54fc4Saliguori     }
1232f3d54fc4Saliguori     return -1;
1233f3d54fc4Saliguori }
1234f3d54fc4Saliguori 
1235f3d54fc4Saliguori void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1236f3d54fc4Saliguori {
1237f3d54fc4Saliguori     int translation, lba_detected = 0;
1238f3d54fc4Saliguori     int cylinders, heads, secs;
1239a38131b6Sblueswir1     uint64_t nb_sectors;
1240f3d54fc4Saliguori 
1241f3d54fc4Saliguori     /* if a geometry hint is available, use it */
1242f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1243f3d54fc4Saliguori     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1244f3d54fc4Saliguori     translation = bdrv_get_translation_hint(bs);
1245f3d54fc4Saliguori     if (cylinders != 0) {
1246f3d54fc4Saliguori         *pcyls = cylinders;
1247f3d54fc4Saliguori         *pheads = heads;
1248f3d54fc4Saliguori         *psecs = secs;
1249f3d54fc4Saliguori     } else {
1250f3d54fc4Saliguori         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1251f3d54fc4Saliguori             if (heads > 16) {
1252f3d54fc4Saliguori                 /* if heads > 16, it means that a BIOS LBA
1253f3d54fc4Saliguori                    translation was active, so the default
1254f3d54fc4Saliguori                    hardware geometry is OK */
1255f3d54fc4Saliguori                 lba_detected = 1;
1256f3d54fc4Saliguori                 goto default_geometry;
1257f3d54fc4Saliguori             } else {
1258f3d54fc4Saliguori                 *pcyls = cylinders;
1259f3d54fc4Saliguori                 *pheads = heads;
1260f3d54fc4Saliguori                 *psecs = secs;
1261f3d54fc4Saliguori                 /* disable any translation to be in sync with
1262f3d54fc4Saliguori                    the logical geometry */
1263f3d54fc4Saliguori                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1264f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1265f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_NONE);
1266f3d54fc4Saliguori                 }
1267f3d54fc4Saliguori             }
1268f3d54fc4Saliguori         } else {
1269f3d54fc4Saliguori         default_geometry:
1270f3d54fc4Saliguori             /* if no geometry, use a standard physical disk geometry */
1271f3d54fc4Saliguori             cylinders = nb_sectors / (16 * 63);
1272f3d54fc4Saliguori 
1273f3d54fc4Saliguori             if (cylinders > 16383)
1274f3d54fc4Saliguori                 cylinders = 16383;
1275f3d54fc4Saliguori             else if (cylinders < 2)
1276f3d54fc4Saliguori                 cylinders = 2;
1277f3d54fc4Saliguori             *pcyls = cylinders;
1278f3d54fc4Saliguori             *pheads = 16;
1279f3d54fc4Saliguori             *psecs = 63;
1280f3d54fc4Saliguori             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1281f3d54fc4Saliguori                 if ((*pcyls * *pheads) <= 131072) {
1282f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1283f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LARGE);
1284f3d54fc4Saliguori                 } else {
1285f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1286f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LBA);
1287f3d54fc4Saliguori                 }
1288f3d54fc4Saliguori             }
1289f3d54fc4Saliguori         }
1290f3d54fc4Saliguori         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1291f3d54fc4Saliguori     }
1292f3d54fc4Saliguori }
1293f3d54fc4Saliguori 
1294b338082bSbellard void bdrv_set_geometry_hint(BlockDriverState *bs,
1295b338082bSbellard                             int cyls, int heads, int secs)
1296b338082bSbellard {
1297b338082bSbellard     bs->cyls = cyls;
1298b338082bSbellard     bs->heads = heads;
1299b338082bSbellard     bs->secs = secs;
1300b338082bSbellard }
1301b338082bSbellard 
1302b338082bSbellard void bdrv_set_type_hint(BlockDriverState *bs, int type)
1303b338082bSbellard {
1304b338082bSbellard     bs->type = type;
1305b338082bSbellard     bs->removable = ((type == BDRV_TYPE_CDROM ||
1306b338082bSbellard                       type == BDRV_TYPE_FLOPPY));
1307b338082bSbellard }
1308b338082bSbellard 
130946d4767dSbellard void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
131046d4767dSbellard {
131146d4767dSbellard     bs->translation = translation;
131246d4767dSbellard }
131346d4767dSbellard 
1314b338082bSbellard void bdrv_get_geometry_hint(BlockDriverState *bs,
1315b338082bSbellard                             int *pcyls, int *pheads, int *psecs)
1316b338082bSbellard {
1317b338082bSbellard     *pcyls = bs->cyls;
1318b338082bSbellard     *pheads = bs->heads;
1319b338082bSbellard     *psecs = bs->secs;
1320b338082bSbellard }
1321b338082bSbellard 
13225bbdbb46SBlue Swirl /* Recognize floppy formats */
13235bbdbb46SBlue Swirl typedef struct FDFormat {
13245bbdbb46SBlue Swirl     FDriveType drive;
13255bbdbb46SBlue Swirl     uint8_t last_sect;
13265bbdbb46SBlue Swirl     uint8_t max_track;
13275bbdbb46SBlue Swirl     uint8_t max_head;
13285bbdbb46SBlue Swirl } FDFormat;
13295bbdbb46SBlue Swirl 
13305bbdbb46SBlue Swirl static const FDFormat fd_formats[] = {
13315bbdbb46SBlue Swirl     /* First entry is default format */
13325bbdbb46SBlue Swirl     /* 1.44 MB 3"1/2 floppy disks */
13335bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 18, 80, 1, },
13345bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 20, 80, 1, },
13355bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 21, 80, 1, },
13365bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 21, 82, 1, },
13375bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 21, 83, 1, },
13385bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 22, 80, 1, },
13395bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 23, 80, 1, },
13405bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 24, 80, 1, },
13415bbdbb46SBlue Swirl     /* 2.88 MB 3"1/2 floppy disks */
13425bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 36, 80, 1, },
13435bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 39, 80, 1, },
13445bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 40, 80, 1, },
13455bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 44, 80, 1, },
13465bbdbb46SBlue Swirl     { FDRIVE_DRV_288, 48, 80, 1, },
13475bbdbb46SBlue Swirl     /* 720 kB 3"1/2 floppy disks */
13485bbdbb46SBlue Swirl     { FDRIVE_DRV_144,  9, 80, 1, },
13495bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 10, 80, 1, },
13505bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 10, 82, 1, },
13515bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 10, 83, 1, },
13525bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 13, 80, 1, },
13535bbdbb46SBlue Swirl     { FDRIVE_DRV_144, 14, 80, 1, },
13545bbdbb46SBlue Swirl     /* 1.2 MB 5"1/4 floppy disks */
13555bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 15, 80, 1, },
13565bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 18, 80, 1, },
13575bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 18, 82, 1, },
13585bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 18, 83, 1, },
13595bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 20, 80, 1, },
13605bbdbb46SBlue Swirl     /* 720 kB 5"1/4 floppy disks */
13615bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  9, 80, 1, },
13625bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 11, 80, 1, },
13635bbdbb46SBlue Swirl     /* 360 kB 5"1/4 floppy disks */
13645bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  9, 40, 1, },
13655bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  9, 40, 0, },
13665bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 10, 41, 1, },
13675bbdbb46SBlue Swirl     { FDRIVE_DRV_120, 10, 42, 1, },
13685bbdbb46SBlue Swirl     /* 320 kB 5"1/4 floppy disks */
13695bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  8, 40, 1, },
13705bbdbb46SBlue Swirl     { FDRIVE_DRV_120,  8, 40, 0, },
13715bbdbb46SBlue Swirl     /* 360 kB must match 5"1/4 better than 3"1/2... */
13725bbdbb46SBlue Swirl     { FDRIVE_DRV_144,  9, 80, 0, },
13735bbdbb46SBlue Swirl     /* end */
13745bbdbb46SBlue Swirl     { FDRIVE_DRV_NONE, -1, -1, 0, },
13755bbdbb46SBlue Swirl };
13765bbdbb46SBlue Swirl 
13775bbdbb46SBlue Swirl void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
13785bbdbb46SBlue Swirl                                    int *max_track, int *last_sect,
13795bbdbb46SBlue Swirl                                    FDriveType drive_in, FDriveType *drive)
13805bbdbb46SBlue Swirl {
13815bbdbb46SBlue Swirl     const FDFormat *parse;
13825bbdbb46SBlue Swirl     uint64_t nb_sectors, size;
13835bbdbb46SBlue Swirl     int i, first_match, match;
13845bbdbb46SBlue Swirl 
13855bbdbb46SBlue Swirl     bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
13865bbdbb46SBlue Swirl     if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
13875bbdbb46SBlue Swirl         /* User defined disk */
13885bbdbb46SBlue Swirl     } else {
13895bbdbb46SBlue Swirl         bdrv_get_geometry(bs, &nb_sectors);
13905bbdbb46SBlue Swirl         match = -1;
13915bbdbb46SBlue Swirl         first_match = -1;
13925bbdbb46SBlue Swirl         for (i = 0; ; i++) {
13935bbdbb46SBlue Swirl             parse = &fd_formats[i];
13945bbdbb46SBlue Swirl             if (parse->drive == FDRIVE_DRV_NONE) {
13955bbdbb46SBlue Swirl                 break;
13965bbdbb46SBlue Swirl             }
13975bbdbb46SBlue Swirl             if (drive_in == parse->drive ||
13985bbdbb46SBlue Swirl                 drive_in == FDRIVE_DRV_NONE) {
13995bbdbb46SBlue Swirl                 size = (parse->max_head + 1) * parse->max_track *
14005bbdbb46SBlue Swirl                     parse->last_sect;
14015bbdbb46SBlue Swirl                 if (nb_sectors == size) {
14025bbdbb46SBlue Swirl                     match = i;
14035bbdbb46SBlue Swirl                     break;
14045bbdbb46SBlue Swirl                 }
14055bbdbb46SBlue Swirl                 if (first_match == -1) {
14065bbdbb46SBlue Swirl                     first_match = i;
14075bbdbb46SBlue Swirl                 }
14085bbdbb46SBlue Swirl             }
14095bbdbb46SBlue Swirl         }
14105bbdbb46SBlue Swirl         if (match == -1) {
14115bbdbb46SBlue Swirl             if (first_match == -1) {
14125bbdbb46SBlue Swirl                 match = 1;
14135bbdbb46SBlue Swirl             } else {
14145bbdbb46SBlue Swirl                 match = first_match;
14155bbdbb46SBlue Swirl             }
14165bbdbb46SBlue Swirl             parse = &fd_formats[match];
14175bbdbb46SBlue Swirl         }
14185bbdbb46SBlue Swirl         *nb_heads = parse->max_head + 1;
14195bbdbb46SBlue Swirl         *max_track = parse->max_track;
14205bbdbb46SBlue Swirl         *last_sect = parse->last_sect;
14215bbdbb46SBlue Swirl         *drive = parse->drive;
14225bbdbb46SBlue Swirl     }
14235bbdbb46SBlue Swirl }
14245bbdbb46SBlue Swirl 
1425b338082bSbellard int bdrv_get_type_hint(BlockDriverState *bs)
1426b338082bSbellard {
1427b338082bSbellard     return bs->type;
1428b338082bSbellard }
1429b338082bSbellard 
143046d4767dSbellard int bdrv_get_translation_hint(BlockDriverState *bs)
143146d4767dSbellard {
143246d4767dSbellard     return bs->translation;
143346d4767dSbellard }
143446d4767dSbellard 
1435abd7f68dSMarkus Armbruster void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1436abd7f68dSMarkus Armbruster                        BlockErrorAction on_write_error)
1437abd7f68dSMarkus Armbruster {
1438abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
1439abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
1440abd7f68dSMarkus Armbruster }
1441abd7f68dSMarkus Armbruster 
1442abd7f68dSMarkus Armbruster BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1443abd7f68dSMarkus Armbruster {
1444abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
1445abd7f68dSMarkus Armbruster }
1446abd7f68dSMarkus Armbruster 
14477d0d6950SMarkus Armbruster void bdrv_set_removable(BlockDriverState *bs, int removable)
14487d0d6950SMarkus Armbruster {
14497d0d6950SMarkus Armbruster     bs->removable = removable;
14507d0d6950SMarkus Armbruster     if (removable && bs == bs_snapshots) {
14517d0d6950SMarkus Armbruster         bs_snapshots = NULL;
14527d0d6950SMarkus Armbruster     }
14537d0d6950SMarkus Armbruster }
14547d0d6950SMarkus Armbruster 
1455b338082bSbellard int bdrv_is_removable(BlockDriverState *bs)
1456b338082bSbellard {
1457b338082bSbellard     return bs->removable;
1458b338082bSbellard }
1459b338082bSbellard 
1460b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
1461b338082bSbellard {
1462b338082bSbellard     return bs->read_only;
1463b338082bSbellard }
1464b338082bSbellard 
1465985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
1466985a03b0Sths {
1467985a03b0Sths     return bs->sg;
1468985a03b0Sths }
1469985a03b0Sths 
1470e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
1471e900a7b7SChristoph Hellwig {
1472e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
1473e900a7b7SChristoph Hellwig }
1474e900a7b7SChristoph Hellwig 
147519cb3738Sbellard /* XXX: no longer used */
1476b338082bSbellard void bdrv_set_change_cb(BlockDriverState *bs,
1477db97ee6aSChristoph Hellwig                         void (*change_cb)(void *opaque, int reason),
1478db97ee6aSChristoph Hellwig                         void *opaque)
1479b338082bSbellard {
1480b338082bSbellard     bs->change_cb = change_cb;
1481b338082bSbellard     bs->change_opaque = opaque;
1482b338082bSbellard }
1483b338082bSbellard 
1484ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
1485ea2384d3Sbellard {
1486ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
1487ea2384d3Sbellard         return 1;
1488ea2384d3Sbellard     return bs->encrypted;
1489ea2384d3Sbellard }
1490ea2384d3Sbellard 
1491c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
1492c0f4ce77Saliguori {
1493c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
1494c0f4ce77Saliguori 
1495c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1496c0f4ce77Saliguori         return 1;
1497c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
1498c0f4ce77Saliguori }
1499c0f4ce77Saliguori 
1500ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
1501ea2384d3Sbellard {
1502ea2384d3Sbellard     int ret;
1503ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
1504ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
1505ea2384d3Sbellard         if (ret < 0)
1506ea2384d3Sbellard             return ret;
1507ea2384d3Sbellard         if (!bs->encrypted)
1508ea2384d3Sbellard             return 0;
1509ea2384d3Sbellard     }
1510fd04a2aeSShahar Havivi     if (!bs->encrypted) {
1511fd04a2aeSShahar Havivi         return -EINVAL;
1512fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1513fd04a2aeSShahar Havivi         return -ENOMEDIUM;
1514fd04a2aeSShahar Havivi     }
1515c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
1516bb5fc20fSaliguori     if (ret < 0) {
1517bb5fc20fSaliguori         bs->valid_key = 0;
1518bb5fc20fSaliguori     } else if (!bs->valid_key) {
1519bb5fc20fSaliguori         bs->valid_key = 1;
1520bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
1521bb5fc20fSaliguori         bs->media_changed = 1;
1522bb5fc20fSaliguori         if (bs->change_cb)
1523db97ee6aSChristoph Hellwig             bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
1524bb5fc20fSaliguori     }
1525c0f4ce77Saliguori     return ret;
1526ea2384d3Sbellard }
1527ea2384d3Sbellard 
1528ea2384d3Sbellard void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1529ea2384d3Sbellard {
153019cb3738Sbellard     if (!bs->drv) {
1531ea2384d3Sbellard         buf[0] = '\0';
1532ea2384d3Sbellard     } else {
1533ea2384d3Sbellard         pstrcpy(buf, buf_size, bs->drv->format_name);
1534ea2384d3Sbellard     }
1535ea2384d3Sbellard }
1536ea2384d3Sbellard 
1537ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1538ea2384d3Sbellard                          void *opaque)
1539ea2384d3Sbellard {
1540ea2384d3Sbellard     BlockDriver *drv;
1541ea2384d3Sbellard 
15428a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
1543ea2384d3Sbellard         it(opaque, drv->format_name);
1544ea2384d3Sbellard     }
1545ea2384d3Sbellard }
1546ea2384d3Sbellard 
1547b338082bSbellard BlockDriverState *bdrv_find(const char *name)
1548b338082bSbellard {
1549b338082bSbellard     BlockDriverState *bs;
1550b338082bSbellard 
15511b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
15521b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
1553b338082bSbellard             return bs;
1554b338082bSbellard         }
15551b7bdbc1SStefan Hajnoczi     }
1556b338082bSbellard     return NULL;
1557b338082bSbellard }
1558b338082bSbellard 
15592f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
15602f399b0aSMarkus Armbruster {
15612f399b0aSMarkus Armbruster     if (!bs) {
15622f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
15632f399b0aSMarkus Armbruster     }
15642f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
15652f399b0aSMarkus Armbruster }
15662f399b0aSMarkus Armbruster 
156751de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
156881d0912dSbellard {
156981d0912dSbellard     BlockDriverState *bs;
157081d0912dSbellard 
15711b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
157251de9760Saliguori         it(opaque, bs);
157381d0912dSbellard     }
157481d0912dSbellard }
157581d0912dSbellard 
1576ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
1577ea2384d3Sbellard {
1578ea2384d3Sbellard     return bs->device_name;
1579ea2384d3Sbellard }
1580ea2384d3Sbellard 
1581205ef796SKevin Wolf int bdrv_flush(BlockDriverState *bs)
15827a6cba61Spbrook {
1583016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
1584205ef796SKevin Wolf         return 0;
1585016f5cf6SAlexander Graf     }
1586016f5cf6SAlexander Graf 
1587205ef796SKevin Wolf     if (bs->drv && bs->drv->bdrv_flush) {
1588205ef796SKevin Wolf         return bs->drv->bdrv_flush(bs);
1589205ef796SKevin Wolf     }
1590205ef796SKevin Wolf 
1591205ef796SKevin Wolf     /*
1592205ef796SKevin Wolf      * Some block drivers always operate in either writethrough or unsafe mode
1593205ef796SKevin Wolf      * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1594205ef796SKevin Wolf      * the server works (because the behaviour is hardcoded or depends on
1595205ef796SKevin Wolf      * server-side configuration), so we can't ensure that everything is safe
1596205ef796SKevin Wolf      * on disk. Returning an error doesn't work because that would break guests
1597205ef796SKevin Wolf      * even if the server operates in writethrough mode.
1598205ef796SKevin Wolf      *
1599205ef796SKevin Wolf      * Let's hope the user knows what he's doing.
1600205ef796SKevin Wolf      */
1601205ef796SKevin Wolf     return 0;
16027a6cba61Spbrook }
16037a6cba61Spbrook 
1604c6ca28d6Saliguori void bdrv_flush_all(void)
1605c6ca28d6Saliguori {
1606c6ca28d6Saliguori     BlockDriverState *bs;
1607c6ca28d6Saliguori 
16081b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1609c6ca28d6Saliguori         if (bs->drv && !bdrv_is_read_only(bs) &&
16101b7bdbc1SStefan Hajnoczi             (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1611c6ca28d6Saliguori             bdrv_flush(bs);
1612c6ca28d6Saliguori         }
16131b7bdbc1SStefan Hajnoczi     }
16141b7bdbc1SStefan Hajnoczi }
1615c6ca28d6Saliguori 
1616f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
1617f2feebbdSKevin Wolf {
1618f2feebbdSKevin Wolf     assert(bs->drv);
1619f2feebbdSKevin Wolf 
1620336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
1621336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
1622f2feebbdSKevin Wolf     }
1623f2feebbdSKevin Wolf 
1624f2feebbdSKevin Wolf     return 1;
1625f2feebbdSKevin Wolf }
1626f2feebbdSKevin Wolf 
1627bb8bf76fSChristoph Hellwig int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1628bb8bf76fSChristoph Hellwig {
1629bb8bf76fSChristoph Hellwig     if (!bs->drv) {
1630bb8bf76fSChristoph Hellwig         return -ENOMEDIUM;
1631bb8bf76fSChristoph Hellwig     }
1632bb8bf76fSChristoph Hellwig     if (!bs->drv->bdrv_discard) {
1633bb8bf76fSChristoph Hellwig         return 0;
1634bb8bf76fSChristoph Hellwig     }
1635bb8bf76fSChristoph Hellwig     return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1636bb8bf76fSChristoph Hellwig }
1637bb8bf76fSChristoph Hellwig 
1638f58c7b35Sths /*
1639f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
1640f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
1641f58c7b35Sths  * hence all their sectors are reported as allocated.
1642f58c7b35Sths  *
1643f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
1644f58c7b35Sths  * the specified sector) that are known to be in the same
1645f58c7b35Sths  * allocated/unallocated state.
1646f58c7b35Sths  *
1647f58c7b35Sths  * 'nb_sectors' is the max value 'pnum' should be set to.
1648f58c7b35Sths  */
1649f58c7b35Sths int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1650f58c7b35Sths 	int *pnum)
1651f58c7b35Sths {
1652f58c7b35Sths     int64_t n;
1653f58c7b35Sths     if (!bs->drv->bdrv_is_allocated) {
1654f58c7b35Sths         if (sector_num >= bs->total_sectors) {
1655f58c7b35Sths             *pnum = 0;
1656f58c7b35Sths             return 0;
1657f58c7b35Sths         }
1658f58c7b35Sths         n = bs->total_sectors - sector_num;
1659f58c7b35Sths         *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1660f58c7b35Sths         return 1;
1661f58c7b35Sths     }
1662f58c7b35Sths     return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1663f58c7b35Sths }
1664f58c7b35Sths 
16652582bfedSLuiz Capitulino void bdrv_mon_event(const BlockDriverState *bdrv,
16662582bfedSLuiz Capitulino                     BlockMonEventAction action, int is_read)
16672582bfedSLuiz Capitulino {
16682582bfedSLuiz Capitulino     QObject *data;
16692582bfedSLuiz Capitulino     const char *action_str;
16702582bfedSLuiz Capitulino 
16712582bfedSLuiz Capitulino     switch (action) {
16722582bfedSLuiz Capitulino     case BDRV_ACTION_REPORT:
16732582bfedSLuiz Capitulino         action_str = "report";
16742582bfedSLuiz Capitulino         break;
16752582bfedSLuiz Capitulino     case BDRV_ACTION_IGNORE:
16762582bfedSLuiz Capitulino         action_str = "ignore";
16772582bfedSLuiz Capitulino         break;
16782582bfedSLuiz Capitulino     case BDRV_ACTION_STOP:
16792582bfedSLuiz Capitulino         action_str = "stop";
16802582bfedSLuiz Capitulino         break;
16812582bfedSLuiz Capitulino     default:
16822582bfedSLuiz Capitulino         abort();
16832582bfedSLuiz Capitulino     }
16842582bfedSLuiz Capitulino 
16852582bfedSLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
16862582bfedSLuiz Capitulino                               bdrv->device_name,
16872582bfedSLuiz Capitulino                               action_str,
16882582bfedSLuiz Capitulino                               is_read ? "read" : "write");
16892582bfedSLuiz Capitulino     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
16902582bfedSLuiz Capitulino 
16912582bfedSLuiz Capitulino     qobject_decref(data);
16922582bfedSLuiz Capitulino }
16932582bfedSLuiz Capitulino 
1694d15e5465SLuiz Capitulino static void bdrv_print_dict(QObject *obj, void *opaque)
1695b338082bSbellard {
1696d15e5465SLuiz Capitulino     QDict *bs_dict;
1697d15e5465SLuiz Capitulino     Monitor *mon = opaque;
1698b338082bSbellard 
1699d15e5465SLuiz Capitulino     bs_dict = qobject_to_qdict(obj);
1700d15e5465SLuiz Capitulino 
1701d15e5465SLuiz Capitulino     monitor_printf(mon, "%s: type=%s removable=%d",
1702d15e5465SLuiz Capitulino                         qdict_get_str(bs_dict, "device"),
1703d15e5465SLuiz Capitulino                         qdict_get_str(bs_dict, "type"),
1704d15e5465SLuiz Capitulino                         qdict_get_bool(bs_dict, "removable"));
1705d15e5465SLuiz Capitulino 
1706d15e5465SLuiz Capitulino     if (qdict_get_bool(bs_dict, "removable")) {
1707d15e5465SLuiz Capitulino         monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1708b338082bSbellard     }
1709d15e5465SLuiz Capitulino 
1710d15e5465SLuiz Capitulino     if (qdict_haskey(bs_dict, "inserted")) {
1711d15e5465SLuiz Capitulino         QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1712d15e5465SLuiz Capitulino 
1713376253ecSaliguori         monitor_printf(mon, " file=");
1714d15e5465SLuiz Capitulino         monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1715d15e5465SLuiz Capitulino         if (qdict_haskey(qdict, "backing_file")) {
1716376253ecSaliguori             monitor_printf(mon, " backing_file=");
1717d15e5465SLuiz Capitulino             monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1718fef30743Sths         }
1719d15e5465SLuiz Capitulino         monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1720d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "ro"),
1721d15e5465SLuiz Capitulino                             qdict_get_str(qdict, "drv"),
1722d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "encrypted"));
1723b338082bSbellard     } else {
1724376253ecSaliguori         monitor_printf(mon, " [not inserted]");
1725b338082bSbellard     }
1726d15e5465SLuiz Capitulino 
1727376253ecSaliguori     monitor_printf(mon, "\n");
1728b338082bSbellard }
1729d15e5465SLuiz Capitulino 
1730d15e5465SLuiz Capitulino void bdrv_info_print(Monitor *mon, const QObject *data)
1731d15e5465SLuiz Capitulino {
1732d15e5465SLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1733d15e5465SLuiz Capitulino }
1734d15e5465SLuiz Capitulino 
1735d15e5465SLuiz Capitulino void bdrv_info(Monitor *mon, QObject **ret_data)
1736d15e5465SLuiz Capitulino {
1737d15e5465SLuiz Capitulino     QList *bs_list;
1738d15e5465SLuiz Capitulino     BlockDriverState *bs;
1739d15e5465SLuiz Capitulino 
1740d15e5465SLuiz Capitulino     bs_list = qlist_new();
1741d15e5465SLuiz Capitulino 
17421b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1743d15e5465SLuiz Capitulino         QObject *bs_obj;
1744d15e5465SLuiz Capitulino         const char *type = "unknown";
1745d15e5465SLuiz Capitulino 
1746d15e5465SLuiz Capitulino         switch(bs->type) {
1747d15e5465SLuiz Capitulino         case BDRV_TYPE_HD:
1748d15e5465SLuiz Capitulino             type = "hd";
1749d15e5465SLuiz Capitulino             break;
1750d15e5465SLuiz Capitulino         case BDRV_TYPE_CDROM:
1751d15e5465SLuiz Capitulino             type = "cdrom";
1752d15e5465SLuiz Capitulino             break;
1753d15e5465SLuiz Capitulino         case BDRV_TYPE_FLOPPY:
1754d15e5465SLuiz Capitulino             type = "floppy";
1755d15e5465SLuiz Capitulino             break;
1756d15e5465SLuiz Capitulino         }
1757d15e5465SLuiz Capitulino 
1758d15e5465SLuiz Capitulino         bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1759d15e5465SLuiz Capitulino                                     "'removable': %i, 'locked': %i }",
1760d15e5465SLuiz Capitulino                                     bs->device_name, type, bs->removable,
1761d15e5465SLuiz Capitulino                                     bs->locked);
1762d15e5465SLuiz Capitulino 
1763d15e5465SLuiz Capitulino         if (bs->drv) {
1764d15e5465SLuiz Capitulino             QObject *obj;
1765d15e5465SLuiz Capitulino             QDict *bs_dict = qobject_to_qdict(bs_obj);
1766d15e5465SLuiz Capitulino 
1767d15e5465SLuiz Capitulino             obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1768d15e5465SLuiz Capitulino                                      "'encrypted': %i }",
1769d15e5465SLuiz Capitulino                                      bs->filename, bs->read_only,
1770d15e5465SLuiz Capitulino                                      bs->drv->format_name,
1771d15e5465SLuiz Capitulino                                      bdrv_is_encrypted(bs));
1772d15e5465SLuiz Capitulino             if (bs->backing_file[0] != '\0') {
1773d15e5465SLuiz Capitulino                 QDict *qdict = qobject_to_qdict(obj);
1774d15e5465SLuiz Capitulino                 qdict_put(qdict, "backing_file",
1775d15e5465SLuiz Capitulino                           qstring_from_str(bs->backing_file));
1776d15e5465SLuiz Capitulino             }
1777d15e5465SLuiz Capitulino 
1778d15e5465SLuiz Capitulino             qdict_put_obj(bs_dict, "inserted", obj);
1779d15e5465SLuiz Capitulino         }
1780d15e5465SLuiz Capitulino         qlist_append_obj(bs_list, bs_obj);
1781d15e5465SLuiz Capitulino     }
1782d15e5465SLuiz Capitulino 
1783d15e5465SLuiz Capitulino     *ret_data = QOBJECT(bs_list);
1784b338082bSbellard }
1785a36e69ddSths 
1786218a536aSLuiz Capitulino static void bdrv_stats_iter(QObject *data, void *opaque)
1787a36e69ddSths {
1788218a536aSLuiz Capitulino     QDict *qdict;
1789218a536aSLuiz Capitulino     Monitor *mon = opaque;
1790218a536aSLuiz Capitulino 
1791218a536aSLuiz Capitulino     qdict = qobject_to_qdict(data);
1792218a536aSLuiz Capitulino     monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1793218a536aSLuiz Capitulino 
1794218a536aSLuiz Capitulino     qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1795218a536aSLuiz Capitulino     monitor_printf(mon, " rd_bytes=%" PRId64
1796218a536aSLuiz Capitulino                         " wr_bytes=%" PRId64
1797218a536aSLuiz Capitulino                         " rd_operations=%" PRId64
1798218a536aSLuiz Capitulino                         " wr_operations=%" PRId64
1799218a536aSLuiz Capitulino                         "\n",
1800218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_bytes"),
1801218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_bytes"),
1802218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_operations"),
1803218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_operations"));
1804218a536aSLuiz Capitulino }
1805218a536aSLuiz Capitulino 
1806218a536aSLuiz Capitulino void bdrv_stats_print(Monitor *mon, const QObject *data)
1807218a536aSLuiz Capitulino {
1808218a536aSLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1809218a536aSLuiz Capitulino }
1810218a536aSLuiz Capitulino 
1811294cc35fSKevin Wolf static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1812294cc35fSKevin Wolf {
1813294cc35fSKevin Wolf     QObject *res;
1814294cc35fSKevin Wolf     QDict *dict;
1815294cc35fSKevin Wolf 
1816294cc35fSKevin Wolf     res = qobject_from_jsonf("{ 'stats': {"
1817294cc35fSKevin Wolf                              "'rd_bytes': %" PRId64 ","
1818294cc35fSKevin Wolf                              "'wr_bytes': %" PRId64 ","
1819294cc35fSKevin Wolf                              "'rd_operations': %" PRId64 ","
1820294cc35fSKevin Wolf                              "'wr_operations': %" PRId64 ","
1821294cc35fSKevin Wolf                              "'wr_highest_offset': %" PRId64
1822294cc35fSKevin Wolf                              "} }",
1823294cc35fSKevin Wolf                              bs->rd_bytes, bs->wr_bytes,
1824294cc35fSKevin Wolf                              bs->rd_ops, bs->wr_ops,
18255ffbbc67SBlue Swirl                              bs->wr_highest_sector *
18265ffbbc67SBlue Swirl                              (uint64_t)BDRV_SECTOR_SIZE);
1827294cc35fSKevin Wolf     dict  = qobject_to_qdict(res);
1828294cc35fSKevin Wolf 
1829294cc35fSKevin Wolf     if (*bs->device_name) {
1830294cc35fSKevin Wolf         qdict_put(dict, "device", qstring_from_str(bs->device_name));
1831294cc35fSKevin Wolf     }
1832294cc35fSKevin Wolf 
1833294cc35fSKevin Wolf     if (bs->file) {
1834294cc35fSKevin Wolf         QObject *parent = bdrv_info_stats_bs(bs->file);
1835294cc35fSKevin Wolf         qdict_put_obj(dict, "parent", parent);
1836294cc35fSKevin Wolf     }
1837294cc35fSKevin Wolf 
1838294cc35fSKevin Wolf     return res;
1839294cc35fSKevin Wolf }
1840294cc35fSKevin Wolf 
1841218a536aSLuiz Capitulino void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1842218a536aSLuiz Capitulino {
1843218a536aSLuiz Capitulino     QObject *obj;
1844218a536aSLuiz Capitulino     QList *devices;
1845a36e69ddSths     BlockDriverState *bs;
1846a36e69ddSths 
1847218a536aSLuiz Capitulino     devices = qlist_new();
1848218a536aSLuiz Capitulino 
18491b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1850294cc35fSKevin Wolf         obj = bdrv_info_stats_bs(bs);
1851218a536aSLuiz Capitulino         qlist_append_obj(devices, obj);
1852a36e69ddSths     }
1853218a536aSLuiz Capitulino 
1854218a536aSLuiz Capitulino     *ret_data = QOBJECT(devices);
1855a36e69ddSths }
1856ea2384d3Sbellard 
1857045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1858045df330Saliguori {
1859045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
1860045df330Saliguori         return bs->backing_file;
1861045df330Saliguori     else if (bs->encrypted)
1862045df330Saliguori         return bs->filename;
1863045df330Saliguori     else
1864045df330Saliguori         return NULL;
1865045df330Saliguori }
1866045df330Saliguori 
186783f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
186883f64091Sbellard                                char *filename, int filename_size)
186983f64091Sbellard {
1870b783e409SKevin Wolf     if (!bs->backing_file) {
187183f64091Sbellard         pstrcpy(filename, filename_size, "");
187283f64091Sbellard     } else {
187383f64091Sbellard         pstrcpy(filename, filename_size, bs->backing_file);
187483f64091Sbellard     }
187583f64091Sbellard }
187683f64091Sbellard 
1877faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1878faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
1879faea38e7Sbellard {
1880faea38e7Sbellard     BlockDriver *drv = bs->drv;
1881faea38e7Sbellard     if (!drv)
188219cb3738Sbellard         return -ENOMEDIUM;
1883faea38e7Sbellard     if (!drv->bdrv_write_compressed)
1884faea38e7Sbellard         return -ENOTSUP;
1885fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
1886fbb7b4e0SKevin Wolf         return -EIO;
18877cd1e32aSlirans@il.ibm.com 
1888c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
18897cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
18907cd1e32aSlirans@il.ibm.com     }
18917cd1e32aSlirans@il.ibm.com 
1892faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1893faea38e7Sbellard }
1894faea38e7Sbellard 
1895faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1896faea38e7Sbellard {
1897faea38e7Sbellard     BlockDriver *drv = bs->drv;
1898faea38e7Sbellard     if (!drv)
189919cb3738Sbellard         return -ENOMEDIUM;
1900faea38e7Sbellard     if (!drv->bdrv_get_info)
1901faea38e7Sbellard         return -ENOTSUP;
1902faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
1903faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
1904faea38e7Sbellard }
1905faea38e7Sbellard 
190645566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
190745566e9cSChristoph Hellwig                       int64_t pos, int size)
1908178e08a5Saliguori {
1909178e08a5Saliguori     BlockDriver *drv = bs->drv;
1910178e08a5Saliguori     if (!drv)
1911178e08a5Saliguori         return -ENOMEDIUM;
19127cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
191345566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
19147cdb1f6dSMORITA Kazutaka     if (bs->file)
19157cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
19167cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1917178e08a5Saliguori }
1918178e08a5Saliguori 
191945566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
192045566e9cSChristoph Hellwig                       int64_t pos, int size)
1921178e08a5Saliguori {
1922178e08a5Saliguori     BlockDriver *drv = bs->drv;
1923178e08a5Saliguori     if (!drv)
1924178e08a5Saliguori         return -ENOMEDIUM;
19257cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
192645566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
19277cdb1f6dSMORITA Kazutaka     if (bs->file)
19287cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
19297cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1930178e08a5Saliguori }
1931178e08a5Saliguori 
19328b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
19338b9b0cc2SKevin Wolf {
19348b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
19358b9b0cc2SKevin Wolf 
19368b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
19378b9b0cc2SKevin Wolf         return;
19388b9b0cc2SKevin Wolf     }
19398b9b0cc2SKevin Wolf 
19408b9b0cc2SKevin Wolf     return drv->bdrv_debug_event(bs, event);
19418b9b0cc2SKevin Wolf 
19428b9b0cc2SKevin Wolf }
19438b9b0cc2SKevin Wolf 
1944faea38e7Sbellard /**************************************************************/
1945faea38e7Sbellard /* handling of snapshots */
1946faea38e7Sbellard 
1947feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
1948feeee5acSMiguel Di Ciurcio Filho {
1949feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
1950feeee5acSMiguel Di Ciurcio Filho     if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1951feeee5acSMiguel Di Ciurcio Filho         return 0;
1952feeee5acSMiguel Di Ciurcio Filho     }
1953feeee5acSMiguel Di Ciurcio Filho 
1954feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
1955feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
1956feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
1957feeee5acSMiguel Di Ciurcio Filho         }
1958feeee5acSMiguel Di Ciurcio Filho         return 0;
1959feeee5acSMiguel Di Ciurcio Filho     }
1960feeee5acSMiguel Di Ciurcio Filho 
1961feeee5acSMiguel Di Ciurcio Filho     return 1;
1962feeee5acSMiguel Di Ciurcio Filho }
1963feeee5acSMiguel Di Ciurcio Filho 
1964199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
1965199630b6SBlue Swirl {
1966199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
1967199630b6SBlue Swirl }
1968199630b6SBlue Swirl 
1969f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
1970f9092b10SMarkus Armbruster {
1971f9092b10SMarkus Armbruster     BlockDriverState *bs;
1972f9092b10SMarkus Armbruster 
19733ac906f7SMarkus Armbruster     if (bs_snapshots) {
1974f9092b10SMarkus Armbruster         return bs_snapshots;
19753ac906f7SMarkus Armbruster     }
1976f9092b10SMarkus Armbruster 
1977f9092b10SMarkus Armbruster     bs = NULL;
1978f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
1979f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
19803ac906f7SMarkus Armbruster             bs_snapshots = bs;
19813ac906f7SMarkus Armbruster             return bs;
1982f9092b10SMarkus Armbruster         }
1983f9092b10SMarkus Armbruster     }
1984f9092b10SMarkus Armbruster     return NULL;
1985f9092b10SMarkus Armbruster }
1986f9092b10SMarkus Armbruster 
1987faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
1988faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
1989faea38e7Sbellard {
1990faea38e7Sbellard     BlockDriver *drv = bs->drv;
1991faea38e7Sbellard     if (!drv)
199219cb3738Sbellard         return -ENOMEDIUM;
19937cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
1994faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
19957cdb1f6dSMORITA Kazutaka     if (bs->file)
19967cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
19977cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1998faea38e7Sbellard }
1999faea38e7Sbellard 
2000faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
2001faea38e7Sbellard                        const char *snapshot_id)
2002faea38e7Sbellard {
2003faea38e7Sbellard     BlockDriver *drv = bs->drv;
20047cdb1f6dSMORITA Kazutaka     int ret, open_ret;
20057cdb1f6dSMORITA Kazutaka 
2006faea38e7Sbellard     if (!drv)
200719cb3738Sbellard         return -ENOMEDIUM;
20087cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
2009faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
20107cdb1f6dSMORITA Kazutaka 
20117cdb1f6dSMORITA Kazutaka     if (bs->file) {
20127cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
20137cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
20147cdb1f6dSMORITA Kazutaka         open_ret = drv->bdrv_open(bs, bs->open_flags);
20157cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
20167cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
20177cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
20187cdb1f6dSMORITA Kazutaka             return open_ret;
20197cdb1f6dSMORITA Kazutaka         }
20207cdb1f6dSMORITA Kazutaka         return ret;
20217cdb1f6dSMORITA Kazutaka     }
20227cdb1f6dSMORITA Kazutaka 
20237cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2024faea38e7Sbellard }
2025faea38e7Sbellard 
2026faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2027faea38e7Sbellard {
2028faea38e7Sbellard     BlockDriver *drv = bs->drv;
2029faea38e7Sbellard     if (!drv)
203019cb3738Sbellard         return -ENOMEDIUM;
20317cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
2032faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
20337cdb1f6dSMORITA Kazutaka     if (bs->file)
20347cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
20357cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2036faea38e7Sbellard }
2037faea38e7Sbellard 
2038faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
2039faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
2040faea38e7Sbellard {
2041faea38e7Sbellard     BlockDriver *drv = bs->drv;
2042faea38e7Sbellard     if (!drv)
204319cb3738Sbellard         return -ENOMEDIUM;
20447cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
2045faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
20467cdb1f6dSMORITA Kazutaka     if (bs->file)
20477cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
20487cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2049faea38e7Sbellard }
2050faea38e7Sbellard 
205151ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
205251ef6727Sedison         const char *snapshot_name)
205351ef6727Sedison {
205451ef6727Sedison     BlockDriver *drv = bs->drv;
205551ef6727Sedison     if (!drv) {
205651ef6727Sedison         return -ENOMEDIUM;
205751ef6727Sedison     }
205851ef6727Sedison     if (!bs->read_only) {
205951ef6727Sedison         return -EINVAL;
206051ef6727Sedison     }
206151ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
206251ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
206351ef6727Sedison     }
206451ef6727Sedison     return -ENOTSUP;
206551ef6727Sedison }
206651ef6727Sedison 
2067faea38e7Sbellard #define NB_SUFFIXES 4
2068faea38e7Sbellard 
2069faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2070faea38e7Sbellard {
2071faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
2072faea38e7Sbellard     int64_t base;
2073faea38e7Sbellard     int i;
2074faea38e7Sbellard 
2075faea38e7Sbellard     if (size <= 999) {
2076faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
2077faea38e7Sbellard     } else {
2078faea38e7Sbellard         base = 1024;
2079faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
2080faea38e7Sbellard             if (size < (10 * base)) {
2081faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
2082faea38e7Sbellard                          (double)size / base,
2083faea38e7Sbellard                          suffixes[i]);
2084faea38e7Sbellard                 break;
2085faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2086faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
2087faea38e7Sbellard                          ((size + (base >> 1)) / base),
2088faea38e7Sbellard                          suffixes[i]);
2089faea38e7Sbellard                 break;
2090faea38e7Sbellard             }
2091faea38e7Sbellard             base = base * 1024;
2092faea38e7Sbellard         }
2093faea38e7Sbellard     }
2094faea38e7Sbellard     return buf;
2095faea38e7Sbellard }
2096faea38e7Sbellard 
2097faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2098faea38e7Sbellard {
2099faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
21003b9f94e1Sbellard #ifdef _WIN32
21013b9f94e1Sbellard     struct tm *ptm;
21023b9f94e1Sbellard #else
2103faea38e7Sbellard     struct tm tm;
21043b9f94e1Sbellard #endif
2105faea38e7Sbellard     time_t ti;
2106faea38e7Sbellard     int64_t secs;
2107faea38e7Sbellard 
2108faea38e7Sbellard     if (!sn) {
2109faea38e7Sbellard         snprintf(buf, buf_size,
2110faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2111faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2112faea38e7Sbellard     } else {
2113faea38e7Sbellard         ti = sn->date_sec;
21143b9f94e1Sbellard #ifdef _WIN32
21153b9f94e1Sbellard         ptm = localtime(&ti);
21163b9f94e1Sbellard         strftime(date_buf, sizeof(date_buf),
21173b9f94e1Sbellard                  "%Y-%m-%d %H:%M:%S", ptm);
21183b9f94e1Sbellard #else
2119faea38e7Sbellard         localtime_r(&ti, &tm);
2120faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
2121faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
21223b9f94e1Sbellard #endif
2123faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
2124faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
2125faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
2126faea38e7Sbellard                  (int)(secs / 3600),
2127faea38e7Sbellard                  (int)((secs / 60) % 60),
2128faea38e7Sbellard                  (int)(secs % 60),
2129faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
2130faea38e7Sbellard         snprintf(buf, buf_size,
2131faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2132faea38e7Sbellard                  sn->id_str, sn->name,
2133faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2134faea38e7Sbellard                  date_buf,
2135faea38e7Sbellard                  clock_buf);
2136faea38e7Sbellard     }
2137faea38e7Sbellard     return buf;
2138faea38e7Sbellard }
2139faea38e7Sbellard 
214083f64091Sbellard 
2141ea2384d3Sbellard /**************************************************************/
214283f64091Sbellard /* async I/Os */
2143ea2384d3Sbellard 
21443b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2145f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
214683f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
2147ea2384d3Sbellard {
214883f64091Sbellard     BlockDriver *drv = bs->drv;
2149a36e69ddSths     BlockDriverAIOCB *ret;
2150ea2384d3Sbellard 
2151bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2152bbf0a440SStefan Hajnoczi 
215319cb3738Sbellard     if (!drv)
2154ce1a14dcSpbrook         return NULL;
215571d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
215671d0770cSaliguori         return NULL;
215783f64091Sbellard 
2158f141eafeSaliguori     ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2159f141eafeSaliguori                               cb, opaque);
2160a36e69ddSths 
2161a36e69ddSths     if (ret) {
2162a36e69ddSths 	/* Update stats even though technically transfer has not happened. */
21636ea44308SJan Kiszka 	bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2164a36e69ddSths 	bs->rd_ops ++;
2165a36e69ddSths     }
2166a36e69ddSths 
2167a36e69ddSths     return ret;
216883f64091Sbellard }
216983f64091Sbellard 
21704dcafbb1SMarcelo Tosatti typedef struct BlockCompleteData {
21714dcafbb1SMarcelo Tosatti     BlockDriverCompletionFunc *cb;
21724dcafbb1SMarcelo Tosatti     void *opaque;
21734dcafbb1SMarcelo Tosatti     BlockDriverState *bs;
21744dcafbb1SMarcelo Tosatti     int64_t sector_num;
21754dcafbb1SMarcelo Tosatti     int nb_sectors;
21764dcafbb1SMarcelo Tosatti } BlockCompleteData;
21774dcafbb1SMarcelo Tosatti 
21784dcafbb1SMarcelo Tosatti static void block_complete_cb(void *opaque, int ret)
21794dcafbb1SMarcelo Tosatti {
21804dcafbb1SMarcelo Tosatti     BlockCompleteData *b = opaque;
21814dcafbb1SMarcelo Tosatti 
21824dcafbb1SMarcelo Tosatti     if (b->bs->dirty_bitmap) {
21834dcafbb1SMarcelo Tosatti         set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
21844dcafbb1SMarcelo Tosatti     }
21854dcafbb1SMarcelo Tosatti     b->cb(b->opaque, ret);
21864dcafbb1SMarcelo Tosatti     qemu_free(b);
21874dcafbb1SMarcelo Tosatti }
21884dcafbb1SMarcelo Tosatti 
21894dcafbb1SMarcelo Tosatti static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
21904dcafbb1SMarcelo Tosatti                                              int64_t sector_num,
21914dcafbb1SMarcelo Tosatti                                              int nb_sectors,
21924dcafbb1SMarcelo Tosatti                                              BlockDriverCompletionFunc *cb,
21934dcafbb1SMarcelo Tosatti                                              void *opaque)
21944dcafbb1SMarcelo Tosatti {
21954dcafbb1SMarcelo Tosatti     BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
21964dcafbb1SMarcelo Tosatti 
21974dcafbb1SMarcelo Tosatti     blkdata->bs = bs;
21984dcafbb1SMarcelo Tosatti     blkdata->cb = cb;
21994dcafbb1SMarcelo Tosatti     blkdata->opaque = opaque;
22004dcafbb1SMarcelo Tosatti     blkdata->sector_num = sector_num;
22014dcafbb1SMarcelo Tosatti     blkdata->nb_sectors = nb_sectors;
22024dcafbb1SMarcelo Tosatti 
22034dcafbb1SMarcelo Tosatti     return blkdata;
22044dcafbb1SMarcelo Tosatti }
22054dcafbb1SMarcelo Tosatti 
2206f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2207f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
220883f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
22097674e7bfSbellard {
221083f64091Sbellard     BlockDriver *drv = bs->drv;
2211a36e69ddSths     BlockDriverAIOCB *ret;
22124dcafbb1SMarcelo Tosatti     BlockCompleteData *blk_cb_data;
221383f64091Sbellard 
2214bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2215bbf0a440SStefan Hajnoczi 
221619cb3738Sbellard     if (!drv)
2217ce1a14dcSpbrook         return NULL;
221883f64091Sbellard     if (bs->read_only)
2219ce1a14dcSpbrook         return NULL;
222071d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
222171d0770cSaliguori         return NULL;
222283f64091Sbellard 
2223c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
22244dcafbb1SMarcelo Tosatti         blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
22254dcafbb1SMarcelo Tosatti                                          opaque);
22264dcafbb1SMarcelo Tosatti         cb = &block_complete_cb;
22274dcafbb1SMarcelo Tosatti         opaque = blk_cb_data;
22287cd1e32aSlirans@il.ibm.com     }
22297cd1e32aSlirans@il.ibm.com 
2230f141eafeSaliguori     ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2231f141eafeSaliguori                                cb, opaque);
2232a36e69ddSths 
2233a36e69ddSths     if (ret) {
2234a36e69ddSths         /* Update stats even though technically transfer has not happened. */
22356ea44308SJan Kiszka         bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2236a36e69ddSths         bs->wr_ops ++;
2237294cc35fSKevin Wolf         if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2238294cc35fSKevin Wolf             bs->wr_highest_sector = sector_num + nb_sectors - 1;
2239294cc35fSKevin Wolf         }
2240a36e69ddSths     }
2241a36e69ddSths 
2242a36e69ddSths     return ret;
224383f64091Sbellard }
224483f64091Sbellard 
224540b4f539SKevin Wolf 
224640b4f539SKevin Wolf typedef struct MultiwriteCB {
224740b4f539SKevin Wolf     int error;
224840b4f539SKevin Wolf     int num_requests;
224940b4f539SKevin Wolf     int num_callbacks;
225040b4f539SKevin Wolf     struct {
225140b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
225240b4f539SKevin Wolf         void *opaque;
225340b4f539SKevin Wolf         QEMUIOVector *free_qiov;
225440b4f539SKevin Wolf         void *free_buf;
225540b4f539SKevin Wolf     } callbacks[];
225640b4f539SKevin Wolf } MultiwriteCB;
225740b4f539SKevin Wolf 
225840b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
225940b4f539SKevin Wolf {
226040b4f539SKevin Wolf     int i;
226140b4f539SKevin Wolf 
226240b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
226340b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
22641e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
22651e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
22661e1ea48dSStefan Hajnoczi         }
226740b4f539SKevin Wolf         qemu_free(mcb->callbacks[i].free_qiov);
2268f8a83245SHerve Poussineau         qemu_vfree(mcb->callbacks[i].free_buf);
226940b4f539SKevin Wolf     }
227040b4f539SKevin Wolf }
227140b4f539SKevin Wolf 
227240b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
227340b4f539SKevin Wolf {
227440b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
227540b4f539SKevin Wolf 
22766d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
22776d519a5fSStefan Hajnoczi 
2278cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
227940b4f539SKevin Wolf         mcb->error = ret;
228040b4f539SKevin Wolf     }
228140b4f539SKevin Wolf 
228240b4f539SKevin Wolf     mcb->num_requests--;
228340b4f539SKevin Wolf     if (mcb->num_requests == 0) {
228440b4f539SKevin Wolf         multiwrite_user_cb(mcb);
228540b4f539SKevin Wolf         qemu_free(mcb);
228640b4f539SKevin Wolf     }
228740b4f539SKevin Wolf }
228840b4f539SKevin Wolf 
228940b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
229040b4f539SKevin Wolf {
229177be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
229277be4366SChristoph Hellwig 
229377be4366SChristoph Hellwig     /*
229477be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
229577be4366SChristoph Hellwig      * here as that could overflow the return value.
229677be4366SChristoph Hellwig      */
229777be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
229877be4366SChristoph Hellwig         return 1;
229977be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
230077be4366SChristoph Hellwig         return -1;
230177be4366SChristoph Hellwig     } else {
230277be4366SChristoph Hellwig         return 0;
230377be4366SChristoph Hellwig     }
230440b4f539SKevin Wolf }
230540b4f539SKevin Wolf 
230640b4f539SKevin Wolf /*
230740b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
230840b4f539SKevin Wolf  * requests that remain after merging.
230940b4f539SKevin Wolf  */
231040b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
231140b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
231240b4f539SKevin Wolf {
231340b4f539SKevin Wolf     int i, outidx;
231440b4f539SKevin Wolf 
231540b4f539SKevin Wolf     // Sort requests by start sector
231640b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
231740b4f539SKevin Wolf 
231840b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
231940b4f539SKevin Wolf     // filling up gaps with zero sectors.
232040b4f539SKevin Wolf     outidx = 0;
232140b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
232240b4f539SKevin Wolf         int merge = 0;
232340b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
232440b4f539SKevin Wolf 
232540b4f539SKevin Wolf         // This handles the cases that are valid for all block drivers, namely
232640b4f539SKevin Wolf         // exactly sequential writes and overlapping writes.
232740b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
232840b4f539SKevin Wolf             merge = 1;
232940b4f539SKevin Wolf         }
233040b4f539SKevin Wolf 
233140b4f539SKevin Wolf         // The block driver may decide that it makes sense to combine requests
233240b4f539SKevin Wolf         // even if there is a gap of some sectors between them. In this case,
233340b4f539SKevin Wolf         // the gap is filled with zeros (therefore only applicable for yet
233440b4f539SKevin Wolf         // unused space in format like qcow2).
233540b4f539SKevin Wolf         if (!merge && bs->drv->bdrv_merge_requests) {
233640b4f539SKevin Wolf             merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
233740b4f539SKevin Wolf         }
233840b4f539SKevin Wolf 
2339e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2340e2a305fbSChristoph Hellwig             merge = 0;
2341e2a305fbSChristoph Hellwig         }
2342e2a305fbSChristoph Hellwig 
234340b4f539SKevin Wolf         if (merge) {
234440b4f539SKevin Wolf             size_t size;
234540b4f539SKevin Wolf             QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
234640b4f539SKevin Wolf             qemu_iovec_init(qiov,
234740b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
234840b4f539SKevin Wolf 
234940b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
235040b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
235140b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
235240b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
235340b4f539SKevin Wolf 
235440b4f539SKevin Wolf             // We might need to add some zeros between the two requests
235540b4f539SKevin Wolf             if (reqs[i].sector > oldreq_last) {
235640b4f539SKevin Wolf                 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
235740b4f539SKevin Wolf                 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
235840b4f539SKevin Wolf                 memset(buf, 0, zero_bytes);
235940b4f539SKevin Wolf                 qemu_iovec_add(qiov, buf, zero_bytes);
236040b4f539SKevin Wolf                 mcb->callbacks[i].free_buf = buf;
236140b4f539SKevin Wolf             }
236240b4f539SKevin Wolf 
236340b4f539SKevin Wolf             // Add the second request
236440b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
236540b4f539SKevin Wolf 
2366cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
236740b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
236840b4f539SKevin Wolf 
236940b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
237040b4f539SKevin Wolf         } else {
237140b4f539SKevin Wolf             outidx++;
237240b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
237340b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
237440b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
237540b4f539SKevin Wolf         }
237640b4f539SKevin Wolf     }
237740b4f539SKevin Wolf 
237840b4f539SKevin Wolf     return outidx + 1;
237940b4f539SKevin Wolf }
238040b4f539SKevin Wolf 
238140b4f539SKevin Wolf /*
238240b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
238340b4f539SKevin Wolf  *
238440b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
238540b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
238640b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
238740b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
238840b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
238940b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
239040b4f539SKevin Wolf  *
239140b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
239240b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
239340b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
239440b4f539SKevin Wolf  */
239540b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
239640b4f539SKevin Wolf {
239740b4f539SKevin Wolf     BlockDriverAIOCB *acb;
239840b4f539SKevin Wolf     MultiwriteCB *mcb;
239940b4f539SKevin Wolf     int i;
240040b4f539SKevin Wolf 
240140b4f539SKevin Wolf     if (num_reqs == 0) {
240240b4f539SKevin Wolf         return 0;
240340b4f539SKevin Wolf     }
240440b4f539SKevin Wolf 
240540b4f539SKevin Wolf     // Create MultiwriteCB structure
240640b4f539SKevin Wolf     mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
240740b4f539SKevin Wolf     mcb->num_requests = 0;
240840b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
240940b4f539SKevin Wolf 
241040b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
241140b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
241240b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
241340b4f539SKevin Wolf     }
241440b4f539SKevin Wolf 
241540b4f539SKevin Wolf     // Check for mergable requests
241640b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
241740b4f539SKevin Wolf 
24186d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
24196d519a5fSStefan Hajnoczi 
2420453f9a16SKevin Wolf     /*
2421453f9a16SKevin Wolf      * Run the aio requests. As soon as one request can't be submitted
2422453f9a16SKevin Wolf      * successfully, fail all requests that are not yet submitted (we must
2423453f9a16SKevin Wolf      * return failure for all requests anyway)
2424453f9a16SKevin Wolf      *
2425453f9a16SKevin Wolf      * num_requests cannot be set to the right value immediately: If
2426453f9a16SKevin Wolf      * bdrv_aio_writev fails for some request, num_requests would be too high
2427453f9a16SKevin Wolf      * and therefore multiwrite_cb() would never recognize the multiwrite
2428453f9a16SKevin Wolf      * request as completed. We also cannot use the loop variable i to set it
2429453f9a16SKevin Wolf      * when the first request fails because the callback may already have been
2430453f9a16SKevin Wolf      * called for previously submitted requests. Thus, num_requests must be
2431453f9a16SKevin Wolf      * incremented for each request that is submitted.
2432453f9a16SKevin Wolf      *
2433453f9a16SKevin Wolf      * The problem that callbacks may be called early also means that we need
2434453f9a16SKevin Wolf      * to take care that num_requests doesn't become 0 before all requests are
2435453f9a16SKevin Wolf      * submitted - multiwrite_cb() would consider the multiwrite request
2436453f9a16SKevin Wolf      * completed. A dummy request that is "completed" by a manual call to
2437453f9a16SKevin Wolf      * multiwrite_cb() takes care of this.
2438453f9a16SKevin Wolf      */
2439453f9a16SKevin Wolf     mcb->num_requests = 1;
2440453f9a16SKevin Wolf 
24416d519a5fSStefan Hajnoczi     // Run the aio requests
244240b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
2443453f9a16SKevin Wolf         mcb->num_requests++;
244440b4f539SKevin Wolf         acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
244540b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
244640b4f539SKevin Wolf 
244740b4f539SKevin Wolf         if (acb == NULL) {
244840b4f539SKevin Wolf             // We can only fail the whole thing if no request has been
244940b4f539SKevin Wolf             // submitted yet. Otherwise we'll wait for the submitted AIOs to
245040b4f539SKevin Wolf             // complete and report the error in the callback.
2451453f9a16SKevin Wolf             if (i == 0) {
24526d519a5fSStefan Hajnoczi                 trace_bdrv_aio_multiwrite_earlyfail(mcb);
245340b4f539SKevin Wolf                 goto fail;
245440b4f539SKevin Wolf             } else {
24556d519a5fSStefan Hajnoczi                 trace_bdrv_aio_multiwrite_latefail(mcb, i);
24567eb58a6cSKevin Wolf                 multiwrite_cb(mcb, -EIO);
245740b4f539SKevin Wolf                 break;
245840b4f539SKevin Wolf             }
245940b4f539SKevin Wolf         }
246040b4f539SKevin Wolf     }
246140b4f539SKevin Wolf 
2462453f9a16SKevin Wolf     /* Complete the dummy request */
2463453f9a16SKevin Wolf     multiwrite_cb(mcb, 0);
2464453f9a16SKevin Wolf 
246540b4f539SKevin Wolf     return 0;
246640b4f539SKevin Wolf 
246740b4f539SKevin Wolf fail:
2468453f9a16SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
2469453f9a16SKevin Wolf         reqs[i].error = -EIO;
2470453f9a16SKevin Wolf     }
2471af474591SBruce Rogers     qemu_free(mcb);
247240b4f539SKevin Wolf     return -1;
247340b4f539SKevin Wolf }
247440b4f539SKevin Wolf 
2475b2e12bc6SChristoph Hellwig BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2476b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2477b2e12bc6SChristoph Hellwig {
2478b2e12bc6SChristoph Hellwig     BlockDriver *drv = bs->drv;
2479b2e12bc6SChristoph Hellwig 
2480*a13aac04SStefan Hajnoczi     trace_bdrv_aio_flush(bs, opaque);
2481*a13aac04SStefan Hajnoczi 
2482016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2483016f5cf6SAlexander Graf         return bdrv_aio_noop_em(bs, cb, opaque);
2484016f5cf6SAlexander Graf     }
2485016f5cf6SAlexander Graf 
2486b2e12bc6SChristoph Hellwig     if (!drv)
2487b2e12bc6SChristoph Hellwig         return NULL;
2488b2e12bc6SChristoph Hellwig     return drv->bdrv_aio_flush(bs, cb, opaque);
2489b2e12bc6SChristoph Hellwig }
2490b2e12bc6SChristoph Hellwig 
249183f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
249283f64091Sbellard {
24936bbff9a0Saliguori     acb->pool->cancel(acb);
249483f64091Sbellard }
249583f64091Sbellard 
249683f64091Sbellard 
249783f64091Sbellard /**************************************************************/
249883f64091Sbellard /* async block device emulation */
249983f64091Sbellard 
2500c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
2501c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
2502c16b5a2cSChristoph Hellwig     QEMUBH *bh;
2503c16b5a2cSChristoph Hellwig     int ret;
2504c16b5a2cSChristoph Hellwig     /* vector translation state */
2505c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
2506c16b5a2cSChristoph Hellwig     uint8_t *bounce;
2507c16b5a2cSChristoph Hellwig     int is_write;
2508c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
2509c16b5a2cSChristoph Hellwig 
2510c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2511c16b5a2cSChristoph Hellwig {
2512b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
2513b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
25146a7ad299SDor Laor     qemu_bh_delete(acb->bh);
251536afc451SAvi Kivity     acb->bh = NULL;
2516c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
2517c16b5a2cSChristoph Hellwig }
2518c16b5a2cSChristoph Hellwig 
2519c16b5a2cSChristoph Hellwig static AIOPool bdrv_em_aio_pool = {
2520c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2521c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
2522c16b5a2cSChristoph Hellwig };
2523c16b5a2cSChristoph Hellwig 
252483f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
2525beac80cdSbellard {
2526ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
2527f141eafeSaliguori 
2528f141eafeSaliguori     if (!acb->is_write)
2529f141eafeSaliguori         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2530ceb42de8Saliguori     qemu_vfree(acb->bounce);
2531ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
25326a7ad299SDor Laor     qemu_bh_delete(acb->bh);
253336afc451SAvi Kivity     acb->bh = NULL;
2534ce1a14dcSpbrook     qemu_aio_release(acb);
2535beac80cdSbellard }
2536beac80cdSbellard 
2537f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2538f141eafeSaliguori                                             int64_t sector_num,
2539f141eafeSaliguori                                             QEMUIOVector *qiov,
2540f141eafeSaliguori                                             int nb_sectors,
2541f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
2542f141eafeSaliguori                                             void *opaque,
2543f141eafeSaliguori                                             int is_write)
2544f141eafeSaliguori 
2545ea2384d3Sbellard {
2546ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
254783f64091Sbellard 
2548c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2549f141eafeSaliguori     acb->is_write = is_write;
2550f141eafeSaliguori     acb->qiov = qiov;
2551e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
2552f141eafeSaliguori 
2553ce1a14dcSpbrook     if (!acb->bh)
2554ce1a14dcSpbrook         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2555f141eafeSaliguori 
2556f141eafeSaliguori     if (is_write) {
2557f141eafeSaliguori         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2558f141eafeSaliguori         acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2559f141eafeSaliguori     } else {
2560f141eafeSaliguori         acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2561f141eafeSaliguori     }
2562f141eafeSaliguori 
2563ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
2564f141eafeSaliguori 
2565ce1a14dcSpbrook     return &acb->common;
25667a6cba61Spbrook }
25677a6cba61Spbrook 
2568f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2569f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2570ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
257183f64091Sbellard {
2572f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
257383f64091Sbellard }
257483f64091Sbellard 
2575f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2576f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2577f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
2578f141eafeSaliguori {
2579f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2580f141eafeSaliguori }
2581f141eafeSaliguori 
2582b2e12bc6SChristoph Hellwig static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2583b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2584b2e12bc6SChristoph Hellwig {
2585b2e12bc6SChristoph Hellwig     BlockDriverAIOCBSync *acb;
2586b2e12bc6SChristoph Hellwig 
2587b2e12bc6SChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2588b2e12bc6SChristoph Hellwig     acb->is_write = 1; /* don't bounce in the completion hadler */
2589b2e12bc6SChristoph Hellwig     acb->qiov = NULL;
2590b2e12bc6SChristoph Hellwig     acb->bounce = NULL;
2591b2e12bc6SChristoph Hellwig     acb->ret = 0;
2592b2e12bc6SChristoph Hellwig 
2593b2e12bc6SChristoph Hellwig     if (!acb->bh)
2594b2e12bc6SChristoph Hellwig         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2595b2e12bc6SChristoph Hellwig 
2596b2e12bc6SChristoph Hellwig     bdrv_flush(bs);
2597b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
2598b2e12bc6SChristoph Hellwig     return &acb->common;
2599b2e12bc6SChristoph Hellwig }
2600b2e12bc6SChristoph Hellwig 
2601016f5cf6SAlexander Graf static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2602016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
2603016f5cf6SAlexander Graf {
2604016f5cf6SAlexander Graf     BlockDriverAIOCBSync *acb;
2605016f5cf6SAlexander Graf 
2606016f5cf6SAlexander Graf     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2607016f5cf6SAlexander Graf     acb->is_write = 1; /* don't bounce in the completion handler */
2608016f5cf6SAlexander Graf     acb->qiov = NULL;
2609016f5cf6SAlexander Graf     acb->bounce = NULL;
2610016f5cf6SAlexander Graf     acb->ret = 0;
2611016f5cf6SAlexander Graf 
2612016f5cf6SAlexander Graf     if (!acb->bh) {
2613016f5cf6SAlexander Graf         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2614016f5cf6SAlexander Graf     }
2615016f5cf6SAlexander Graf 
2616016f5cf6SAlexander Graf     qemu_bh_schedule(acb->bh);
2617016f5cf6SAlexander Graf     return &acb->common;
2618016f5cf6SAlexander Graf }
2619016f5cf6SAlexander Graf 
262083f64091Sbellard /**************************************************************/
262183f64091Sbellard /* sync block device emulation */
262283f64091Sbellard 
262383f64091Sbellard static void bdrv_rw_em_cb(void *opaque, int ret)
262483f64091Sbellard {
262583f64091Sbellard     *(int *)opaque = ret;
262683f64091Sbellard }
262783f64091Sbellard 
262883f64091Sbellard #define NOT_DONE 0x7fffffff
262983f64091Sbellard 
263083f64091Sbellard static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
263183f64091Sbellard                         uint8_t *buf, int nb_sectors)
263283f64091Sbellard {
2633ce1a14dcSpbrook     int async_ret;
2634ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2635f141eafeSaliguori     struct iovec iov;
2636f141eafeSaliguori     QEMUIOVector qiov;
263783f64091Sbellard 
263865d6b3d8SKevin Wolf     async_context_push();
263965d6b3d8SKevin Wolf 
264083f64091Sbellard     async_ret = NOT_DONE;
26413f4cb3d3Sblueswir1     iov.iov_base = (void *)buf;
2642eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2643f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2644f141eafeSaliguori     acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
264583f64091Sbellard         bdrv_rw_em_cb, &async_ret);
264665d6b3d8SKevin Wolf     if (acb == NULL) {
264765d6b3d8SKevin Wolf         async_ret = -1;
264865d6b3d8SKevin Wolf         goto fail;
264965d6b3d8SKevin Wolf     }
2650baf35cb9Saliguori 
265183f64091Sbellard     while (async_ret == NOT_DONE) {
265283f64091Sbellard         qemu_aio_wait();
265383f64091Sbellard     }
2654baf35cb9Saliguori 
265565d6b3d8SKevin Wolf 
265665d6b3d8SKevin Wolf fail:
265765d6b3d8SKevin Wolf     async_context_pop();
265883f64091Sbellard     return async_ret;
265983f64091Sbellard }
266083f64091Sbellard 
266183f64091Sbellard static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
266283f64091Sbellard                          const uint8_t *buf, int nb_sectors)
266383f64091Sbellard {
2664ce1a14dcSpbrook     int async_ret;
2665ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2666f141eafeSaliguori     struct iovec iov;
2667f141eafeSaliguori     QEMUIOVector qiov;
266883f64091Sbellard 
266965d6b3d8SKevin Wolf     async_context_push();
267065d6b3d8SKevin Wolf 
267183f64091Sbellard     async_ret = NOT_DONE;
2672f141eafeSaliguori     iov.iov_base = (void *)buf;
2673eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2674f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2675f141eafeSaliguori     acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
267683f64091Sbellard         bdrv_rw_em_cb, &async_ret);
267765d6b3d8SKevin Wolf     if (acb == NULL) {
267865d6b3d8SKevin Wolf         async_ret = -1;
267965d6b3d8SKevin Wolf         goto fail;
268065d6b3d8SKevin Wolf     }
268183f64091Sbellard     while (async_ret == NOT_DONE) {
268283f64091Sbellard         qemu_aio_wait();
268383f64091Sbellard     }
268465d6b3d8SKevin Wolf 
268565d6b3d8SKevin Wolf fail:
268665d6b3d8SKevin Wolf     async_context_pop();
268783f64091Sbellard     return async_ret;
268883f64091Sbellard }
2689ea2384d3Sbellard 
2690ea2384d3Sbellard void bdrv_init(void)
2691ea2384d3Sbellard {
26925efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
2693ea2384d3Sbellard }
2694ce1a14dcSpbrook 
2695eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
2696eb852011SMarkus Armbruster {
2697eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
2698eb852011SMarkus Armbruster     bdrv_init();
2699eb852011SMarkus Armbruster }
2700eb852011SMarkus Armbruster 
2701c16b5a2cSChristoph Hellwig void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
27026bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
27036bbff9a0Saliguori {
2704ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2705ce1a14dcSpbrook 
27066bbff9a0Saliguori     if (pool->free_aiocb) {
27076bbff9a0Saliguori         acb = pool->free_aiocb;
27086bbff9a0Saliguori         pool->free_aiocb = acb->next;
2709ce1a14dcSpbrook     } else {
27106bbff9a0Saliguori         acb = qemu_mallocz(pool->aiocb_size);
27116bbff9a0Saliguori         acb->pool = pool;
2712ce1a14dcSpbrook     }
2713ce1a14dcSpbrook     acb->bs = bs;
2714ce1a14dcSpbrook     acb->cb = cb;
2715ce1a14dcSpbrook     acb->opaque = opaque;
2716ce1a14dcSpbrook     return acb;
2717ce1a14dcSpbrook }
2718ce1a14dcSpbrook 
2719ce1a14dcSpbrook void qemu_aio_release(void *p)
2720ce1a14dcSpbrook {
27216bbff9a0Saliguori     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
27226bbff9a0Saliguori     AIOPool *pool = acb->pool;
27236bbff9a0Saliguori     acb->next = pool->free_aiocb;
27246bbff9a0Saliguori     pool->free_aiocb = acb;
2725ce1a14dcSpbrook }
272619cb3738Sbellard 
272719cb3738Sbellard /**************************************************************/
272819cb3738Sbellard /* removable device support */
272919cb3738Sbellard 
273019cb3738Sbellard /**
273119cb3738Sbellard  * Return TRUE if the media is present
273219cb3738Sbellard  */
273319cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
273419cb3738Sbellard {
273519cb3738Sbellard     BlockDriver *drv = bs->drv;
273619cb3738Sbellard     int ret;
273719cb3738Sbellard     if (!drv)
273819cb3738Sbellard         return 0;
273919cb3738Sbellard     if (!drv->bdrv_is_inserted)
27404be9762aSMarkus Armbruster         return !bs->tray_open;
274119cb3738Sbellard     ret = drv->bdrv_is_inserted(bs);
274219cb3738Sbellard     return ret;
274319cb3738Sbellard }
274419cb3738Sbellard 
274519cb3738Sbellard /**
274619cb3738Sbellard  * Return TRUE if the media changed since the last call to this
274719cb3738Sbellard  * function. It is currently only used for floppy disks
274819cb3738Sbellard  */
274919cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
275019cb3738Sbellard {
275119cb3738Sbellard     BlockDriver *drv = bs->drv;
275219cb3738Sbellard     int ret;
275319cb3738Sbellard 
275419cb3738Sbellard     if (!drv || !drv->bdrv_media_changed)
275519cb3738Sbellard         ret = -ENOTSUP;
275619cb3738Sbellard     else
275719cb3738Sbellard         ret = drv->bdrv_media_changed(bs);
275819cb3738Sbellard     if (ret == -ENOTSUP)
275919cb3738Sbellard         ret = bs->media_changed;
276019cb3738Sbellard     bs->media_changed = 0;
276119cb3738Sbellard     return ret;
276219cb3738Sbellard }
276319cb3738Sbellard 
276419cb3738Sbellard /**
276519cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
276619cb3738Sbellard  */
2767aea2a33cSMark McLoughlin int bdrv_eject(BlockDriverState *bs, int eject_flag)
276819cb3738Sbellard {
276919cb3738Sbellard     BlockDriver *drv = bs->drv;
277019cb3738Sbellard     int ret;
277119cb3738Sbellard 
2772aea2a33cSMark McLoughlin     if (bs->locked) {
2773aea2a33cSMark McLoughlin         return -EBUSY;
2774aea2a33cSMark McLoughlin     }
2775aea2a33cSMark McLoughlin 
277619cb3738Sbellard     if (!drv || !drv->bdrv_eject) {
277719cb3738Sbellard         ret = -ENOTSUP;
277819cb3738Sbellard     } else {
277919cb3738Sbellard         ret = drv->bdrv_eject(bs, eject_flag);
278019cb3738Sbellard     }
278119cb3738Sbellard     if (ret == -ENOTSUP) {
2782aea2a33cSMark McLoughlin         ret = 0;
278319cb3738Sbellard     }
27844be9762aSMarkus Armbruster     if (ret >= 0) {
27854be9762aSMarkus Armbruster         bs->tray_open = eject_flag;
27864be9762aSMarkus Armbruster     }
2787aea2a33cSMark McLoughlin 
2788aea2a33cSMark McLoughlin     return ret;
278919cb3738Sbellard }
279019cb3738Sbellard 
279119cb3738Sbellard int bdrv_is_locked(BlockDriverState *bs)
279219cb3738Sbellard {
279319cb3738Sbellard     return bs->locked;
279419cb3738Sbellard }
279519cb3738Sbellard 
279619cb3738Sbellard /**
279719cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
279819cb3738Sbellard  * to eject it manually).
279919cb3738Sbellard  */
280019cb3738Sbellard void bdrv_set_locked(BlockDriverState *bs, int locked)
280119cb3738Sbellard {
280219cb3738Sbellard     BlockDriver *drv = bs->drv;
280319cb3738Sbellard 
280419cb3738Sbellard     bs->locked = locked;
280519cb3738Sbellard     if (drv && drv->bdrv_set_locked) {
280619cb3738Sbellard         drv->bdrv_set_locked(bs, locked);
280719cb3738Sbellard     }
280819cb3738Sbellard }
2809985a03b0Sths 
2810985a03b0Sths /* needed for generic scsi interface */
2811985a03b0Sths 
2812985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2813985a03b0Sths {
2814985a03b0Sths     BlockDriver *drv = bs->drv;
2815985a03b0Sths 
2816985a03b0Sths     if (drv && drv->bdrv_ioctl)
2817985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
2818985a03b0Sths     return -ENOTSUP;
2819985a03b0Sths }
28207d780669Saliguori 
2821221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2822221f715dSaliguori         unsigned long int req, void *buf,
28237d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
28247d780669Saliguori {
2825221f715dSaliguori     BlockDriver *drv = bs->drv;
28267d780669Saliguori 
2827221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
2828221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2829221f715dSaliguori     return NULL;
28307d780669Saliguori }
2831e268ca52Saliguori 
28327cd1e32aSlirans@il.ibm.com 
28337cd1e32aSlirans@il.ibm.com 
2834e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
2835e268ca52Saliguori {
2836e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2837e268ca52Saliguori }
28387cd1e32aSlirans@il.ibm.com 
28397cd1e32aSlirans@il.ibm.com void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
28407cd1e32aSlirans@il.ibm.com {
28417cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
2842a55eb92cSJan Kiszka 
2843aaa0eb75SLiran Schour     bs->dirty_count = 0;
28447cd1e32aSlirans@il.ibm.com     if (enable) {
2845c6d22830SJan Kiszka         if (!bs->dirty_bitmap) {
2846c6d22830SJan Kiszka             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2847c6d22830SJan Kiszka                     BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2848c6d22830SJan Kiszka             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
28497cd1e32aSlirans@il.ibm.com 
28507cd1e32aSlirans@il.ibm.com             bs->dirty_bitmap = qemu_mallocz(bitmap_size);
28517cd1e32aSlirans@il.ibm.com         }
28527cd1e32aSlirans@il.ibm.com     } else {
2853c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
28547cd1e32aSlirans@il.ibm.com             qemu_free(bs->dirty_bitmap);
2855c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
28567cd1e32aSlirans@il.ibm.com         }
28577cd1e32aSlirans@il.ibm.com     }
28587cd1e32aSlirans@il.ibm.com }
28597cd1e32aSlirans@il.ibm.com 
28607cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
28617cd1e32aSlirans@il.ibm.com {
28626ea44308SJan Kiszka     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
28637cd1e32aSlirans@il.ibm.com 
2864c6d22830SJan Kiszka     if (bs->dirty_bitmap &&
2865c6d22830SJan Kiszka         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
28666d59fec1SMarcelo Tosatti         return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
28676d59fec1SMarcelo Tosatti             (1UL << (chunk % (sizeof(unsigned long) * 8))));
28687cd1e32aSlirans@il.ibm.com     } else {
28697cd1e32aSlirans@il.ibm.com         return 0;
28707cd1e32aSlirans@il.ibm.com     }
28717cd1e32aSlirans@il.ibm.com }
28727cd1e32aSlirans@il.ibm.com 
28737cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
28747cd1e32aSlirans@il.ibm.com                       int nr_sectors)
28757cd1e32aSlirans@il.ibm.com {
28767cd1e32aSlirans@il.ibm.com     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
28777cd1e32aSlirans@il.ibm.com }
2878aaa0eb75SLiran Schour 
2879aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2880aaa0eb75SLiran Schour {
2881aaa0eb75SLiran Schour     return bs->dirty_count;
2882aaa0eb75SLiran Schour }
2883f88e1a42SJes Sorensen 
2884db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
2885db593f25SMarcelo Tosatti {
2886db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
2887db593f25SMarcelo Tosatti     bs->in_use = in_use;
2888db593f25SMarcelo Tosatti }
2889db593f25SMarcelo Tosatti 
2890db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
2891db593f25SMarcelo Tosatti {
2892db593f25SMarcelo Tosatti     return bs->in_use;
2893db593f25SMarcelo Tosatti }
2894db593f25SMarcelo Tosatti 
2895f88e1a42SJes Sorensen int bdrv_img_create(const char *filename, const char *fmt,
2896f88e1a42SJes Sorensen                     const char *base_filename, const char *base_fmt,
2897f88e1a42SJes Sorensen                     char *options, uint64_t img_size, int flags)
2898f88e1a42SJes Sorensen {
2899f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
2900792da93aSJes Sorensen     QEMUOptionParameter *backing_fmt, *backing_file;
2901f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
2902f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
290396df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
2904f88e1a42SJes Sorensen     int ret = 0;
2905f88e1a42SJes Sorensen 
2906f88e1a42SJes Sorensen     /* Find driver and parse its options */
2907f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
2908f88e1a42SJes Sorensen     if (!drv) {
2909f88e1a42SJes Sorensen         error_report("Unknown file format '%s'", fmt);
29104f70f249SJes Sorensen         ret = -EINVAL;
2911f88e1a42SJes Sorensen         goto out;
2912f88e1a42SJes Sorensen     }
2913f88e1a42SJes Sorensen 
2914f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
2915f88e1a42SJes Sorensen     if (!proto_drv) {
2916f88e1a42SJes Sorensen         error_report("Unknown protocol '%s'", filename);
29174f70f249SJes Sorensen         ret = -EINVAL;
2918f88e1a42SJes Sorensen         goto out;
2919f88e1a42SJes Sorensen     }
2920f88e1a42SJes Sorensen 
2921f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
2922f88e1a42SJes Sorensen                                               drv->create_options);
2923f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
2924f88e1a42SJes Sorensen                                               proto_drv->create_options);
2925f88e1a42SJes Sorensen 
2926f88e1a42SJes Sorensen     /* Create parameter list with default values */
2927f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
2928f88e1a42SJes Sorensen 
2929f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
2930f88e1a42SJes Sorensen 
2931f88e1a42SJes Sorensen     /* Parse -o options */
2932f88e1a42SJes Sorensen     if (options) {
2933f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
2934f88e1a42SJes Sorensen         if (param == NULL) {
2935f88e1a42SJes Sorensen             error_report("Invalid options for file format '%s'.", fmt);
29364f70f249SJes Sorensen             ret = -EINVAL;
2937f88e1a42SJes Sorensen             goto out;
2938f88e1a42SJes Sorensen         }
2939f88e1a42SJes Sorensen     }
2940f88e1a42SJes Sorensen 
2941f88e1a42SJes Sorensen     if (base_filename) {
2942f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
2943f88e1a42SJes Sorensen                                  base_filename)) {
2944f88e1a42SJes Sorensen             error_report("Backing file not supported for file format '%s'",
2945f88e1a42SJes Sorensen                          fmt);
29464f70f249SJes Sorensen             ret = -EINVAL;
2947f88e1a42SJes Sorensen             goto out;
2948f88e1a42SJes Sorensen         }
2949f88e1a42SJes Sorensen     }
2950f88e1a42SJes Sorensen 
2951f88e1a42SJes Sorensen     if (base_fmt) {
2952f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
2953f88e1a42SJes Sorensen             error_report("Backing file format not supported for file "
2954f88e1a42SJes Sorensen                          "format '%s'", fmt);
29554f70f249SJes Sorensen             ret = -EINVAL;
2956f88e1a42SJes Sorensen             goto out;
2957f88e1a42SJes Sorensen         }
2958f88e1a42SJes Sorensen     }
2959f88e1a42SJes Sorensen 
2960792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
2961792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
2962792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
2963792da93aSJes Sorensen             error_report("Error: Trying to create an image with the "
2964792da93aSJes Sorensen                          "same filename as the backing file");
29654f70f249SJes Sorensen             ret = -EINVAL;
2966792da93aSJes Sorensen             goto out;
2967792da93aSJes Sorensen         }
2968792da93aSJes Sorensen     }
2969792da93aSJes Sorensen 
2970f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
2971f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
297296df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
297396df67d1SStefan Hajnoczi         if (!backing_drv) {
2974f88e1a42SJes Sorensen             error_report("Unknown backing file format '%s'",
2975f88e1a42SJes Sorensen                          backing_fmt->value.s);
29764f70f249SJes Sorensen             ret = -EINVAL;
2977f88e1a42SJes Sorensen             goto out;
2978f88e1a42SJes Sorensen         }
2979f88e1a42SJes Sorensen     }
2980f88e1a42SJes Sorensen 
2981f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
2982f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
2983f88e1a42SJes Sorensen     if (get_option_parameter(param, BLOCK_OPT_SIZE)->value.n == -1) {
2984f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
2985f88e1a42SJes Sorensen             uint64_t size;
2986f88e1a42SJes Sorensen             char buf[32];
2987f88e1a42SJes Sorensen 
2988f88e1a42SJes Sorensen             bs = bdrv_new("");
2989f88e1a42SJes Sorensen 
299096df67d1SStefan Hajnoczi             ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
2991f88e1a42SJes Sorensen             if (ret < 0) {
299296df67d1SStefan Hajnoczi                 error_report("Could not open '%s'", backing_file->value.s);
2993f88e1a42SJes Sorensen                 goto out;
2994f88e1a42SJes Sorensen             }
2995f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
2996f88e1a42SJes Sorensen             size *= 512;
2997f88e1a42SJes Sorensen 
2998f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
2999f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3000f88e1a42SJes Sorensen         } else {
3001f88e1a42SJes Sorensen             error_report("Image creation needs a size parameter");
30024f70f249SJes Sorensen             ret = -EINVAL;
3003f88e1a42SJes Sorensen             goto out;
3004f88e1a42SJes Sorensen         }
3005f88e1a42SJes Sorensen     }
3006f88e1a42SJes Sorensen 
3007f88e1a42SJes Sorensen     printf("Formatting '%s', fmt=%s ", filename, fmt);
3008f88e1a42SJes Sorensen     print_option_parameters(param);
3009f88e1a42SJes Sorensen     puts("");
3010f88e1a42SJes Sorensen 
3011f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
3012f88e1a42SJes Sorensen 
3013f88e1a42SJes Sorensen     if (ret < 0) {
3014f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
3015f88e1a42SJes Sorensen             error_report("Formatting or formatting option not supported for "
3016f88e1a42SJes Sorensen                          "file format '%s'", fmt);
3017f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
3018f88e1a42SJes Sorensen             error_report("The image size is too large for file format '%s'",
3019f88e1a42SJes Sorensen                          fmt);
3020f88e1a42SJes Sorensen         } else {
3021f88e1a42SJes Sorensen             error_report("%s: error while creating %s: %s", filename, fmt,
3022f88e1a42SJes Sorensen                          strerror(-ret));
3023f88e1a42SJes Sorensen         }
3024f88e1a42SJes Sorensen     }
3025f88e1a42SJes Sorensen 
3026f88e1a42SJes Sorensen out:
3027f88e1a42SJes Sorensen     free_option_parameters(create_options);
3028f88e1a42SJes Sorensen     free_option_parameters(param);
3029f88e1a42SJes Sorensen 
3030f88e1a42SJes Sorensen     if (bs) {
3031f88e1a42SJes Sorensen         bdrv_delete(bs);
3032f88e1a42SJes Sorensen     }
30334f70f249SJes Sorensen 
30344f70f249SJes Sorensen     return ret;
3035f88e1a42SJes Sorensen }
3036