xref: /openbmc/qemu/block.c (revision 792da93a635bce0181c8a46a26941560bf2f7412)
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)
648b6ce07aaSKevin Wolf             bs->change_cb(bs->change_opaque);
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)
687b338082bSbellard             bs->change_cb(bs->change_opaque);
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;
113551762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
113651762288SStefan Hajnoczi     if (ret == 0) {
113751762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
113851762288SStefan Hajnoczi     }
113951762288SStefan Hajnoczi     return ret;
114083f64091Sbellard }
114183f64091Sbellard 
114283f64091Sbellard /**
114383f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
114483f64091Sbellard  */
114583f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
114683f64091Sbellard {
114783f64091Sbellard     BlockDriver *drv = bs->drv;
114883f64091Sbellard     if (!drv)
114919cb3738Sbellard         return -ENOMEDIUM;
115051762288SStefan Hajnoczi 
115151762288SStefan Hajnoczi     /* Fixed size devices use the total_sectors value for speed instead of
115251762288SStefan Hajnoczi        issuing a length query (like lseek) on each call.  Also, legacy block
115351762288SStefan Hajnoczi        drivers don't provide a bdrv_getlength function and must use
115451762288SStefan Hajnoczi        total_sectors. */
115551762288SStefan Hajnoczi     if (!bs->growable || !drv->bdrv_getlength) {
11566ea44308SJan Kiszka         return bs->total_sectors * BDRV_SECTOR_SIZE;
115783f64091Sbellard     }
115883f64091Sbellard     return drv->bdrv_getlength(bs);
1159fc01f7e7Sbellard }
1160fc01f7e7Sbellard 
116119cb3738Sbellard /* return 0 as number of sectors if no device present or error */
116296b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1163fc01f7e7Sbellard {
116419cb3738Sbellard     int64_t length;
116519cb3738Sbellard     length = bdrv_getlength(bs);
116619cb3738Sbellard     if (length < 0)
116719cb3738Sbellard         length = 0;
116819cb3738Sbellard     else
11696ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
117019cb3738Sbellard     *nb_sectors_ptr = length;
1171fc01f7e7Sbellard }
1172cf98951bSbellard 
1173f3d54fc4Saliguori struct partition {
1174f3d54fc4Saliguori         uint8_t boot_ind;           /* 0x80 - active */
1175f3d54fc4Saliguori         uint8_t head;               /* starting head */
1176f3d54fc4Saliguori         uint8_t sector;             /* starting sector */
1177f3d54fc4Saliguori         uint8_t cyl;                /* starting cylinder */
1178f3d54fc4Saliguori         uint8_t sys_ind;            /* What partition type */
1179f3d54fc4Saliguori         uint8_t end_head;           /* end head */
1180f3d54fc4Saliguori         uint8_t end_sector;         /* end sector */
1181f3d54fc4Saliguori         uint8_t end_cyl;            /* end cylinder */
1182f3d54fc4Saliguori         uint32_t start_sect;        /* starting sector counting from 0 */
1183f3d54fc4Saliguori         uint32_t nr_sects;          /* nr of sectors in partition */
1184f3d54fc4Saliguori } __attribute__((packed));
1185f3d54fc4Saliguori 
1186f3d54fc4Saliguori /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1187f3d54fc4Saliguori static int guess_disk_lchs(BlockDriverState *bs,
1188f3d54fc4Saliguori                            int *pcylinders, int *pheads, int *psectors)
1189f3d54fc4Saliguori {
1190eb5a3165SJes Sorensen     uint8_t buf[BDRV_SECTOR_SIZE];
1191f3d54fc4Saliguori     int ret, i, heads, sectors, cylinders;
1192f3d54fc4Saliguori     struct partition *p;
1193f3d54fc4Saliguori     uint32_t nr_sects;
1194a38131b6Sblueswir1     uint64_t nb_sectors;
1195f3d54fc4Saliguori 
1196f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1197f3d54fc4Saliguori 
1198f3d54fc4Saliguori     ret = bdrv_read(bs, 0, buf, 1);
1199f3d54fc4Saliguori     if (ret < 0)
1200f3d54fc4Saliguori         return -1;
1201f3d54fc4Saliguori     /* test msdos magic */
1202f3d54fc4Saliguori     if (buf[510] != 0x55 || buf[511] != 0xaa)
1203f3d54fc4Saliguori         return -1;
1204f3d54fc4Saliguori     for(i = 0; i < 4; i++) {
1205f3d54fc4Saliguori         p = ((struct partition *)(buf + 0x1be)) + i;
1206f3d54fc4Saliguori         nr_sects = le32_to_cpu(p->nr_sects);
1207f3d54fc4Saliguori         if (nr_sects && p->end_head) {
1208f3d54fc4Saliguori             /* We make the assumption that the partition terminates on
1209f3d54fc4Saliguori                a cylinder boundary */
1210f3d54fc4Saliguori             heads = p->end_head + 1;
1211f3d54fc4Saliguori             sectors = p->end_sector & 63;
1212f3d54fc4Saliguori             if (sectors == 0)
1213f3d54fc4Saliguori                 continue;
1214f3d54fc4Saliguori             cylinders = nb_sectors / (heads * sectors);
1215f3d54fc4Saliguori             if (cylinders < 1 || cylinders > 16383)
1216f3d54fc4Saliguori                 continue;
1217f3d54fc4Saliguori             *pheads = heads;
1218f3d54fc4Saliguori             *psectors = sectors;
1219f3d54fc4Saliguori             *pcylinders = cylinders;
1220f3d54fc4Saliguori #if 0
1221f3d54fc4Saliguori             printf("guessed geometry: LCHS=%d %d %d\n",
1222f3d54fc4Saliguori                    cylinders, heads, sectors);
1223f3d54fc4Saliguori #endif
1224f3d54fc4Saliguori             return 0;
1225f3d54fc4Saliguori         }
1226f3d54fc4Saliguori     }
1227f3d54fc4Saliguori     return -1;
1228f3d54fc4Saliguori }
1229f3d54fc4Saliguori 
1230f3d54fc4Saliguori void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1231f3d54fc4Saliguori {
1232f3d54fc4Saliguori     int translation, lba_detected = 0;
1233f3d54fc4Saliguori     int cylinders, heads, secs;
1234a38131b6Sblueswir1     uint64_t nb_sectors;
1235f3d54fc4Saliguori 
1236f3d54fc4Saliguori     /* if a geometry hint is available, use it */
1237f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1238f3d54fc4Saliguori     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1239f3d54fc4Saliguori     translation = bdrv_get_translation_hint(bs);
1240f3d54fc4Saliguori     if (cylinders != 0) {
1241f3d54fc4Saliguori         *pcyls = cylinders;
1242f3d54fc4Saliguori         *pheads = heads;
1243f3d54fc4Saliguori         *psecs = secs;
1244f3d54fc4Saliguori     } else {
1245f3d54fc4Saliguori         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1246f3d54fc4Saliguori             if (heads > 16) {
1247f3d54fc4Saliguori                 /* if heads > 16, it means that a BIOS LBA
1248f3d54fc4Saliguori                    translation was active, so the default
1249f3d54fc4Saliguori                    hardware geometry is OK */
1250f3d54fc4Saliguori                 lba_detected = 1;
1251f3d54fc4Saliguori                 goto default_geometry;
1252f3d54fc4Saliguori             } else {
1253f3d54fc4Saliguori                 *pcyls = cylinders;
1254f3d54fc4Saliguori                 *pheads = heads;
1255f3d54fc4Saliguori                 *psecs = secs;
1256f3d54fc4Saliguori                 /* disable any translation to be in sync with
1257f3d54fc4Saliguori                    the logical geometry */
1258f3d54fc4Saliguori                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1259f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1260f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_NONE);
1261f3d54fc4Saliguori                 }
1262f3d54fc4Saliguori             }
1263f3d54fc4Saliguori         } else {
1264f3d54fc4Saliguori         default_geometry:
1265f3d54fc4Saliguori             /* if no geometry, use a standard physical disk geometry */
1266f3d54fc4Saliguori             cylinders = nb_sectors / (16 * 63);
1267f3d54fc4Saliguori 
1268f3d54fc4Saliguori             if (cylinders > 16383)
1269f3d54fc4Saliguori                 cylinders = 16383;
1270f3d54fc4Saliguori             else if (cylinders < 2)
1271f3d54fc4Saliguori                 cylinders = 2;
1272f3d54fc4Saliguori             *pcyls = cylinders;
1273f3d54fc4Saliguori             *pheads = 16;
1274f3d54fc4Saliguori             *psecs = 63;
1275f3d54fc4Saliguori             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1276f3d54fc4Saliguori                 if ((*pcyls * *pheads) <= 131072) {
1277f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1278f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LARGE);
1279f3d54fc4Saliguori                 } else {
1280f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1281f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LBA);
1282f3d54fc4Saliguori                 }
1283f3d54fc4Saliguori             }
1284f3d54fc4Saliguori         }
1285f3d54fc4Saliguori         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1286f3d54fc4Saliguori     }
1287f3d54fc4Saliguori }
1288f3d54fc4Saliguori 
1289b338082bSbellard void bdrv_set_geometry_hint(BlockDriverState *bs,
1290b338082bSbellard                             int cyls, int heads, int secs)
1291b338082bSbellard {
1292b338082bSbellard     bs->cyls = cyls;
1293b338082bSbellard     bs->heads = heads;
1294b338082bSbellard     bs->secs = secs;
1295b338082bSbellard }
1296b338082bSbellard 
1297b338082bSbellard void bdrv_set_type_hint(BlockDriverState *bs, int type)
1298b338082bSbellard {
1299b338082bSbellard     bs->type = type;
1300b338082bSbellard     bs->removable = ((type == BDRV_TYPE_CDROM ||
1301b338082bSbellard                       type == BDRV_TYPE_FLOPPY));
1302b338082bSbellard }
1303b338082bSbellard 
130446d4767dSbellard void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
130546d4767dSbellard {
130646d4767dSbellard     bs->translation = translation;
130746d4767dSbellard }
130846d4767dSbellard 
1309b338082bSbellard void bdrv_get_geometry_hint(BlockDriverState *bs,
1310b338082bSbellard                             int *pcyls, int *pheads, int *psecs)
1311b338082bSbellard {
1312b338082bSbellard     *pcyls = bs->cyls;
1313b338082bSbellard     *pheads = bs->heads;
1314b338082bSbellard     *psecs = bs->secs;
1315b338082bSbellard }
1316b338082bSbellard 
1317b338082bSbellard int bdrv_get_type_hint(BlockDriverState *bs)
1318b338082bSbellard {
1319b338082bSbellard     return bs->type;
1320b338082bSbellard }
1321b338082bSbellard 
132246d4767dSbellard int bdrv_get_translation_hint(BlockDriverState *bs)
132346d4767dSbellard {
132446d4767dSbellard     return bs->translation;
132546d4767dSbellard }
132646d4767dSbellard 
1327abd7f68dSMarkus Armbruster void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1328abd7f68dSMarkus Armbruster                        BlockErrorAction on_write_error)
1329abd7f68dSMarkus Armbruster {
1330abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
1331abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
1332abd7f68dSMarkus Armbruster }
1333abd7f68dSMarkus Armbruster 
1334abd7f68dSMarkus Armbruster BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1335abd7f68dSMarkus Armbruster {
1336abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
1337abd7f68dSMarkus Armbruster }
1338abd7f68dSMarkus Armbruster 
13397d0d6950SMarkus Armbruster void bdrv_set_removable(BlockDriverState *bs, int removable)
13407d0d6950SMarkus Armbruster {
13417d0d6950SMarkus Armbruster     bs->removable = removable;
13427d0d6950SMarkus Armbruster     if (removable && bs == bs_snapshots) {
13437d0d6950SMarkus Armbruster         bs_snapshots = NULL;
13447d0d6950SMarkus Armbruster     }
13457d0d6950SMarkus Armbruster }
13467d0d6950SMarkus Armbruster 
1347b338082bSbellard int bdrv_is_removable(BlockDriverState *bs)
1348b338082bSbellard {
1349b338082bSbellard     return bs->removable;
1350b338082bSbellard }
1351b338082bSbellard 
1352b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
1353b338082bSbellard {
1354b338082bSbellard     return bs->read_only;
1355b338082bSbellard }
1356b338082bSbellard 
1357985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
1358985a03b0Sths {
1359985a03b0Sths     return bs->sg;
1360985a03b0Sths }
1361985a03b0Sths 
1362e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
1363e900a7b7SChristoph Hellwig {
1364e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
1365e900a7b7SChristoph Hellwig }
1366e900a7b7SChristoph Hellwig 
136719cb3738Sbellard /* XXX: no longer used */
1368b338082bSbellard void bdrv_set_change_cb(BlockDriverState *bs,
1369b338082bSbellard                         void (*change_cb)(void *opaque), void *opaque)
1370b338082bSbellard {
1371b338082bSbellard     bs->change_cb = change_cb;
1372b338082bSbellard     bs->change_opaque = opaque;
1373b338082bSbellard }
1374b338082bSbellard 
1375ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
1376ea2384d3Sbellard {
1377ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
1378ea2384d3Sbellard         return 1;
1379ea2384d3Sbellard     return bs->encrypted;
1380ea2384d3Sbellard }
1381ea2384d3Sbellard 
1382c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
1383c0f4ce77Saliguori {
1384c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
1385c0f4ce77Saliguori 
1386c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1387c0f4ce77Saliguori         return 1;
1388c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
1389c0f4ce77Saliguori }
1390c0f4ce77Saliguori 
1391ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
1392ea2384d3Sbellard {
1393ea2384d3Sbellard     int ret;
1394ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
1395ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
1396ea2384d3Sbellard         if (ret < 0)
1397ea2384d3Sbellard             return ret;
1398ea2384d3Sbellard         if (!bs->encrypted)
1399ea2384d3Sbellard             return 0;
1400ea2384d3Sbellard     }
1401fd04a2aeSShahar Havivi     if (!bs->encrypted) {
1402fd04a2aeSShahar Havivi         return -EINVAL;
1403fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1404fd04a2aeSShahar Havivi         return -ENOMEDIUM;
1405fd04a2aeSShahar Havivi     }
1406c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
1407bb5fc20fSaliguori     if (ret < 0) {
1408bb5fc20fSaliguori         bs->valid_key = 0;
1409bb5fc20fSaliguori     } else if (!bs->valid_key) {
1410bb5fc20fSaliguori         bs->valid_key = 1;
1411bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
1412bb5fc20fSaliguori         bs->media_changed = 1;
1413bb5fc20fSaliguori         if (bs->change_cb)
1414bb5fc20fSaliguori             bs->change_cb(bs->change_opaque);
1415bb5fc20fSaliguori     }
1416c0f4ce77Saliguori     return ret;
1417ea2384d3Sbellard }
1418ea2384d3Sbellard 
1419ea2384d3Sbellard void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1420ea2384d3Sbellard {
142119cb3738Sbellard     if (!bs->drv) {
1422ea2384d3Sbellard         buf[0] = '\0';
1423ea2384d3Sbellard     } else {
1424ea2384d3Sbellard         pstrcpy(buf, buf_size, bs->drv->format_name);
1425ea2384d3Sbellard     }
1426ea2384d3Sbellard }
1427ea2384d3Sbellard 
1428ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1429ea2384d3Sbellard                          void *opaque)
1430ea2384d3Sbellard {
1431ea2384d3Sbellard     BlockDriver *drv;
1432ea2384d3Sbellard 
14338a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
1434ea2384d3Sbellard         it(opaque, drv->format_name);
1435ea2384d3Sbellard     }
1436ea2384d3Sbellard }
1437ea2384d3Sbellard 
1438b338082bSbellard BlockDriverState *bdrv_find(const char *name)
1439b338082bSbellard {
1440b338082bSbellard     BlockDriverState *bs;
1441b338082bSbellard 
14421b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
14431b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
1444b338082bSbellard             return bs;
1445b338082bSbellard         }
14461b7bdbc1SStefan Hajnoczi     }
1447b338082bSbellard     return NULL;
1448b338082bSbellard }
1449b338082bSbellard 
14502f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
14512f399b0aSMarkus Armbruster {
14522f399b0aSMarkus Armbruster     if (!bs) {
14532f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
14542f399b0aSMarkus Armbruster     }
14552f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
14562f399b0aSMarkus Armbruster }
14572f399b0aSMarkus Armbruster 
145851de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
145981d0912dSbellard {
146081d0912dSbellard     BlockDriverState *bs;
146181d0912dSbellard 
14621b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
146351de9760Saliguori         it(opaque, bs);
146481d0912dSbellard     }
146581d0912dSbellard }
146681d0912dSbellard 
1467ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
1468ea2384d3Sbellard {
1469ea2384d3Sbellard     return bs->device_name;
1470ea2384d3Sbellard }
1471ea2384d3Sbellard 
1472205ef796SKevin Wolf int bdrv_flush(BlockDriverState *bs)
14737a6cba61Spbrook {
1474016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
1475205ef796SKevin Wolf         return 0;
1476016f5cf6SAlexander Graf     }
1477016f5cf6SAlexander Graf 
1478205ef796SKevin Wolf     if (bs->drv && bs->drv->bdrv_flush) {
1479205ef796SKevin Wolf         return bs->drv->bdrv_flush(bs);
1480205ef796SKevin Wolf     }
1481205ef796SKevin Wolf 
1482205ef796SKevin Wolf     /*
1483205ef796SKevin Wolf      * Some block drivers always operate in either writethrough or unsafe mode
1484205ef796SKevin Wolf      * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1485205ef796SKevin Wolf      * the server works (because the behaviour is hardcoded or depends on
1486205ef796SKevin Wolf      * server-side configuration), so we can't ensure that everything is safe
1487205ef796SKevin Wolf      * on disk. Returning an error doesn't work because that would break guests
1488205ef796SKevin Wolf      * even if the server operates in writethrough mode.
1489205ef796SKevin Wolf      *
1490205ef796SKevin Wolf      * Let's hope the user knows what he's doing.
1491205ef796SKevin Wolf      */
1492205ef796SKevin Wolf     return 0;
14937a6cba61Spbrook }
14947a6cba61Spbrook 
1495c6ca28d6Saliguori void bdrv_flush_all(void)
1496c6ca28d6Saliguori {
1497c6ca28d6Saliguori     BlockDriverState *bs;
1498c6ca28d6Saliguori 
14991b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1500c6ca28d6Saliguori         if (bs->drv && !bdrv_is_read_only(bs) &&
15011b7bdbc1SStefan Hajnoczi             (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1502c6ca28d6Saliguori             bdrv_flush(bs);
1503c6ca28d6Saliguori         }
15041b7bdbc1SStefan Hajnoczi     }
15051b7bdbc1SStefan Hajnoczi }
1506c6ca28d6Saliguori 
1507f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
1508f2feebbdSKevin Wolf {
1509f2feebbdSKevin Wolf     assert(bs->drv);
1510f2feebbdSKevin Wolf 
1511336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
1512336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
1513f2feebbdSKevin Wolf     }
1514f2feebbdSKevin Wolf 
1515f2feebbdSKevin Wolf     return 1;
1516f2feebbdSKevin Wolf }
1517f2feebbdSKevin Wolf 
1518f58c7b35Sths /*
1519f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
1520f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
1521f58c7b35Sths  * hence all their sectors are reported as allocated.
1522f58c7b35Sths  *
1523f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
1524f58c7b35Sths  * the specified sector) that are known to be in the same
1525f58c7b35Sths  * allocated/unallocated state.
1526f58c7b35Sths  *
1527f58c7b35Sths  * 'nb_sectors' is the max value 'pnum' should be set to.
1528f58c7b35Sths  */
1529f58c7b35Sths int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1530f58c7b35Sths 	int *pnum)
1531f58c7b35Sths {
1532f58c7b35Sths     int64_t n;
1533f58c7b35Sths     if (!bs->drv->bdrv_is_allocated) {
1534f58c7b35Sths         if (sector_num >= bs->total_sectors) {
1535f58c7b35Sths             *pnum = 0;
1536f58c7b35Sths             return 0;
1537f58c7b35Sths         }
1538f58c7b35Sths         n = bs->total_sectors - sector_num;
1539f58c7b35Sths         *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1540f58c7b35Sths         return 1;
1541f58c7b35Sths     }
1542f58c7b35Sths     return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1543f58c7b35Sths }
1544f58c7b35Sths 
15452582bfedSLuiz Capitulino void bdrv_mon_event(const BlockDriverState *bdrv,
15462582bfedSLuiz Capitulino                     BlockMonEventAction action, int is_read)
15472582bfedSLuiz Capitulino {
15482582bfedSLuiz Capitulino     QObject *data;
15492582bfedSLuiz Capitulino     const char *action_str;
15502582bfedSLuiz Capitulino 
15512582bfedSLuiz Capitulino     switch (action) {
15522582bfedSLuiz Capitulino     case BDRV_ACTION_REPORT:
15532582bfedSLuiz Capitulino         action_str = "report";
15542582bfedSLuiz Capitulino         break;
15552582bfedSLuiz Capitulino     case BDRV_ACTION_IGNORE:
15562582bfedSLuiz Capitulino         action_str = "ignore";
15572582bfedSLuiz Capitulino         break;
15582582bfedSLuiz Capitulino     case BDRV_ACTION_STOP:
15592582bfedSLuiz Capitulino         action_str = "stop";
15602582bfedSLuiz Capitulino         break;
15612582bfedSLuiz Capitulino     default:
15622582bfedSLuiz Capitulino         abort();
15632582bfedSLuiz Capitulino     }
15642582bfedSLuiz Capitulino 
15652582bfedSLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
15662582bfedSLuiz Capitulino                               bdrv->device_name,
15672582bfedSLuiz Capitulino                               action_str,
15682582bfedSLuiz Capitulino                               is_read ? "read" : "write");
15692582bfedSLuiz Capitulino     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
15702582bfedSLuiz Capitulino 
15712582bfedSLuiz Capitulino     qobject_decref(data);
15722582bfedSLuiz Capitulino }
15732582bfedSLuiz Capitulino 
1574d15e5465SLuiz Capitulino static void bdrv_print_dict(QObject *obj, void *opaque)
1575b338082bSbellard {
1576d15e5465SLuiz Capitulino     QDict *bs_dict;
1577d15e5465SLuiz Capitulino     Monitor *mon = opaque;
1578b338082bSbellard 
1579d15e5465SLuiz Capitulino     bs_dict = qobject_to_qdict(obj);
1580d15e5465SLuiz Capitulino 
1581d15e5465SLuiz Capitulino     monitor_printf(mon, "%s: type=%s removable=%d",
1582d15e5465SLuiz Capitulino                         qdict_get_str(bs_dict, "device"),
1583d15e5465SLuiz Capitulino                         qdict_get_str(bs_dict, "type"),
1584d15e5465SLuiz Capitulino                         qdict_get_bool(bs_dict, "removable"));
1585d15e5465SLuiz Capitulino 
1586d15e5465SLuiz Capitulino     if (qdict_get_bool(bs_dict, "removable")) {
1587d15e5465SLuiz Capitulino         monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1588b338082bSbellard     }
1589d15e5465SLuiz Capitulino 
1590d15e5465SLuiz Capitulino     if (qdict_haskey(bs_dict, "inserted")) {
1591d15e5465SLuiz Capitulino         QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1592d15e5465SLuiz Capitulino 
1593376253ecSaliguori         monitor_printf(mon, " file=");
1594d15e5465SLuiz Capitulino         monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1595d15e5465SLuiz Capitulino         if (qdict_haskey(qdict, "backing_file")) {
1596376253ecSaliguori             monitor_printf(mon, " backing_file=");
1597d15e5465SLuiz Capitulino             monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1598fef30743Sths         }
1599d15e5465SLuiz Capitulino         monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1600d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "ro"),
1601d15e5465SLuiz Capitulino                             qdict_get_str(qdict, "drv"),
1602d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "encrypted"));
1603b338082bSbellard     } else {
1604376253ecSaliguori         monitor_printf(mon, " [not inserted]");
1605b338082bSbellard     }
1606d15e5465SLuiz Capitulino 
1607376253ecSaliguori     monitor_printf(mon, "\n");
1608b338082bSbellard }
1609d15e5465SLuiz Capitulino 
1610d15e5465SLuiz Capitulino void bdrv_info_print(Monitor *mon, const QObject *data)
1611d15e5465SLuiz Capitulino {
1612d15e5465SLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1613d15e5465SLuiz Capitulino }
1614d15e5465SLuiz Capitulino 
1615d15e5465SLuiz Capitulino void bdrv_info(Monitor *mon, QObject **ret_data)
1616d15e5465SLuiz Capitulino {
1617d15e5465SLuiz Capitulino     QList *bs_list;
1618d15e5465SLuiz Capitulino     BlockDriverState *bs;
1619d15e5465SLuiz Capitulino 
1620d15e5465SLuiz Capitulino     bs_list = qlist_new();
1621d15e5465SLuiz Capitulino 
16221b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1623d15e5465SLuiz Capitulino         QObject *bs_obj;
1624d15e5465SLuiz Capitulino         const char *type = "unknown";
1625d15e5465SLuiz Capitulino 
1626d15e5465SLuiz Capitulino         switch(bs->type) {
1627d15e5465SLuiz Capitulino         case BDRV_TYPE_HD:
1628d15e5465SLuiz Capitulino             type = "hd";
1629d15e5465SLuiz Capitulino             break;
1630d15e5465SLuiz Capitulino         case BDRV_TYPE_CDROM:
1631d15e5465SLuiz Capitulino             type = "cdrom";
1632d15e5465SLuiz Capitulino             break;
1633d15e5465SLuiz Capitulino         case BDRV_TYPE_FLOPPY:
1634d15e5465SLuiz Capitulino             type = "floppy";
1635d15e5465SLuiz Capitulino             break;
1636d15e5465SLuiz Capitulino         }
1637d15e5465SLuiz Capitulino 
1638d15e5465SLuiz Capitulino         bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1639d15e5465SLuiz Capitulino                                     "'removable': %i, 'locked': %i }",
1640d15e5465SLuiz Capitulino                                     bs->device_name, type, bs->removable,
1641d15e5465SLuiz Capitulino                                     bs->locked);
1642d15e5465SLuiz Capitulino 
1643d15e5465SLuiz Capitulino         if (bs->drv) {
1644d15e5465SLuiz Capitulino             QObject *obj;
1645d15e5465SLuiz Capitulino             QDict *bs_dict = qobject_to_qdict(bs_obj);
1646d15e5465SLuiz Capitulino 
1647d15e5465SLuiz Capitulino             obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1648d15e5465SLuiz Capitulino                                      "'encrypted': %i }",
1649d15e5465SLuiz Capitulino                                      bs->filename, bs->read_only,
1650d15e5465SLuiz Capitulino                                      bs->drv->format_name,
1651d15e5465SLuiz Capitulino                                      bdrv_is_encrypted(bs));
1652d15e5465SLuiz Capitulino             if (bs->backing_file[0] != '\0') {
1653d15e5465SLuiz Capitulino                 QDict *qdict = qobject_to_qdict(obj);
1654d15e5465SLuiz Capitulino                 qdict_put(qdict, "backing_file",
1655d15e5465SLuiz Capitulino                           qstring_from_str(bs->backing_file));
1656d15e5465SLuiz Capitulino             }
1657d15e5465SLuiz Capitulino 
1658d15e5465SLuiz Capitulino             qdict_put_obj(bs_dict, "inserted", obj);
1659d15e5465SLuiz Capitulino         }
1660d15e5465SLuiz Capitulino         qlist_append_obj(bs_list, bs_obj);
1661d15e5465SLuiz Capitulino     }
1662d15e5465SLuiz Capitulino 
1663d15e5465SLuiz Capitulino     *ret_data = QOBJECT(bs_list);
1664b338082bSbellard }
1665a36e69ddSths 
1666218a536aSLuiz Capitulino static void bdrv_stats_iter(QObject *data, void *opaque)
1667a36e69ddSths {
1668218a536aSLuiz Capitulino     QDict *qdict;
1669218a536aSLuiz Capitulino     Monitor *mon = opaque;
1670218a536aSLuiz Capitulino 
1671218a536aSLuiz Capitulino     qdict = qobject_to_qdict(data);
1672218a536aSLuiz Capitulino     monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1673218a536aSLuiz Capitulino 
1674218a536aSLuiz Capitulino     qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1675218a536aSLuiz Capitulino     monitor_printf(mon, " rd_bytes=%" PRId64
1676218a536aSLuiz Capitulino                         " wr_bytes=%" PRId64
1677218a536aSLuiz Capitulino                         " rd_operations=%" PRId64
1678218a536aSLuiz Capitulino                         " wr_operations=%" PRId64
1679218a536aSLuiz Capitulino                         "\n",
1680218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_bytes"),
1681218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_bytes"),
1682218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_operations"),
1683218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_operations"));
1684218a536aSLuiz Capitulino }
1685218a536aSLuiz Capitulino 
1686218a536aSLuiz Capitulino void bdrv_stats_print(Monitor *mon, const QObject *data)
1687218a536aSLuiz Capitulino {
1688218a536aSLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1689218a536aSLuiz Capitulino }
1690218a536aSLuiz Capitulino 
1691294cc35fSKevin Wolf static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1692294cc35fSKevin Wolf {
1693294cc35fSKevin Wolf     QObject *res;
1694294cc35fSKevin Wolf     QDict *dict;
1695294cc35fSKevin Wolf 
1696294cc35fSKevin Wolf     res = qobject_from_jsonf("{ 'stats': {"
1697294cc35fSKevin Wolf                              "'rd_bytes': %" PRId64 ","
1698294cc35fSKevin Wolf                              "'wr_bytes': %" PRId64 ","
1699294cc35fSKevin Wolf                              "'rd_operations': %" PRId64 ","
1700294cc35fSKevin Wolf                              "'wr_operations': %" PRId64 ","
1701294cc35fSKevin Wolf                              "'wr_highest_offset': %" PRId64
1702294cc35fSKevin Wolf                              "} }",
1703294cc35fSKevin Wolf                              bs->rd_bytes, bs->wr_bytes,
1704294cc35fSKevin Wolf                              bs->rd_ops, bs->wr_ops,
17055ffbbc67SBlue Swirl                              bs->wr_highest_sector *
17065ffbbc67SBlue Swirl                              (uint64_t)BDRV_SECTOR_SIZE);
1707294cc35fSKevin Wolf     dict  = qobject_to_qdict(res);
1708294cc35fSKevin Wolf 
1709294cc35fSKevin Wolf     if (*bs->device_name) {
1710294cc35fSKevin Wolf         qdict_put(dict, "device", qstring_from_str(bs->device_name));
1711294cc35fSKevin Wolf     }
1712294cc35fSKevin Wolf 
1713294cc35fSKevin Wolf     if (bs->file) {
1714294cc35fSKevin Wolf         QObject *parent = bdrv_info_stats_bs(bs->file);
1715294cc35fSKevin Wolf         qdict_put_obj(dict, "parent", parent);
1716294cc35fSKevin Wolf     }
1717294cc35fSKevin Wolf 
1718294cc35fSKevin Wolf     return res;
1719294cc35fSKevin Wolf }
1720294cc35fSKevin Wolf 
1721218a536aSLuiz Capitulino void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1722218a536aSLuiz Capitulino {
1723218a536aSLuiz Capitulino     QObject *obj;
1724218a536aSLuiz Capitulino     QList *devices;
1725a36e69ddSths     BlockDriverState *bs;
1726a36e69ddSths 
1727218a536aSLuiz Capitulino     devices = qlist_new();
1728218a536aSLuiz Capitulino 
17291b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1730294cc35fSKevin Wolf         obj = bdrv_info_stats_bs(bs);
1731218a536aSLuiz Capitulino         qlist_append_obj(devices, obj);
1732a36e69ddSths     }
1733218a536aSLuiz Capitulino 
1734218a536aSLuiz Capitulino     *ret_data = QOBJECT(devices);
1735a36e69ddSths }
1736ea2384d3Sbellard 
1737045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1738045df330Saliguori {
1739045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
1740045df330Saliguori         return bs->backing_file;
1741045df330Saliguori     else if (bs->encrypted)
1742045df330Saliguori         return bs->filename;
1743045df330Saliguori     else
1744045df330Saliguori         return NULL;
1745045df330Saliguori }
1746045df330Saliguori 
174783f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
174883f64091Sbellard                                char *filename, int filename_size)
174983f64091Sbellard {
1750b783e409SKevin Wolf     if (!bs->backing_file) {
175183f64091Sbellard         pstrcpy(filename, filename_size, "");
175283f64091Sbellard     } else {
175383f64091Sbellard         pstrcpy(filename, filename_size, bs->backing_file);
175483f64091Sbellard     }
175583f64091Sbellard }
175683f64091Sbellard 
1757faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1758faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
1759faea38e7Sbellard {
1760faea38e7Sbellard     BlockDriver *drv = bs->drv;
1761faea38e7Sbellard     if (!drv)
176219cb3738Sbellard         return -ENOMEDIUM;
1763faea38e7Sbellard     if (!drv->bdrv_write_compressed)
1764faea38e7Sbellard         return -ENOTSUP;
1765fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
1766fbb7b4e0SKevin Wolf         return -EIO;
17677cd1e32aSlirans@il.ibm.com 
1768c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
17697cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
17707cd1e32aSlirans@il.ibm.com     }
17717cd1e32aSlirans@il.ibm.com 
1772faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1773faea38e7Sbellard }
1774faea38e7Sbellard 
1775faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1776faea38e7Sbellard {
1777faea38e7Sbellard     BlockDriver *drv = bs->drv;
1778faea38e7Sbellard     if (!drv)
177919cb3738Sbellard         return -ENOMEDIUM;
1780faea38e7Sbellard     if (!drv->bdrv_get_info)
1781faea38e7Sbellard         return -ENOTSUP;
1782faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
1783faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
1784faea38e7Sbellard }
1785faea38e7Sbellard 
178645566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
178745566e9cSChristoph Hellwig                       int64_t pos, int size)
1788178e08a5Saliguori {
1789178e08a5Saliguori     BlockDriver *drv = bs->drv;
1790178e08a5Saliguori     if (!drv)
1791178e08a5Saliguori         return -ENOMEDIUM;
17927cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
179345566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
17947cdb1f6dSMORITA Kazutaka     if (bs->file)
17957cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
17967cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1797178e08a5Saliguori }
1798178e08a5Saliguori 
179945566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
180045566e9cSChristoph Hellwig                       int64_t pos, int size)
1801178e08a5Saliguori {
1802178e08a5Saliguori     BlockDriver *drv = bs->drv;
1803178e08a5Saliguori     if (!drv)
1804178e08a5Saliguori         return -ENOMEDIUM;
18057cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
180645566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
18077cdb1f6dSMORITA Kazutaka     if (bs->file)
18087cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
18097cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1810178e08a5Saliguori }
1811178e08a5Saliguori 
18128b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
18138b9b0cc2SKevin Wolf {
18148b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
18158b9b0cc2SKevin Wolf 
18168b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
18178b9b0cc2SKevin Wolf         return;
18188b9b0cc2SKevin Wolf     }
18198b9b0cc2SKevin Wolf 
18208b9b0cc2SKevin Wolf     return drv->bdrv_debug_event(bs, event);
18218b9b0cc2SKevin Wolf 
18228b9b0cc2SKevin Wolf }
18238b9b0cc2SKevin Wolf 
1824faea38e7Sbellard /**************************************************************/
1825faea38e7Sbellard /* handling of snapshots */
1826faea38e7Sbellard 
1827feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
1828feeee5acSMiguel Di Ciurcio Filho {
1829feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
1830feeee5acSMiguel Di Ciurcio Filho     if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1831feeee5acSMiguel Di Ciurcio Filho         return 0;
1832feeee5acSMiguel Di Ciurcio Filho     }
1833feeee5acSMiguel Di Ciurcio Filho 
1834feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
1835feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
1836feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
1837feeee5acSMiguel Di Ciurcio Filho         }
1838feeee5acSMiguel Di Ciurcio Filho         return 0;
1839feeee5acSMiguel Di Ciurcio Filho     }
1840feeee5acSMiguel Di Ciurcio Filho 
1841feeee5acSMiguel Di Ciurcio Filho     return 1;
1842feeee5acSMiguel Di Ciurcio Filho }
1843feeee5acSMiguel Di Ciurcio Filho 
1844199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
1845199630b6SBlue Swirl {
1846199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
1847199630b6SBlue Swirl }
1848199630b6SBlue Swirl 
1849f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
1850f9092b10SMarkus Armbruster {
1851f9092b10SMarkus Armbruster     BlockDriverState *bs;
1852f9092b10SMarkus Armbruster 
18533ac906f7SMarkus Armbruster     if (bs_snapshots) {
1854f9092b10SMarkus Armbruster         return bs_snapshots;
18553ac906f7SMarkus Armbruster     }
1856f9092b10SMarkus Armbruster 
1857f9092b10SMarkus Armbruster     bs = NULL;
1858f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
1859f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
18603ac906f7SMarkus Armbruster             bs_snapshots = bs;
18613ac906f7SMarkus Armbruster             return bs;
1862f9092b10SMarkus Armbruster         }
1863f9092b10SMarkus Armbruster     }
1864f9092b10SMarkus Armbruster     return NULL;
1865f9092b10SMarkus Armbruster }
1866f9092b10SMarkus Armbruster 
1867faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
1868faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
1869faea38e7Sbellard {
1870faea38e7Sbellard     BlockDriver *drv = bs->drv;
1871faea38e7Sbellard     if (!drv)
187219cb3738Sbellard         return -ENOMEDIUM;
18737cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
1874faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
18757cdb1f6dSMORITA Kazutaka     if (bs->file)
18767cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
18777cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1878faea38e7Sbellard }
1879faea38e7Sbellard 
1880faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
1881faea38e7Sbellard                        const char *snapshot_id)
1882faea38e7Sbellard {
1883faea38e7Sbellard     BlockDriver *drv = bs->drv;
18847cdb1f6dSMORITA Kazutaka     int ret, open_ret;
18857cdb1f6dSMORITA Kazutaka 
1886faea38e7Sbellard     if (!drv)
188719cb3738Sbellard         return -ENOMEDIUM;
18887cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
1889faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
18907cdb1f6dSMORITA Kazutaka 
18917cdb1f6dSMORITA Kazutaka     if (bs->file) {
18927cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
18937cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
18947cdb1f6dSMORITA Kazutaka         open_ret = drv->bdrv_open(bs, bs->open_flags);
18957cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
18967cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
18977cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
18987cdb1f6dSMORITA Kazutaka             return open_ret;
18997cdb1f6dSMORITA Kazutaka         }
19007cdb1f6dSMORITA Kazutaka         return ret;
19017cdb1f6dSMORITA Kazutaka     }
19027cdb1f6dSMORITA Kazutaka 
19037cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1904faea38e7Sbellard }
1905faea38e7Sbellard 
1906faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1907faea38e7Sbellard {
1908faea38e7Sbellard     BlockDriver *drv = bs->drv;
1909faea38e7Sbellard     if (!drv)
191019cb3738Sbellard         return -ENOMEDIUM;
19117cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
1912faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
19137cdb1f6dSMORITA Kazutaka     if (bs->file)
19147cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
19157cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1916faea38e7Sbellard }
1917faea38e7Sbellard 
1918faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
1919faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
1920faea38e7Sbellard {
1921faea38e7Sbellard     BlockDriver *drv = bs->drv;
1922faea38e7Sbellard     if (!drv)
192319cb3738Sbellard         return -ENOMEDIUM;
19247cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
1925faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
19267cdb1f6dSMORITA Kazutaka     if (bs->file)
19277cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
19287cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1929faea38e7Sbellard }
1930faea38e7Sbellard 
193151ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
193251ef6727Sedison         const char *snapshot_name)
193351ef6727Sedison {
193451ef6727Sedison     BlockDriver *drv = bs->drv;
193551ef6727Sedison     if (!drv) {
193651ef6727Sedison         return -ENOMEDIUM;
193751ef6727Sedison     }
193851ef6727Sedison     if (!bs->read_only) {
193951ef6727Sedison         return -EINVAL;
194051ef6727Sedison     }
194151ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
194251ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
194351ef6727Sedison     }
194451ef6727Sedison     return -ENOTSUP;
194551ef6727Sedison }
194651ef6727Sedison 
1947faea38e7Sbellard #define NB_SUFFIXES 4
1948faea38e7Sbellard 
1949faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1950faea38e7Sbellard {
1951faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
1952faea38e7Sbellard     int64_t base;
1953faea38e7Sbellard     int i;
1954faea38e7Sbellard 
1955faea38e7Sbellard     if (size <= 999) {
1956faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
1957faea38e7Sbellard     } else {
1958faea38e7Sbellard         base = 1024;
1959faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
1960faea38e7Sbellard             if (size < (10 * base)) {
1961faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
1962faea38e7Sbellard                          (double)size / base,
1963faea38e7Sbellard                          suffixes[i]);
1964faea38e7Sbellard                 break;
1965faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1966faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
1967faea38e7Sbellard                          ((size + (base >> 1)) / base),
1968faea38e7Sbellard                          suffixes[i]);
1969faea38e7Sbellard                 break;
1970faea38e7Sbellard             }
1971faea38e7Sbellard             base = base * 1024;
1972faea38e7Sbellard         }
1973faea38e7Sbellard     }
1974faea38e7Sbellard     return buf;
1975faea38e7Sbellard }
1976faea38e7Sbellard 
1977faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1978faea38e7Sbellard {
1979faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
19803b9f94e1Sbellard #ifdef _WIN32
19813b9f94e1Sbellard     struct tm *ptm;
19823b9f94e1Sbellard #else
1983faea38e7Sbellard     struct tm tm;
19843b9f94e1Sbellard #endif
1985faea38e7Sbellard     time_t ti;
1986faea38e7Sbellard     int64_t secs;
1987faea38e7Sbellard 
1988faea38e7Sbellard     if (!sn) {
1989faea38e7Sbellard         snprintf(buf, buf_size,
1990faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
1991faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1992faea38e7Sbellard     } else {
1993faea38e7Sbellard         ti = sn->date_sec;
19943b9f94e1Sbellard #ifdef _WIN32
19953b9f94e1Sbellard         ptm = localtime(&ti);
19963b9f94e1Sbellard         strftime(date_buf, sizeof(date_buf),
19973b9f94e1Sbellard                  "%Y-%m-%d %H:%M:%S", ptm);
19983b9f94e1Sbellard #else
1999faea38e7Sbellard         localtime_r(&ti, &tm);
2000faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
2001faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
20023b9f94e1Sbellard #endif
2003faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
2004faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
2005faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
2006faea38e7Sbellard                  (int)(secs / 3600),
2007faea38e7Sbellard                  (int)((secs / 60) % 60),
2008faea38e7Sbellard                  (int)(secs % 60),
2009faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
2010faea38e7Sbellard         snprintf(buf, buf_size,
2011faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2012faea38e7Sbellard                  sn->id_str, sn->name,
2013faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2014faea38e7Sbellard                  date_buf,
2015faea38e7Sbellard                  clock_buf);
2016faea38e7Sbellard     }
2017faea38e7Sbellard     return buf;
2018faea38e7Sbellard }
2019faea38e7Sbellard 
202083f64091Sbellard 
2021ea2384d3Sbellard /**************************************************************/
202283f64091Sbellard /* async I/Os */
2023ea2384d3Sbellard 
20243b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2025f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
202683f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
2027ea2384d3Sbellard {
202883f64091Sbellard     BlockDriver *drv = bs->drv;
2029a36e69ddSths     BlockDriverAIOCB *ret;
2030ea2384d3Sbellard 
2031bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2032bbf0a440SStefan Hajnoczi 
203319cb3738Sbellard     if (!drv)
2034ce1a14dcSpbrook         return NULL;
203571d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
203671d0770cSaliguori         return NULL;
203783f64091Sbellard 
2038f141eafeSaliguori     ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2039f141eafeSaliguori                               cb, opaque);
2040a36e69ddSths 
2041a36e69ddSths     if (ret) {
2042a36e69ddSths 	/* Update stats even though technically transfer has not happened. */
20436ea44308SJan Kiszka 	bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2044a36e69ddSths 	bs->rd_ops ++;
2045a36e69ddSths     }
2046a36e69ddSths 
2047a36e69ddSths     return ret;
204883f64091Sbellard }
204983f64091Sbellard 
20504dcafbb1SMarcelo Tosatti typedef struct BlockCompleteData {
20514dcafbb1SMarcelo Tosatti     BlockDriverCompletionFunc *cb;
20524dcafbb1SMarcelo Tosatti     void *opaque;
20534dcafbb1SMarcelo Tosatti     BlockDriverState *bs;
20544dcafbb1SMarcelo Tosatti     int64_t sector_num;
20554dcafbb1SMarcelo Tosatti     int nb_sectors;
20564dcafbb1SMarcelo Tosatti } BlockCompleteData;
20574dcafbb1SMarcelo Tosatti 
20584dcafbb1SMarcelo Tosatti static void block_complete_cb(void *opaque, int ret)
20594dcafbb1SMarcelo Tosatti {
20604dcafbb1SMarcelo Tosatti     BlockCompleteData *b = opaque;
20614dcafbb1SMarcelo Tosatti 
20624dcafbb1SMarcelo Tosatti     if (b->bs->dirty_bitmap) {
20634dcafbb1SMarcelo Tosatti         set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
20644dcafbb1SMarcelo Tosatti     }
20654dcafbb1SMarcelo Tosatti     b->cb(b->opaque, ret);
20664dcafbb1SMarcelo Tosatti     qemu_free(b);
20674dcafbb1SMarcelo Tosatti }
20684dcafbb1SMarcelo Tosatti 
20694dcafbb1SMarcelo Tosatti static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
20704dcafbb1SMarcelo Tosatti                                              int64_t sector_num,
20714dcafbb1SMarcelo Tosatti                                              int nb_sectors,
20724dcafbb1SMarcelo Tosatti                                              BlockDriverCompletionFunc *cb,
20734dcafbb1SMarcelo Tosatti                                              void *opaque)
20744dcafbb1SMarcelo Tosatti {
20754dcafbb1SMarcelo Tosatti     BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
20764dcafbb1SMarcelo Tosatti 
20774dcafbb1SMarcelo Tosatti     blkdata->bs = bs;
20784dcafbb1SMarcelo Tosatti     blkdata->cb = cb;
20794dcafbb1SMarcelo Tosatti     blkdata->opaque = opaque;
20804dcafbb1SMarcelo Tosatti     blkdata->sector_num = sector_num;
20814dcafbb1SMarcelo Tosatti     blkdata->nb_sectors = nb_sectors;
20824dcafbb1SMarcelo Tosatti 
20834dcafbb1SMarcelo Tosatti     return blkdata;
20844dcafbb1SMarcelo Tosatti }
20854dcafbb1SMarcelo Tosatti 
2086f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2087f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
208883f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
20897674e7bfSbellard {
209083f64091Sbellard     BlockDriver *drv = bs->drv;
2091a36e69ddSths     BlockDriverAIOCB *ret;
20924dcafbb1SMarcelo Tosatti     BlockCompleteData *blk_cb_data;
209383f64091Sbellard 
2094bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2095bbf0a440SStefan Hajnoczi 
209619cb3738Sbellard     if (!drv)
2097ce1a14dcSpbrook         return NULL;
209883f64091Sbellard     if (bs->read_only)
2099ce1a14dcSpbrook         return NULL;
210071d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
210171d0770cSaliguori         return NULL;
210283f64091Sbellard 
2103c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
21044dcafbb1SMarcelo Tosatti         blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
21054dcafbb1SMarcelo Tosatti                                          opaque);
21064dcafbb1SMarcelo Tosatti         cb = &block_complete_cb;
21074dcafbb1SMarcelo Tosatti         opaque = blk_cb_data;
21087cd1e32aSlirans@il.ibm.com     }
21097cd1e32aSlirans@il.ibm.com 
2110f141eafeSaliguori     ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2111f141eafeSaliguori                                cb, opaque);
2112a36e69ddSths 
2113a36e69ddSths     if (ret) {
2114a36e69ddSths         /* Update stats even though technically transfer has not happened. */
21156ea44308SJan Kiszka         bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2116a36e69ddSths         bs->wr_ops ++;
2117294cc35fSKevin Wolf         if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2118294cc35fSKevin Wolf             bs->wr_highest_sector = sector_num + nb_sectors - 1;
2119294cc35fSKevin Wolf         }
2120a36e69ddSths     }
2121a36e69ddSths 
2122a36e69ddSths     return ret;
212383f64091Sbellard }
212483f64091Sbellard 
212540b4f539SKevin Wolf 
212640b4f539SKevin Wolf typedef struct MultiwriteCB {
212740b4f539SKevin Wolf     int error;
212840b4f539SKevin Wolf     int num_requests;
212940b4f539SKevin Wolf     int num_callbacks;
213040b4f539SKevin Wolf     struct {
213140b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
213240b4f539SKevin Wolf         void *opaque;
213340b4f539SKevin Wolf         QEMUIOVector *free_qiov;
213440b4f539SKevin Wolf         void *free_buf;
213540b4f539SKevin Wolf     } callbacks[];
213640b4f539SKevin Wolf } MultiwriteCB;
213740b4f539SKevin Wolf 
213840b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
213940b4f539SKevin Wolf {
214040b4f539SKevin Wolf     int i;
214140b4f539SKevin Wolf 
214240b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
214340b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
21441e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
21451e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
21461e1ea48dSStefan Hajnoczi         }
214740b4f539SKevin Wolf         qemu_free(mcb->callbacks[i].free_qiov);
2148f8a83245SHerve Poussineau         qemu_vfree(mcb->callbacks[i].free_buf);
214940b4f539SKevin Wolf     }
215040b4f539SKevin Wolf }
215140b4f539SKevin Wolf 
215240b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
215340b4f539SKevin Wolf {
215440b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
215540b4f539SKevin Wolf 
21566d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
21576d519a5fSStefan Hajnoczi 
2158cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
215940b4f539SKevin Wolf         mcb->error = ret;
216040b4f539SKevin Wolf     }
216140b4f539SKevin Wolf 
216240b4f539SKevin Wolf     mcb->num_requests--;
216340b4f539SKevin Wolf     if (mcb->num_requests == 0) {
216440b4f539SKevin Wolf         multiwrite_user_cb(mcb);
216540b4f539SKevin Wolf         qemu_free(mcb);
216640b4f539SKevin Wolf     }
216740b4f539SKevin Wolf }
216840b4f539SKevin Wolf 
216940b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
217040b4f539SKevin Wolf {
217177be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
217277be4366SChristoph Hellwig 
217377be4366SChristoph Hellwig     /*
217477be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
217577be4366SChristoph Hellwig      * here as that could overflow the return value.
217677be4366SChristoph Hellwig      */
217777be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
217877be4366SChristoph Hellwig         return 1;
217977be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
218077be4366SChristoph Hellwig         return -1;
218177be4366SChristoph Hellwig     } else {
218277be4366SChristoph Hellwig         return 0;
218377be4366SChristoph Hellwig     }
218440b4f539SKevin Wolf }
218540b4f539SKevin Wolf 
218640b4f539SKevin Wolf /*
218740b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
218840b4f539SKevin Wolf  * requests that remain after merging.
218940b4f539SKevin Wolf  */
219040b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
219140b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
219240b4f539SKevin Wolf {
219340b4f539SKevin Wolf     int i, outidx;
219440b4f539SKevin Wolf 
219540b4f539SKevin Wolf     // Sort requests by start sector
219640b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
219740b4f539SKevin Wolf 
219840b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
219940b4f539SKevin Wolf     // filling up gaps with zero sectors.
220040b4f539SKevin Wolf     outidx = 0;
220140b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
220240b4f539SKevin Wolf         int merge = 0;
220340b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
220440b4f539SKevin Wolf 
220540b4f539SKevin Wolf         // This handles the cases that are valid for all block drivers, namely
220640b4f539SKevin Wolf         // exactly sequential writes and overlapping writes.
220740b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
220840b4f539SKevin Wolf             merge = 1;
220940b4f539SKevin Wolf         }
221040b4f539SKevin Wolf 
221140b4f539SKevin Wolf         // The block driver may decide that it makes sense to combine requests
221240b4f539SKevin Wolf         // even if there is a gap of some sectors between them. In this case,
221340b4f539SKevin Wolf         // the gap is filled with zeros (therefore only applicable for yet
221440b4f539SKevin Wolf         // unused space in format like qcow2).
221540b4f539SKevin Wolf         if (!merge && bs->drv->bdrv_merge_requests) {
221640b4f539SKevin Wolf             merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
221740b4f539SKevin Wolf         }
221840b4f539SKevin Wolf 
2219e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2220e2a305fbSChristoph Hellwig             merge = 0;
2221e2a305fbSChristoph Hellwig         }
2222e2a305fbSChristoph Hellwig 
222340b4f539SKevin Wolf         if (merge) {
222440b4f539SKevin Wolf             size_t size;
222540b4f539SKevin Wolf             QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
222640b4f539SKevin Wolf             qemu_iovec_init(qiov,
222740b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
222840b4f539SKevin Wolf 
222940b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
223040b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
223140b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
223240b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
223340b4f539SKevin Wolf 
223440b4f539SKevin Wolf             // We might need to add some zeros between the two requests
223540b4f539SKevin Wolf             if (reqs[i].sector > oldreq_last) {
223640b4f539SKevin Wolf                 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
223740b4f539SKevin Wolf                 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
223840b4f539SKevin Wolf                 memset(buf, 0, zero_bytes);
223940b4f539SKevin Wolf                 qemu_iovec_add(qiov, buf, zero_bytes);
224040b4f539SKevin Wolf                 mcb->callbacks[i].free_buf = buf;
224140b4f539SKevin Wolf             }
224240b4f539SKevin Wolf 
224340b4f539SKevin Wolf             // Add the second request
224440b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
224540b4f539SKevin Wolf 
2246cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
224740b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
224840b4f539SKevin Wolf 
224940b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
225040b4f539SKevin Wolf         } else {
225140b4f539SKevin Wolf             outidx++;
225240b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
225340b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
225440b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
225540b4f539SKevin Wolf         }
225640b4f539SKevin Wolf     }
225740b4f539SKevin Wolf 
225840b4f539SKevin Wolf     return outidx + 1;
225940b4f539SKevin Wolf }
226040b4f539SKevin Wolf 
226140b4f539SKevin Wolf /*
226240b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
226340b4f539SKevin Wolf  *
226440b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
226540b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
226640b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
226740b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
226840b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
226940b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
227040b4f539SKevin Wolf  *
227140b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
227240b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
227340b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
227440b4f539SKevin Wolf  */
227540b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
227640b4f539SKevin Wolf {
227740b4f539SKevin Wolf     BlockDriverAIOCB *acb;
227840b4f539SKevin Wolf     MultiwriteCB *mcb;
227940b4f539SKevin Wolf     int i;
228040b4f539SKevin Wolf 
228140b4f539SKevin Wolf     if (num_reqs == 0) {
228240b4f539SKevin Wolf         return 0;
228340b4f539SKevin Wolf     }
228440b4f539SKevin Wolf 
228540b4f539SKevin Wolf     // Create MultiwriteCB structure
228640b4f539SKevin Wolf     mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
228740b4f539SKevin Wolf     mcb->num_requests = 0;
228840b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
228940b4f539SKevin Wolf 
229040b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
229140b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
229240b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
229340b4f539SKevin Wolf     }
229440b4f539SKevin Wolf 
229540b4f539SKevin Wolf     // Check for mergable requests
229640b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
229740b4f539SKevin Wolf 
22986d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
22996d519a5fSStefan Hajnoczi 
2300453f9a16SKevin Wolf     /*
2301453f9a16SKevin Wolf      * Run the aio requests. As soon as one request can't be submitted
2302453f9a16SKevin Wolf      * successfully, fail all requests that are not yet submitted (we must
2303453f9a16SKevin Wolf      * return failure for all requests anyway)
2304453f9a16SKevin Wolf      *
2305453f9a16SKevin Wolf      * num_requests cannot be set to the right value immediately: If
2306453f9a16SKevin Wolf      * bdrv_aio_writev fails for some request, num_requests would be too high
2307453f9a16SKevin Wolf      * and therefore multiwrite_cb() would never recognize the multiwrite
2308453f9a16SKevin Wolf      * request as completed. We also cannot use the loop variable i to set it
2309453f9a16SKevin Wolf      * when the first request fails because the callback may already have been
2310453f9a16SKevin Wolf      * called for previously submitted requests. Thus, num_requests must be
2311453f9a16SKevin Wolf      * incremented for each request that is submitted.
2312453f9a16SKevin Wolf      *
2313453f9a16SKevin Wolf      * The problem that callbacks may be called early also means that we need
2314453f9a16SKevin Wolf      * to take care that num_requests doesn't become 0 before all requests are
2315453f9a16SKevin Wolf      * submitted - multiwrite_cb() would consider the multiwrite request
2316453f9a16SKevin Wolf      * completed. A dummy request that is "completed" by a manual call to
2317453f9a16SKevin Wolf      * multiwrite_cb() takes care of this.
2318453f9a16SKevin Wolf      */
2319453f9a16SKevin Wolf     mcb->num_requests = 1;
2320453f9a16SKevin Wolf 
23216d519a5fSStefan Hajnoczi     // Run the aio requests
232240b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
2323453f9a16SKevin Wolf         mcb->num_requests++;
232440b4f539SKevin Wolf         acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
232540b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
232640b4f539SKevin Wolf 
232740b4f539SKevin Wolf         if (acb == NULL) {
232840b4f539SKevin Wolf             // We can only fail the whole thing if no request has been
232940b4f539SKevin Wolf             // submitted yet. Otherwise we'll wait for the submitted AIOs to
233040b4f539SKevin Wolf             // complete and report the error in the callback.
2331453f9a16SKevin Wolf             if (i == 0) {
23326d519a5fSStefan Hajnoczi                 trace_bdrv_aio_multiwrite_earlyfail(mcb);
233340b4f539SKevin Wolf                 goto fail;
233440b4f539SKevin Wolf             } else {
23356d519a5fSStefan Hajnoczi                 trace_bdrv_aio_multiwrite_latefail(mcb, i);
23367eb58a6cSKevin Wolf                 multiwrite_cb(mcb, -EIO);
233740b4f539SKevin Wolf                 break;
233840b4f539SKevin Wolf             }
233940b4f539SKevin Wolf         }
234040b4f539SKevin Wolf     }
234140b4f539SKevin Wolf 
2342453f9a16SKevin Wolf     /* Complete the dummy request */
2343453f9a16SKevin Wolf     multiwrite_cb(mcb, 0);
2344453f9a16SKevin Wolf 
234540b4f539SKevin Wolf     return 0;
234640b4f539SKevin Wolf 
234740b4f539SKevin Wolf fail:
2348453f9a16SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
2349453f9a16SKevin Wolf         reqs[i].error = -EIO;
2350453f9a16SKevin Wolf     }
2351af474591SBruce Rogers     qemu_free(mcb);
235240b4f539SKevin Wolf     return -1;
235340b4f539SKevin Wolf }
235440b4f539SKevin Wolf 
2355b2e12bc6SChristoph Hellwig BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2356b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2357b2e12bc6SChristoph Hellwig {
2358b2e12bc6SChristoph Hellwig     BlockDriver *drv = bs->drv;
2359b2e12bc6SChristoph Hellwig 
2360016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2361016f5cf6SAlexander Graf         return bdrv_aio_noop_em(bs, cb, opaque);
2362016f5cf6SAlexander Graf     }
2363016f5cf6SAlexander Graf 
2364b2e12bc6SChristoph Hellwig     if (!drv)
2365b2e12bc6SChristoph Hellwig         return NULL;
2366b2e12bc6SChristoph Hellwig     return drv->bdrv_aio_flush(bs, cb, opaque);
2367b2e12bc6SChristoph Hellwig }
2368b2e12bc6SChristoph Hellwig 
236983f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
237083f64091Sbellard {
23716bbff9a0Saliguori     acb->pool->cancel(acb);
237283f64091Sbellard }
237383f64091Sbellard 
237483f64091Sbellard 
237583f64091Sbellard /**************************************************************/
237683f64091Sbellard /* async block device emulation */
237783f64091Sbellard 
2378c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
2379c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
2380c16b5a2cSChristoph Hellwig     QEMUBH *bh;
2381c16b5a2cSChristoph Hellwig     int ret;
2382c16b5a2cSChristoph Hellwig     /* vector translation state */
2383c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
2384c16b5a2cSChristoph Hellwig     uint8_t *bounce;
2385c16b5a2cSChristoph Hellwig     int is_write;
2386c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
2387c16b5a2cSChristoph Hellwig 
2388c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2389c16b5a2cSChristoph Hellwig {
2390b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
2391b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
23926a7ad299SDor Laor     qemu_bh_delete(acb->bh);
239336afc451SAvi Kivity     acb->bh = NULL;
2394c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
2395c16b5a2cSChristoph Hellwig }
2396c16b5a2cSChristoph Hellwig 
2397c16b5a2cSChristoph Hellwig static AIOPool bdrv_em_aio_pool = {
2398c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2399c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
2400c16b5a2cSChristoph Hellwig };
2401c16b5a2cSChristoph Hellwig 
240283f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
2403beac80cdSbellard {
2404ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
2405f141eafeSaliguori 
2406f141eafeSaliguori     if (!acb->is_write)
2407f141eafeSaliguori         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2408ceb42de8Saliguori     qemu_vfree(acb->bounce);
2409ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
24106a7ad299SDor Laor     qemu_bh_delete(acb->bh);
241136afc451SAvi Kivity     acb->bh = NULL;
2412ce1a14dcSpbrook     qemu_aio_release(acb);
2413beac80cdSbellard }
2414beac80cdSbellard 
2415f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2416f141eafeSaliguori                                             int64_t sector_num,
2417f141eafeSaliguori                                             QEMUIOVector *qiov,
2418f141eafeSaliguori                                             int nb_sectors,
2419f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
2420f141eafeSaliguori                                             void *opaque,
2421f141eafeSaliguori                                             int is_write)
2422f141eafeSaliguori 
2423ea2384d3Sbellard {
2424ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
242583f64091Sbellard 
2426c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2427f141eafeSaliguori     acb->is_write = is_write;
2428f141eafeSaliguori     acb->qiov = qiov;
2429e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
2430f141eafeSaliguori 
2431ce1a14dcSpbrook     if (!acb->bh)
2432ce1a14dcSpbrook         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2433f141eafeSaliguori 
2434f141eafeSaliguori     if (is_write) {
2435f141eafeSaliguori         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2436f141eafeSaliguori         acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2437f141eafeSaliguori     } else {
2438f141eafeSaliguori         acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2439f141eafeSaliguori     }
2440f141eafeSaliguori 
2441ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
2442f141eafeSaliguori 
2443ce1a14dcSpbrook     return &acb->common;
24447a6cba61Spbrook }
24457a6cba61Spbrook 
2446f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2447f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2448ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
244983f64091Sbellard {
2450f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
245183f64091Sbellard }
245283f64091Sbellard 
2453f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2454f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2455f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
2456f141eafeSaliguori {
2457f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2458f141eafeSaliguori }
2459f141eafeSaliguori 
2460b2e12bc6SChristoph Hellwig static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2461b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2462b2e12bc6SChristoph Hellwig {
2463b2e12bc6SChristoph Hellwig     BlockDriverAIOCBSync *acb;
2464b2e12bc6SChristoph Hellwig 
2465b2e12bc6SChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2466b2e12bc6SChristoph Hellwig     acb->is_write = 1; /* don't bounce in the completion hadler */
2467b2e12bc6SChristoph Hellwig     acb->qiov = NULL;
2468b2e12bc6SChristoph Hellwig     acb->bounce = NULL;
2469b2e12bc6SChristoph Hellwig     acb->ret = 0;
2470b2e12bc6SChristoph Hellwig 
2471b2e12bc6SChristoph Hellwig     if (!acb->bh)
2472b2e12bc6SChristoph Hellwig         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2473b2e12bc6SChristoph Hellwig 
2474b2e12bc6SChristoph Hellwig     bdrv_flush(bs);
2475b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
2476b2e12bc6SChristoph Hellwig     return &acb->common;
2477b2e12bc6SChristoph Hellwig }
2478b2e12bc6SChristoph Hellwig 
2479016f5cf6SAlexander Graf static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2480016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
2481016f5cf6SAlexander Graf {
2482016f5cf6SAlexander Graf     BlockDriverAIOCBSync *acb;
2483016f5cf6SAlexander Graf 
2484016f5cf6SAlexander Graf     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2485016f5cf6SAlexander Graf     acb->is_write = 1; /* don't bounce in the completion handler */
2486016f5cf6SAlexander Graf     acb->qiov = NULL;
2487016f5cf6SAlexander Graf     acb->bounce = NULL;
2488016f5cf6SAlexander Graf     acb->ret = 0;
2489016f5cf6SAlexander Graf 
2490016f5cf6SAlexander Graf     if (!acb->bh) {
2491016f5cf6SAlexander Graf         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2492016f5cf6SAlexander Graf     }
2493016f5cf6SAlexander Graf 
2494016f5cf6SAlexander Graf     qemu_bh_schedule(acb->bh);
2495016f5cf6SAlexander Graf     return &acb->common;
2496016f5cf6SAlexander Graf }
2497016f5cf6SAlexander Graf 
249883f64091Sbellard /**************************************************************/
249983f64091Sbellard /* sync block device emulation */
250083f64091Sbellard 
250183f64091Sbellard static void bdrv_rw_em_cb(void *opaque, int ret)
250283f64091Sbellard {
250383f64091Sbellard     *(int *)opaque = ret;
250483f64091Sbellard }
250583f64091Sbellard 
250683f64091Sbellard #define NOT_DONE 0x7fffffff
250783f64091Sbellard 
250883f64091Sbellard static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
250983f64091Sbellard                         uint8_t *buf, int nb_sectors)
251083f64091Sbellard {
2511ce1a14dcSpbrook     int async_ret;
2512ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2513f141eafeSaliguori     struct iovec iov;
2514f141eafeSaliguori     QEMUIOVector qiov;
251583f64091Sbellard 
251665d6b3d8SKevin Wolf     async_context_push();
251765d6b3d8SKevin Wolf 
251883f64091Sbellard     async_ret = NOT_DONE;
25193f4cb3d3Sblueswir1     iov.iov_base = (void *)buf;
2520eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2521f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2522f141eafeSaliguori     acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
252383f64091Sbellard         bdrv_rw_em_cb, &async_ret);
252465d6b3d8SKevin Wolf     if (acb == NULL) {
252565d6b3d8SKevin Wolf         async_ret = -1;
252665d6b3d8SKevin Wolf         goto fail;
252765d6b3d8SKevin Wolf     }
2528baf35cb9Saliguori 
252983f64091Sbellard     while (async_ret == NOT_DONE) {
253083f64091Sbellard         qemu_aio_wait();
253183f64091Sbellard     }
2532baf35cb9Saliguori 
253365d6b3d8SKevin Wolf 
253465d6b3d8SKevin Wolf fail:
253565d6b3d8SKevin Wolf     async_context_pop();
253683f64091Sbellard     return async_ret;
253783f64091Sbellard }
253883f64091Sbellard 
253983f64091Sbellard static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
254083f64091Sbellard                          const uint8_t *buf, int nb_sectors)
254183f64091Sbellard {
2542ce1a14dcSpbrook     int async_ret;
2543ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2544f141eafeSaliguori     struct iovec iov;
2545f141eafeSaliguori     QEMUIOVector qiov;
254683f64091Sbellard 
254765d6b3d8SKevin Wolf     async_context_push();
254865d6b3d8SKevin Wolf 
254983f64091Sbellard     async_ret = NOT_DONE;
2550f141eafeSaliguori     iov.iov_base = (void *)buf;
2551eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2552f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2553f141eafeSaliguori     acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
255483f64091Sbellard         bdrv_rw_em_cb, &async_ret);
255565d6b3d8SKevin Wolf     if (acb == NULL) {
255665d6b3d8SKevin Wolf         async_ret = -1;
255765d6b3d8SKevin Wolf         goto fail;
255865d6b3d8SKevin Wolf     }
255983f64091Sbellard     while (async_ret == NOT_DONE) {
256083f64091Sbellard         qemu_aio_wait();
256183f64091Sbellard     }
256265d6b3d8SKevin Wolf 
256365d6b3d8SKevin Wolf fail:
256465d6b3d8SKevin Wolf     async_context_pop();
256583f64091Sbellard     return async_ret;
256683f64091Sbellard }
2567ea2384d3Sbellard 
2568ea2384d3Sbellard void bdrv_init(void)
2569ea2384d3Sbellard {
25705efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
2571ea2384d3Sbellard }
2572ce1a14dcSpbrook 
2573eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
2574eb852011SMarkus Armbruster {
2575eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
2576eb852011SMarkus Armbruster     bdrv_init();
2577eb852011SMarkus Armbruster }
2578eb852011SMarkus Armbruster 
2579c16b5a2cSChristoph Hellwig void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
25806bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
25816bbff9a0Saliguori {
2582ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2583ce1a14dcSpbrook 
25846bbff9a0Saliguori     if (pool->free_aiocb) {
25856bbff9a0Saliguori         acb = pool->free_aiocb;
25866bbff9a0Saliguori         pool->free_aiocb = acb->next;
2587ce1a14dcSpbrook     } else {
25886bbff9a0Saliguori         acb = qemu_mallocz(pool->aiocb_size);
25896bbff9a0Saliguori         acb->pool = pool;
2590ce1a14dcSpbrook     }
2591ce1a14dcSpbrook     acb->bs = bs;
2592ce1a14dcSpbrook     acb->cb = cb;
2593ce1a14dcSpbrook     acb->opaque = opaque;
2594ce1a14dcSpbrook     return acb;
2595ce1a14dcSpbrook }
2596ce1a14dcSpbrook 
2597ce1a14dcSpbrook void qemu_aio_release(void *p)
2598ce1a14dcSpbrook {
25996bbff9a0Saliguori     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
26006bbff9a0Saliguori     AIOPool *pool = acb->pool;
26016bbff9a0Saliguori     acb->next = pool->free_aiocb;
26026bbff9a0Saliguori     pool->free_aiocb = acb;
2603ce1a14dcSpbrook }
260419cb3738Sbellard 
260519cb3738Sbellard /**************************************************************/
260619cb3738Sbellard /* removable device support */
260719cb3738Sbellard 
260819cb3738Sbellard /**
260919cb3738Sbellard  * Return TRUE if the media is present
261019cb3738Sbellard  */
261119cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
261219cb3738Sbellard {
261319cb3738Sbellard     BlockDriver *drv = bs->drv;
261419cb3738Sbellard     int ret;
261519cb3738Sbellard     if (!drv)
261619cb3738Sbellard         return 0;
261719cb3738Sbellard     if (!drv->bdrv_is_inserted)
26184be9762aSMarkus Armbruster         return !bs->tray_open;
261919cb3738Sbellard     ret = drv->bdrv_is_inserted(bs);
262019cb3738Sbellard     return ret;
262119cb3738Sbellard }
262219cb3738Sbellard 
262319cb3738Sbellard /**
262419cb3738Sbellard  * Return TRUE if the media changed since the last call to this
262519cb3738Sbellard  * function. It is currently only used for floppy disks
262619cb3738Sbellard  */
262719cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
262819cb3738Sbellard {
262919cb3738Sbellard     BlockDriver *drv = bs->drv;
263019cb3738Sbellard     int ret;
263119cb3738Sbellard 
263219cb3738Sbellard     if (!drv || !drv->bdrv_media_changed)
263319cb3738Sbellard         ret = -ENOTSUP;
263419cb3738Sbellard     else
263519cb3738Sbellard         ret = drv->bdrv_media_changed(bs);
263619cb3738Sbellard     if (ret == -ENOTSUP)
263719cb3738Sbellard         ret = bs->media_changed;
263819cb3738Sbellard     bs->media_changed = 0;
263919cb3738Sbellard     return ret;
264019cb3738Sbellard }
264119cb3738Sbellard 
264219cb3738Sbellard /**
264319cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
264419cb3738Sbellard  */
2645aea2a33cSMark McLoughlin int bdrv_eject(BlockDriverState *bs, int eject_flag)
264619cb3738Sbellard {
264719cb3738Sbellard     BlockDriver *drv = bs->drv;
264819cb3738Sbellard     int ret;
264919cb3738Sbellard 
2650aea2a33cSMark McLoughlin     if (bs->locked) {
2651aea2a33cSMark McLoughlin         return -EBUSY;
2652aea2a33cSMark McLoughlin     }
2653aea2a33cSMark McLoughlin 
265419cb3738Sbellard     if (!drv || !drv->bdrv_eject) {
265519cb3738Sbellard         ret = -ENOTSUP;
265619cb3738Sbellard     } else {
265719cb3738Sbellard         ret = drv->bdrv_eject(bs, eject_flag);
265819cb3738Sbellard     }
265919cb3738Sbellard     if (ret == -ENOTSUP) {
2660aea2a33cSMark McLoughlin         ret = 0;
266119cb3738Sbellard     }
26624be9762aSMarkus Armbruster     if (ret >= 0) {
26634be9762aSMarkus Armbruster         bs->tray_open = eject_flag;
26644be9762aSMarkus Armbruster     }
2665aea2a33cSMark McLoughlin 
2666aea2a33cSMark McLoughlin     return ret;
266719cb3738Sbellard }
266819cb3738Sbellard 
266919cb3738Sbellard int bdrv_is_locked(BlockDriverState *bs)
267019cb3738Sbellard {
267119cb3738Sbellard     return bs->locked;
267219cb3738Sbellard }
267319cb3738Sbellard 
267419cb3738Sbellard /**
267519cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
267619cb3738Sbellard  * to eject it manually).
267719cb3738Sbellard  */
267819cb3738Sbellard void bdrv_set_locked(BlockDriverState *bs, int locked)
267919cb3738Sbellard {
268019cb3738Sbellard     BlockDriver *drv = bs->drv;
268119cb3738Sbellard 
268219cb3738Sbellard     bs->locked = locked;
268319cb3738Sbellard     if (drv && drv->bdrv_set_locked) {
268419cb3738Sbellard         drv->bdrv_set_locked(bs, locked);
268519cb3738Sbellard     }
268619cb3738Sbellard }
2687985a03b0Sths 
2688985a03b0Sths /* needed for generic scsi interface */
2689985a03b0Sths 
2690985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2691985a03b0Sths {
2692985a03b0Sths     BlockDriver *drv = bs->drv;
2693985a03b0Sths 
2694985a03b0Sths     if (drv && drv->bdrv_ioctl)
2695985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
2696985a03b0Sths     return -ENOTSUP;
2697985a03b0Sths }
26987d780669Saliguori 
2699221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2700221f715dSaliguori         unsigned long int req, void *buf,
27017d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
27027d780669Saliguori {
2703221f715dSaliguori     BlockDriver *drv = bs->drv;
27047d780669Saliguori 
2705221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
2706221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2707221f715dSaliguori     return NULL;
27087d780669Saliguori }
2709e268ca52Saliguori 
27107cd1e32aSlirans@il.ibm.com 
27117cd1e32aSlirans@il.ibm.com 
2712e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
2713e268ca52Saliguori {
2714e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2715e268ca52Saliguori }
27167cd1e32aSlirans@il.ibm.com 
27177cd1e32aSlirans@il.ibm.com void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
27187cd1e32aSlirans@il.ibm.com {
27197cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
2720a55eb92cSJan Kiszka 
2721aaa0eb75SLiran Schour     bs->dirty_count = 0;
27227cd1e32aSlirans@il.ibm.com     if (enable) {
2723c6d22830SJan Kiszka         if (!bs->dirty_bitmap) {
2724c6d22830SJan Kiszka             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2725c6d22830SJan Kiszka                     BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2726c6d22830SJan Kiszka             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
27277cd1e32aSlirans@il.ibm.com 
27287cd1e32aSlirans@il.ibm.com             bs->dirty_bitmap = qemu_mallocz(bitmap_size);
27297cd1e32aSlirans@il.ibm.com         }
27307cd1e32aSlirans@il.ibm.com     } else {
2731c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
27327cd1e32aSlirans@il.ibm.com             qemu_free(bs->dirty_bitmap);
2733c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
27347cd1e32aSlirans@il.ibm.com         }
27357cd1e32aSlirans@il.ibm.com     }
27367cd1e32aSlirans@il.ibm.com }
27377cd1e32aSlirans@il.ibm.com 
27387cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
27397cd1e32aSlirans@il.ibm.com {
27406ea44308SJan Kiszka     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
27417cd1e32aSlirans@il.ibm.com 
2742c6d22830SJan Kiszka     if (bs->dirty_bitmap &&
2743c6d22830SJan Kiszka         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
27446d59fec1SMarcelo Tosatti         return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
27456d59fec1SMarcelo Tosatti             (1UL << (chunk % (sizeof(unsigned long) * 8))));
27467cd1e32aSlirans@il.ibm.com     } else {
27477cd1e32aSlirans@il.ibm.com         return 0;
27487cd1e32aSlirans@il.ibm.com     }
27497cd1e32aSlirans@il.ibm.com }
27507cd1e32aSlirans@il.ibm.com 
27517cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
27527cd1e32aSlirans@il.ibm.com                       int nr_sectors)
27537cd1e32aSlirans@il.ibm.com {
27547cd1e32aSlirans@il.ibm.com     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
27557cd1e32aSlirans@il.ibm.com }
2756aaa0eb75SLiran Schour 
2757aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2758aaa0eb75SLiran Schour {
2759aaa0eb75SLiran Schour     return bs->dirty_count;
2760aaa0eb75SLiran Schour }
2761f88e1a42SJes Sorensen 
2762f88e1a42SJes Sorensen int bdrv_img_create(const char *filename, const char *fmt,
2763f88e1a42SJes Sorensen                     const char *base_filename, const char *base_fmt,
2764f88e1a42SJes Sorensen                     char *options, uint64_t img_size, int flags)
2765f88e1a42SJes Sorensen {
2766f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
2767*792da93aSJes Sorensen     QEMUOptionParameter *backing_fmt, *backing_file;
2768f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
2769f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
2770f88e1a42SJes Sorensen     int ret = 0;
2771f88e1a42SJes Sorensen 
2772f88e1a42SJes Sorensen     /* Find driver and parse its options */
2773f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
2774f88e1a42SJes Sorensen     if (!drv) {
2775f88e1a42SJes Sorensen         error_report("Unknown file format '%s'", fmt);
2776f88e1a42SJes Sorensen         ret = -1;
2777f88e1a42SJes Sorensen         goto out;
2778f88e1a42SJes Sorensen     }
2779f88e1a42SJes Sorensen 
2780f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
2781f88e1a42SJes Sorensen     if (!proto_drv) {
2782f88e1a42SJes Sorensen         error_report("Unknown protocol '%s'", filename);
2783f88e1a42SJes Sorensen         ret = -1;
2784f88e1a42SJes Sorensen         goto out;
2785f88e1a42SJes Sorensen     }
2786f88e1a42SJes Sorensen 
2787f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
2788f88e1a42SJes Sorensen                                               drv->create_options);
2789f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
2790f88e1a42SJes Sorensen                                               proto_drv->create_options);
2791f88e1a42SJes Sorensen 
2792f88e1a42SJes Sorensen     /* Create parameter list with default values */
2793f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
2794f88e1a42SJes Sorensen 
2795f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
2796f88e1a42SJes Sorensen 
2797f88e1a42SJes Sorensen     /* Parse -o options */
2798f88e1a42SJes Sorensen     if (options) {
2799f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
2800f88e1a42SJes Sorensen         if (param == NULL) {
2801f88e1a42SJes Sorensen             error_report("Invalid options for file format '%s'.", fmt);
2802f88e1a42SJes Sorensen             ret = -1;
2803f88e1a42SJes Sorensen             goto out;
2804f88e1a42SJes Sorensen         }
2805f88e1a42SJes Sorensen     }
2806f88e1a42SJes Sorensen 
2807f88e1a42SJes Sorensen     if (base_filename) {
2808f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
2809f88e1a42SJes Sorensen                                  base_filename)) {
2810f88e1a42SJes Sorensen             error_report("Backing file not supported for file format '%s'",
2811f88e1a42SJes Sorensen                          fmt);
2812f88e1a42SJes Sorensen             ret = -1;
2813f88e1a42SJes Sorensen             goto out;
2814f88e1a42SJes Sorensen         }
2815f88e1a42SJes Sorensen     }
2816f88e1a42SJes Sorensen 
2817f88e1a42SJes Sorensen     if (base_fmt) {
2818f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
2819f88e1a42SJes Sorensen             error_report("Backing file format not supported for file "
2820f88e1a42SJes Sorensen                          "format '%s'", fmt);
2821f88e1a42SJes Sorensen             ret = -1;
2822f88e1a42SJes Sorensen             goto out;
2823f88e1a42SJes Sorensen         }
2824f88e1a42SJes Sorensen     }
2825f88e1a42SJes Sorensen 
2826*792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
2827*792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
2828*792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
2829*792da93aSJes Sorensen             error_report("Error: Trying to create an image with the "
2830*792da93aSJes Sorensen                          "same filename as the backing file");
2831*792da93aSJes Sorensen             ret = -1;
2832*792da93aSJes Sorensen             goto out;
2833*792da93aSJes Sorensen         }
2834*792da93aSJes Sorensen     }
2835*792da93aSJes Sorensen 
2836f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
2837f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
2838f88e1a42SJes Sorensen         if (!bdrv_find_format(backing_fmt->value.s)) {
2839f88e1a42SJes Sorensen             error_report("Unknown backing file format '%s'",
2840f88e1a42SJes Sorensen                          backing_fmt->value.s);
2841f88e1a42SJes Sorensen             ret = -1;
2842f88e1a42SJes Sorensen             goto out;
2843f88e1a42SJes Sorensen         }
2844f88e1a42SJes Sorensen     }
2845f88e1a42SJes Sorensen 
2846f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
2847f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
2848f88e1a42SJes Sorensen     if (get_option_parameter(param, BLOCK_OPT_SIZE)->value.n == -1) {
2849f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
2850f88e1a42SJes Sorensen             uint64_t size;
2851f88e1a42SJes Sorensen             const char *fmt = NULL;
2852f88e1a42SJes Sorensen             char buf[32];
2853f88e1a42SJes Sorensen 
2854f88e1a42SJes Sorensen             if (backing_fmt && backing_fmt->value.s) {
2855f88e1a42SJes Sorensen                 fmt = backing_fmt->value.s;
2856f88e1a42SJes Sorensen             }
2857f88e1a42SJes Sorensen 
2858f88e1a42SJes Sorensen             bs = bdrv_new("");
2859f88e1a42SJes Sorensen 
2860f88e1a42SJes Sorensen             ret = bdrv_open(bs, backing_file->value.s, flags, drv);
2861f88e1a42SJes Sorensen             if (ret < 0) {
2862f88e1a42SJes Sorensen                 error_report("Could not open '%s'", filename);
2863f88e1a42SJes Sorensen                 ret = -1;
2864f88e1a42SJes Sorensen                 goto out;
2865f88e1a42SJes Sorensen             }
2866f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
2867f88e1a42SJes Sorensen             size *= 512;
2868f88e1a42SJes Sorensen 
2869f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
2870f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
2871f88e1a42SJes Sorensen         } else {
2872f88e1a42SJes Sorensen             error_report("Image creation needs a size parameter");
2873f88e1a42SJes Sorensen             ret = -1;
2874f88e1a42SJes Sorensen             goto out;
2875f88e1a42SJes Sorensen         }
2876f88e1a42SJes Sorensen     }
2877f88e1a42SJes Sorensen 
2878f88e1a42SJes Sorensen     printf("Formatting '%s', fmt=%s ", filename, fmt);
2879f88e1a42SJes Sorensen     print_option_parameters(param);
2880f88e1a42SJes Sorensen     puts("");
2881f88e1a42SJes Sorensen 
2882f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
2883f88e1a42SJes Sorensen 
2884f88e1a42SJes Sorensen     if (ret < 0) {
2885f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
2886f88e1a42SJes Sorensen             error_report("Formatting or formatting option not supported for "
2887f88e1a42SJes Sorensen                          "file format '%s'", fmt);
2888f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
2889f88e1a42SJes Sorensen             error_report("The image size is too large for file format '%s'",
2890f88e1a42SJes Sorensen                          fmt);
2891f88e1a42SJes Sorensen         } else {
2892f88e1a42SJes Sorensen             error_report("%s: error while creating %s: %s", filename, fmt,
2893f88e1a42SJes Sorensen                          strerror(-ret));
2894f88e1a42SJes Sorensen         }
2895f88e1a42SJes Sorensen     }
2896f88e1a42SJes Sorensen 
2897f88e1a42SJes Sorensen out:
2898f88e1a42SJes Sorensen     free_option_parameters(create_options);
2899f88e1a42SJes Sorensen     free_option_parameters(param);
2900f88e1a42SJes Sorensen 
2901f88e1a42SJes Sorensen     if (bs) {
2902f88e1a42SJes Sorensen         bdrv_delete(bs);
2903f88e1a42SJes Sorensen     }
2904f88e1a42SJes Sorensen     if (ret) {
2905f88e1a42SJes Sorensen         return 1;
2906f88e1a42SJes Sorensen     }
2907f88e1a42SJes Sorensen     return 0;
2908f88e1a42SJes Sorensen }
2909