xref: /openbmc/qemu/block.c (revision 7d0d69509a966a5328e4fed7d0a942112d431c35)
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"
26376253ecSaliguori #include "monitor.h"
27ea2384d3Sbellard #include "block_int.h"
285efa9d5aSAnthony Liguori #include "module.h"
29d15e5465SLuiz Capitulino #include "qemu-objects.h"
30fc01f7e7Sbellard 
3171e72a19SJuan Quintela #ifdef CONFIG_BSD
327674e7bfSbellard #include <sys/types.h>
337674e7bfSbellard #include <sys/stat.h>
347674e7bfSbellard #include <sys/ioctl.h>
3572cf2d4fSBlue Swirl #include <sys/queue.h>
36c5e97233Sblueswir1 #ifndef __DragonFly__
377674e7bfSbellard #include <sys/disk.h>
387674e7bfSbellard #endif
39c5e97233Sblueswir1 #endif
407674e7bfSbellard 
4149dc768dSaliguori #ifdef _WIN32
4249dc768dSaliguori #include <windows.h>
4349dc768dSaliguori #endif
4449dc768dSaliguori 
45f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
46f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
47c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
48f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
49f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
51b2e12bc6SChristoph Hellwig static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
52b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque);
53016f5cf6SAlexander Graf static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
54016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque);
5583f64091Sbellard static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
5683f64091Sbellard                         uint8_t *buf, int nb_sectors);
5783f64091Sbellard static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
5883f64091Sbellard                          const uint8_t *buf, int nb_sectors);
59ec530c81Sbellard 
601b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
611b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
627ee930d0Sblueswir1 
638a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
648a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
65ea2384d3Sbellard 
66f9092b10SMarkus Armbruster /* The device to use for VM snapshots */
67f9092b10SMarkus Armbruster static BlockDriverState *bs_snapshots;
68f9092b10SMarkus Armbruster 
69eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
70eb852011SMarkus Armbruster static int use_bdrv_whitelist;
71eb852011SMarkus Armbruster 
7283f64091Sbellard int path_is_absolute(const char *path)
7383f64091Sbellard {
7483f64091Sbellard     const char *p;
7521664424Sbellard #ifdef _WIN32
7621664424Sbellard     /* specific case for names like: "\\.\d:" */
7721664424Sbellard     if (*path == '/' || *path == '\\')
7821664424Sbellard         return 1;
7921664424Sbellard #endif
8083f64091Sbellard     p = strchr(path, ':');
8183f64091Sbellard     if (p)
8283f64091Sbellard         p++;
8383f64091Sbellard     else
8483f64091Sbellard         p = path;
853b9f94e1Sbellard #ifdef _WIN32
863b9f94e1Sbellard     return (*p == '/' || *p == '\\');
873b9f94e1Sbellard #else
883b9f94e1Sbellard     return (*p == '/');
893b9f94e1Sbellard #endif
9083f64091Sbellard }
9183f64091Sbellard 
9283f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
9383f64091Sbellard    path to it by considering it is relative to base_path. URL are
9483f64091Sbellard    supported. */
9583f64091Sbellard void path_combine(char *dest, int dest_size,
9683f64091Sbellard                   const char *base_path,
9783f64091Sbellard                   const char *filename)
9883f64091Sbellard {
9983f64091Sbellard     const char *p, *p1;
10083f64091Sbellard     int len;
10183f64091Sbellard 
10283f64091Sbellard     if (dest_size <= 0)
10383f64091Sbellard         return;
10483f64091Sbellard     if (path_is_absolute(filename)) {
10583f64091Sbellard         pstrcpy(dest, dest_size, filename);
10683f64091Sbellard     } else {
10783f64091Sbellard         p = strchr(base_path, ':');
10883f64091Sbellard         if (p)
10983f64091Sbellard             p++;
11083f64091Sbellard         else
11183f64091Sbellard             p = base_path;
1123b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1133b9f94e1Sbellard #ifdef _WIN32
1143b9f94e1Sbellard         {
1153b9f94e1Sbellard             const char *p2;
1163b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1173b9f94e1Sbellard             if (!p1 || p2 > p1)
1183b9f94e1Sbellard                 p1 = p2;
1193b9f94e1Sbellard         }
1203b9f94e1Sbellard #endif
12183f64091Sbellard         if (p1)
12283f64091Sbellard             p1++;
12383f64091Sbellard         else
12483f64091Sbellard             p1 = base_path;
12583f64091Sbellard         if (p1 > p)
12683f64091Sbellard             p = p1;
12783f64091Sbellard         len = p - base_path;
12883f64091Sbellard         if (len > dest_size - 1)
12983f64091Sbellard             len = dest_size - 1;
13083f64091Sbellard         memcpy(dest, base_path, len);
13183f64091Sbellard         dest[len] = '\0';
13283f64091Sbellard         pstrcat(dest, dest_size, filename);
13383f64091Sbellard     }
13483f64091Sbellard }
13583f64091Sbellard 
1365efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
137ea2384d3Sbellard {
138f141eafeSaliguori     if (!bdrv->bdrv_aio_readv) {
13983f64091Sbellard         /* add AIO emulation layer */
140f141eafeSaliguori         bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
141f141eafeSaliguori         bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
142eda578e5Saliguori     } else if (!bdrv->bdrv_read) {
14383f64091Sbellard         /* add synchronous IO emulation layer */
14483f64091Sbellard         bdrv->bdrv_read = bdrv_read_em;
14583f64091Sbellard         bdrv->bdrv_write = bdrv_write_em;
14683f64091Sbellard     }
147b2e12bc6SChristoph Hellwig 
148b2e12bc6SChristoph Hellwig     if (!bdrv->bdrv_aio_flush)
149b2e12bc6SChristoph Hellwig         bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
150b2e12bc6SChristoph Hellwig 
1518a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
152ea2384d3Sbellard }
153b338082bSbellard 
154b338082bSbellard /* create a new block device (by default it is empty) */
155b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
156fc01f7e7Sbellard {
1571b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
158b338082bSbellard 
159b338082bSbellard     bs = qemu_mallocz(sizeof(BlockDriverState));
160b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
161ea2384d3Sbellard     if (device_name[0] != '\0') {
1621b7bdbc1SStefan Hajnoczi         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
163ea2384d3Sbellard     }
164b338082bSbellard     return bs;
165b338082bSbellard }
166b338082bSbellard 
167ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
168ea2384d3Sbellard {
169ea2384d3Sbellard     BlockDriver *drv1;
1708a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
1718a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
172ea2384d3Sbellard             return drv1;
173ea2384d3Sbellard         }
1748a22f02aSStefan Hajnoczi     }
175ea2384d3Sbellard     return NULL;
176ea2384d3Sbellard }
177ea2384d3Sbellard 
178eb852011SMarkus Armbruster static int bdrv_is_whitelisted(BlockDriver *drv)
179eb852011SMarkus Armbruster {
180eb852011SMarkus Armbruster     static const char *whitelist[] = {
181eb852011SMarkus Armbruster         CONFIG_BDRV_WHITELIST
182eb852011SMarkus Armbruster     };
183eb852011SMarkus Armbruster     const char **p;
184eb852011SMarkus Armbruster 
185eb852011SMarkus Armbruster     if (!whitelist[0])
186eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
187eb852011SMarkus Armbruster 
188eb852011SMarkus Armbruster     for (p = whitelist; *p; p++) {
189eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
190eb852011SMarkus Armbruster             return 1;
191eb852011SMarkus Armbruster         }
192eb852011SMarkus Armbruster     }
193eb852011SMarkus Armbruster     return 0;
194eb852011SMarkus Armbruster }
195eb852011SMarkus Armbruster 
196eb852011SMarkus Armbruster BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
197eb852011SMarkus Armbruster {
198eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
199eb852011SMarkus Armbruster     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
200eb852011SMarkus Armbruster }
201eb852011SMarkus Armbruster 
2020e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
2030e7e1989SKevin Wolf     QEMUOptionParameter *options)
204ea2384d3Sbellard {
205ea2384d3Sbellard     if (!drv->bdrv_create)
206ea2384d3Sbellard         return -ENOTSUP;
2070e7e1989SKevin Wolf 
2080e7e1989SKevin Wolf     return drv->bdrv_create(filename, options);
209ea2384d3Sbellard }
210ea2384d3Sbellard 
21184a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
21284a12e66SChristoph Hellwig {
21384a12e66SChristoph Hellwig     BlockDriver *drv;
21484a12e66SChristoph Hellwig 
215b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
21684a12e66SChristoph Hellwig     if (drv == NULL) {
21784a12e66SChristoph Hellwig         drv = bdrv_find_format("file");
21884a12e66SChristoph Hellwig     }
21984a12e66SChristoph Hellwig 
22084a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
22184a12e66SChristoph Hellwig }
22284a12e66SChristoph Hellwig 
223d5249393Sbellard #ifdef _WIN32
22495389c86Sbellard void get_tmp_filename(char *filename, int size)
225d5249393Sbellard {
2263b9f94e1Sbellard     char temp_dir[MAX_PATH];
2273b9f94e1Sbellard 
2283b9f94e1Sbellard     GetTempPath(MAX_PATH, temp_dir);
2293b9f94e1Sbellard     GetTempFileName(temp_dir, "qem", 0, filename);
230d5249393Sbellard }
231d5249393Sbellard #else
23295389c86Sbellard void get_tmp_filename(char *filename, int size)
233ea2384d3Sbellard {
234ea2384d3Sbellard     int fd;
2357ccfb2ebSblueswir1     const char *tmpdir;
236d5249393Sbellard     /* XXX: race condition possible */
2370badc1eeSaurel32     tmpdir = getenv("TMPDIR");
2380badc1eeSaurel32     if (!tmpdir)
2390badc1eeSaurel32         tmpdir = "/tmp";
2400badc1eeSaurel32     snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
241ea2384d3Sbellard     fd = mkstemp(filename);
242ea2384d3Sbellard     close(fd);
243ea2384d3Sbellard }
244d5249393Sbellard #endif
245ea2384d3Sbellard 
24619cb3738Sbellard #ifdef _WIN32
247f45512feSbellard static int is_windows_drive_prefix(const char *filename)
248f45512feSbellard {
249f45512feSbellard     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
250f45512feSbellard              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
251f45512feSbellard             filename[1] == ':');
252f45512feSbellard }
253f45512feSbellard 
254508c7cb3SChristoph Hellwig int is_windows_drive(const char *filename)
25519cb3738Sbellard {
256f45512feSbellard     if (is_windows_drive_prefix(filename) &&
257f45512feSbellard         filename[2] == '\0')
25819cb3738Sbellard         return 1;
25919cb3738Sbellard     if (strstart(filename, "\\\\.\\", NULL) ||
26019cb3738Sbellard         strstart(filename, "//./", NULL))
26119cb3738Sbellard         return 1;
26219cb3738Sbellard     return 0;
26319cb3738Sbellard }
26419cb3738Sbellard #endif
26519cb3738Sbellard 
266f3a5d3f8SChristoph Hellwig /*
267f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
268f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
269f3a5d3f8SChristoph Hellwig  */
270f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
271f3a5d3f8SChristoph Hellwig {
272508c7cb3SChristoph Hellwig     int score_max = 0, score;
273508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
274f3a5d3f8SChristoph Hellwig 
2758a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
276508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
277508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
278508c7cb3SChristoph Hellwig             if (score > score_max) {
279508c7cb3SChristoph Hellwig                 score_max = score;
280508c7cb3SChristoph Hellwig                 drv = d;
281f3a5d3f8SChristoph Hellwig             }
282508c7cb3SChristoph Hellwig         }
283f3a5d3f8SChristoph Hellwig     }
284f3a5d3f8SChristoph Hellwig 
285508c7cb3SChristoph Hellwig     return drv;
286f3a5d3f8SChristoph Hellwig }
287f3a5d3f8SChristoph Hellwig 
288b50cbabcSMORITA Kazutaka BlockDriver *bdrv_find_protocol(const char *filename)
28984a12e66SChristoph Hellwig {
29084a12e66SChristoph Hellwig     BlockDriver *drv1;
29184a12e66SChristoph Hellwig     char protocol[128];
29284a12e66SChristoph Hellwig     int len;
29384a12e66SChristoph Hellwig     const char *p;
29484a12e66SChristoph Hellwig 
29566f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
29666f82ceeSKevin Wolf 
29739508e7aSChristoph Hellwig     /*
29839508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
29939508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
30039508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
30139508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
30239508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
30339508e7aSChristoph Hellwig      */
30484a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
30539508e7aSChristoph Hellwig     if (drv1) {
30684a12e66SChristoph Hellwig         return drv1;
30784a12e66SChristoph Hellwig     }
30839508e7aSChristoph Hellwig 
30939508e7aSChristoph Hellwig #ifdef _WIN32
31039508e7aSChristoph Hellwig      if (is_windows_drive(filename) ||
31139508e7aSChristoph Hellwig          is_windows_drive_prefix(filename))
31239508e7aSChristoph Hellwig          return bdrv_find_format("file");
31339508e7aSChristoph Hellwig #endif
31439508e7aSChristoph Hellwig 
31539508e7aSChristoph Hellwig     p = strchr(filename, ':');
31639508e7aSChristoph Hellwig     if (!p) {
31739508e7aSChristoph Hellwig         return bdrv_find_format("file");
31839508e7aSChristoph Hellwig     }
31984a12e66SChristoph Hellwig     len = p - filename;
32084a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
32184a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
32284a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
32384a12e66SChristoph Hellwig     protocol[len] = '\0';
32484a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
32584a12e66SChristoph Hellwig         if (drv1->protocol_name &&
32684a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
32784a12e66SChristoph Hellwig             return drv1;
32884a12e66SChristoph Hellwig         }
32984a12e66SChristoph Hellwig     }
33084a12e66SChristoph Hellwig     return NULL;
33184a12e66SChristoph Hellwig }
33284a12e66SChristoph Hellwig 
333ea2384d3Sbellard static BlockDriver *find_image_format(const char *filename)
334ea2384d3Sbellard {
33583f64091Sbellard     int ret, score, score_max;
336ea2384d3Sbellard     BlockDriver *drv1, *drv;
33783f64091Sbellard     uint8_t buf[2048];
33883f64091Sbellard     BlockDriverState *bs;
339ea2384d3Sbellard 
340f5edb014SNaphtali Sprei     ret = bdrv_file_open(&bs, filename, 0);
34183f64091Sbellard     if (ret < 0)
3427674e7bfSbellard         return NULL;
343f8ea0b00SNicholas Bellinger 
34408a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
34508a00559SKevin Wolf     if (bs->sg || !bdrv_is_inserted(bs)) {
3461a396859SNicholas A. Bellinger         bdrv_delete(bs);
347f8ea0b00SNicholas Bellinger         return bdrv_find_format("raw");
3481a396859SNicholas A. Bellinger     }
349f8ea0b00SNicholas Bellinger 
35083f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
35183f64091Sbellard     bdrv_delete(bs);
352ea2384d3Sbellard     if (ret < 0) {
353ea2384d3Sbellard         return NULL;
354ea2384d3Sbellard     }
355ea2384d3Sbellard 
356ea2384d3Sbellard     score_max = 0;
35784a12e66SChristoph Hellwig     drv = NULL;
3588a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
35983f64091Sbellard         if (drv1->bdrv_probe) {
360ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
361ea2384d3Sbellard             if (score > score_max) {
362ea2384d3Sbellard                 score_max = score;
363ea2384d3Sbellard                 drv = drv1;
364ea2384d3Sbellard             }
365ea2384d3Sbellard         }
36683f64091Sbellard     }
367ea2384d3Sbellard     return drv;
368ea2384d3Sbellard }
369ea2384d3Sbellard 
37051762288SStefan Hajnoczi /**
37151762288SStefan Hajnoczi  * Set the current 'total_sectors' value
37251762288SStefan Hajnoczi  */
37351762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
37451762288SStefan Hajnoczi {
37551762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
37651762288SStefan Hajnoczi 
377396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
378396759adSNicholas Bellinger     if (bs->sg)
379396759adSNicholas Bellinger         return 0;
380396759adSNicholas Bellinger 
38151762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
38251762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
38351762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
38451762288SStefan Hajnoczi         if (length < 0) {
38551762288SStefan Hajnoczi             return length;
38651762288SStefan Hajnoczi         }
38751762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
38851762288SStefan Hajnoczi     }
38951762288SStefan Hajnoczi 
39051762288SStefan Hajnoczi     bs->total_sectors = hint;
39151762288SStefan Hajnoczi     return 0;
39251762288SStefan Hajnoczi }
39351762288SStefan Hajnoczi 
394b6ce07aaSKevin Wolf /*
39557915332SKevin Wolf  * Common part for opening disk images and files
39657915332SKevin Wolf  */
39757915332SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, const char *filename,
39857915332SKevin Wolf     int flags, BlockDriver *drv)
39957915332SKevin Wolf {
40057915332SKevin Wolf     int ret, open_flags;
40157915332SKevin Wolf 
40257915332SKevin Wolf     assert(drv != NULL);
40357915332SKevin Wolf 
40466f82ceeSKevin Wolf     bs->file = NULL;
40551762288SStefan Hajnoczi     bs->total_sectors = 0;
40657915332SKevin Wolf     bs->encrypted = 0;
40757915332SKevin Wolf     bs->valid_key = 0;
40857915332SKevin Wolf     bs->open_flags = flags;
40957915332SKevin Wolf     /* buffer_alignment defaulted to 512, drivers can change this value */
41057915332SKevin Wolf     bs->buffer_alignment = 512;
41157915332SKevin Wolf 
41257915332SKevin Wolf     pstrcpy(bs->filename, sizeof(bs->filename), filename);
41357915332SKevin Wolf 
41457915332SKevin Wolf     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
41557915332SKevin Wolf         return -ENOTSUP;
41657915332SKevin Wolf     }
41757915332SKevin Wolf 
41857915332SKevin Wolf     bs->drv = drv;
41957915332SKevin Wolf     bs->opaque = qemu_mallocz(drv->instance_size);
42057915332SKevin Wolf 
42157915332SKevin Wolf     /*
42257915332SKevin Wolf      * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
42357915332SKevin Wolf      * write cache to the guest.  We do need the fdatasync to flush
42457915332SKevin Wolf      * out transactions for block allocations, and we maybe have a
42557915332SKevin Wolf      * volatile write cache in our backing device to deal with.
42657915332SKevin Wolf      */
42757915332SKevin Wolf     if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
42857915332SKevin Wolf         bs->enable_write_cache = 1;
42957915332SKevin Wolf 
43057915332SKevin Wolf     /*
43157915332SKevin Wolf      * Clear flags that are internal to the block layer before opening the
43257915332SKevin Wolf      * image.
43357915332SKevin Wolf      */
43457915332SKevin Wolf     open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
43557915332SKevin Wolf 
43657915332SKevin Wolf     /*
43757915332SKevin Wolf      * Snapshots should be writeable.
43857915332SKevin Wolf      */
43957915332SKevin Wolf     if (bs->is_temporary) {
44057915332SKevin Wolf         open_flags |= BDRV_O_RDWR;
44157915332SKevin Wolf     }
44257915332SKevin Wolf 
44366f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
44466f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
44566f82ceeSKevin Wolf         ret = drv->bdrv_file_open(bs, filename, open_flags);
44666f82ceeSKevin Wolf     } else {
44766f82ceeSKevin Wolf         ret = bdrv_file_open(&bs->file, filename, open_flags);
44866f82ceeSKevin Wolf         if (ret >= 0) {
44966f82ceeSKevin Wolf             ret = drv->bdrv_open(bs, open_flags);
45066f82ceeSKevin Wolf         }
45166f82ceeSKevin Wolf     }
45266f82ceeSKevin Wolf 
45357915332SKevin Wolf     if (ret < 0) {
45457915332SKevin Wolf         goto free_and_fail;
45557915332SKevin Wolf     }
45657915332SKevin Wolf 
45757915332SKevin Wolf     bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
45851762288SStefan Hajnoczi 
45951762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
46051762288SStefan Hajnoczi     if (ret < 0) {
46151762288SStefan Hajnoczi         goto free_and_fail;
46257915332SKevin Wolf     }
46351762288SStefan Hajnoczi 
46457915332SKevin Wolf #ifndef _WIN32
46557915332SKevin Wolf     if (bs->is_temporary) {
46657915332SKevin Wolf         unlink(filename);
46757915332SKevin Wolf     }
46857915332SKevin Wolf #endif
46957915332SKevin Wolf     return 0;
47057915332SKevin Wolf 
47157915332SKevin Wolf free_and_fail:
47266f82ceeSKevin Wolf     if (bs->file) {
47366f82ceeSKevin Wolf         bdrv_delete(bs->file);
47466f82ceeSKevin Wolf         bs->file = NULL;
47566f82ceeSKevin Wolf     }
47657915332SKevin Wolf     qemu_free(bs->opaque);
47757915332SKevin Wolf     bs->opaque = NULL;
47857915332SKevin Wolf     bs->drv = NULL;
47957915332SKevin Wolf     return ret;
48057915332SKevin Wolf }
48157915332SKevin Wolf 
48257915332SKevin Wolf /*
483b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
484b6ce07aaSKevin Wolf  */
48583f64091Sbellard int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
486b338082bSbellard {
48783f64091Sbellard     BlockDriverState *bs;
4886db95603SChristoph Hellwig     BlockDriver *drv;
48983f64091Sbellard     int ret;
4903b0d4f61Sbellard 
491b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
4926db95603SChristoph Hellwig     if (!drv) {
4936db95603SChristoph Hellwig         return -ENOENT;
4946db95603SChristoph Hellwig     }
4956db95603SChristoph Hellwig 
49683f64091Sbellard     bs = bdrv_new("");
497b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
49883f64091Sbellard     if (ret < 0) {
49983f64091Sbellard         bdrv_delete(bs);
50083f64091Sbellard         return ret;
5013b0d4f61Sbellard     }
50271d0770cSaliguori     bs->growable = 1;
50383f64091Sbellard     *pbs = bs;
50483f64091Sbellard     return 0;
5053b0d4f61Sbellard }
5063b0d4f61Sbellard 
507b6ce07aaSKevin Wolf /*
508b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
509b6ce07aaSKevin Wolf  */
510d6e9098eSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
511ea2384d3Sbellard               BlockDriver *drv)
512ea2384d3Sbellard {
513b6ce07aaSKevin Wolf     int ret;
51433e3963eSbellard 
51583f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
516ea2384d3Sbellard         BlockDriverState *bs1;
517ea2384d3Sbellard         int64_t total_size;
5187c96d46eSaliguori         int is_protocol = 0;
51991a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
52091a073a9SKevin Wolf         QEMUOptionParameter *options;
521b6ce07aaSKevin Wolf         char tmp_filename[PATH_MAX];
522b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
52333e3963eSbellard 
524ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
525ea2384d3Sbellard            instead of opening 'filename' directly */
526ea2384d3Sbellard 
527ea2384d3Sbellard         /* if there is a backing file, use it */
528ea2384d3Sbellard         bs1 = bdrv_new("");
529d6e9098eSKevin Wolf         ret = bdrv_open(bs1, filename, 0, drv);
53051d7c00cSaliguori         if (ret < 0) {
531ea2384d3Sbellard             bdrv_delete(bs1);
53251d7c00cSaliguori             return ret;
533ea2384d3Sbellard         }
5343e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
5357c96d46eSaliguori 
5367c96d46eSaliguori         if (bs1->drv && bs1->drv->protocol_name)
5377c96d46eSaliguori             is_protocol = 1;
5387c96d46eSaliguori 
539ea2384d3Sbellard         bdrv_delete(bs1);
540ea2384d3Sbellard 
541ea2384d3Sbellard         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
5427c96d46eSaliguori 
5437c96d46eSaliguori         /* Real path is meaningless for protocols */
5447c96d46eSaliguori         if (is_protocol)
5457c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
5467c96d46eSaliguori                      "%s", filename);
547114cdfa9SKirill A. Shutemov         else if (!realpath(filename, backing_filename))
548114cdfa9SKirill A. Shutemov             return -errno;
5497c96d46eSaliguori 
55091a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
55191a073a9SKevin Wolf         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
55291a073a9SKevin Wolf 
5533e82990bSJes Sorensen         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
55491a073a9SKevin Wolf         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
55591a073a9SKevin Wolf         if (drv) {
55691a073a9SKevin Wolf             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
55791a073a9SKevin Wolf                 drv->format_name);
55891a073a9SKevin Wolf         }
55991a073a9SKevin Wolf 
56091a073a9SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
561d748768cSJan Kiszka         free_option_parameters(options);
56251d7c00cSaliguori         if (ret < 0) {
56351d7c00cSaliguori             return ret;
564ea2384d3Sbellard         }
56591a073a9SKevin Wolf 
566ea2384d3Sbellard         filename = tmp_filename;
56791a073a9SKevin Wolf         drv = bdrv_qcow2;
568ea2384d3Sbellard         bs->is_temporary = 1;
569ea2384d3Sbellard     }
570ea2384d3Sbellard 
571b6ce07aaSKevin Wolf     /* Find the right image format driver */
5726db95603SChristoph Hellwig     if (!drv) {
573ea2384d3Sbellard         drv = find_image_format(filename);
574ea2384d3Sbellard     }
5756987307cSChristoph Hellwig 
57651d7c00cSaliguori     if (!drv) {
57751d7c00cSaliguori         ret = -ENOENT;
57851d7c00cSaliguori         goto unlink_and_fail;
57983f64091Sbellard     }
580b6ce07aaSKevin Wolf 
581b6ce07aaSKevin Wolf     /* Open the image */
582b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
583b6ce07aaSKevin Wolf     if (ret < 0) {
5846987307cSChristoph Hellwig         goto unlink_and_fail;
5856987307cSChristoph Hellwig     }
5866987307cSChristoph Hellwig 
587b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
588b6ce07aaSKevin Wolf     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
589b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
590b6ce07aaSKevin Wolf         int back_flags;
591b6ce07aaSKevin Wolf         BlockDriver *back_drv = NULL;
592b6ce07aaSKevin Wolf 
593b6ce07aaSKevin Wolf         bs->backing_hd = bdrv_new("");
594b6ce07aaSKevin Wolf         path_combine(backing_filename, sizeof(backing_filename),
595b6ce07aaSKevin Wolf                      filename, bs->backing_file);
596b6ce07aaSKevin Wolf         if (bs->backing_format[0] != '\0')
597b6ce07aaSKevin Wolf             back_drv = bdrv_find_format(bs->backing_format);
598b6ce07aaSKevin Wolf 
599b6ce07aaSKevin Wolf         /* backing files always opened read-only */
600b6ce07aaSKevin Wolf         back_flags =
601b6ce07aaSKevin Wolf             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
602b6ce07aaSKevin Wolf 
603b6ce07aaSKevin Wolf         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
604b6ce07aaSKevin Wolf         if (ret < 0) {
605b6ce07aaSKevin Wolf             bdrv_close(bs);
606b6ce07aaSKevin Wolf             return ret;
607b6ce07aaSKevin Wolf         }
608b6ce07aaSKevin Wolf         if (bs->is_temporary) {
609b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
610b6ce07aaSKevin Wolf         } else {
611b6ce07aaSKevin Wolf             /* base image inherits from "parent" */
612b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = bs->keep_read_only;
613b6ce07aaSKevin Wolf         }
614b6ce07aaSKevin Wolf     }
615b6ce07aaSKevin Wolf 
616b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
617b6ce07aaSKevin Wolf         /* call the change callback */
618b6ce07aaSKevin Wolf         bs->media_changed = 1;
619b6ce07aaSKevin Wolf         if (bs->change_cb)
620b6ce07aaSKevin Wolf             bs->change_cb(bs->change_opaque);
621b6ce07aaSKevin Wolf     }
622b6ce07aaSKevin Wolf 
623b6ce07aaSKevin Wolf     return 0;
624b6ce07aaSKevin Wolf 
625b6ce07aaSKevin Wolf unlink_and_fail:
626b6ce07aaSKevin Wolf     if (bs->is_temporary) {
627b6ce07aaSKevin Wolf         unlink(filename);
628b6ce07aaSKevin Wolf     }
629b6ce07aaSKevin Wolf     return ret;
630b6ce07aaSKevin Wolf }
631b6ce07aaSKevin Wolf 
632fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
633fc01f7e7Sbellard {
63419cb3738Sbellard     if (bs->drv) {
635f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
636f9092b10SMarkus Armbruster             bs_snapshots = NULL;
637f9092b10SMarkus Armbruster         }
638557df6acSStefan Hajnoczi         if (bs->backing_hd) {
639ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
640557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
641557df6acSStefan Hajnoczi         }
642ea2384d3Sbellard         bs->drv->bdrv_close(bs);
643ea2384d3Sbellard         qemu_free(bs->opaque);
644ea2384d3Sbellard #ifdef _WIN32
645ea2384d3Sbellard         if (bs->is_temporary) {
646ea2384d3Sbellard             unlink(bs->filename);
647ea2384d3Sbellard         }
64867b915a5Sbellard #endif
649ea2384d3Sbellard         bs->opaque = NULL;
650ea2384d3Sbellard         bs->drv = NULL;
651b338082bSbellard 
65266f82ceeSKevin Wolf         if (bs->file != NULL) {
65366f82ceeSKevin Wolf             bdrv_close(bs->file);
65466f82ceeSKevin Wolf         }
65566f82ceeSKevin Wolf 
656b338082bSbellard         /* call the change callback */
65719cb3738Sbellard         bs->media_changed = 1;
658b338082bSbellard         if (bs->change_cb)
659b338082bSbellard             bs->change_cb(bs->change_opaque);
660b338082bSbellard     }
661b338082bSbellard }
662b338082bSbellard 
6632bc93fedSMORITA Kazutaka void bdrv_close_all(void)
6642bc93fedSMORITA Kazutaka {
6652bc93fedSMORITA Kazutaka     BlockDriverState *bs;
6662bc93fedSMORITA Kazutaka 
6672bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
6682bc93fedSMORITA Kazutaka         bdrv_close(bs);
6692bc93fedSMORITA Kazutaka     }
6702bc93fedSMORITA Kazutaka }
6712bc93fedSMORITA Kazutaka 
672b338082bSbellard void bdrv_delete(BlockDriverState *bs)
673b338082bSbellard {
67418846deeSMarkus Armbruster     assert(!bs->peer);
67518846deeSMarkus Armbruster 
6761b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
6771b7bdbc1SStefan Hajnoczi     if (bs->device_name[0] != '\0') {
6781b7bdbc1SStefan Hajnoczi         QTAILQ_REMOVE(&bdrv_states, bs, list);
6791b7bdbc1SStefan Hajnoczi     }
68034c6f050Saurel32 
681b338082bSbellard     bdrv_close(bs);
68266f82ceeSKevin Wolf     if (bs->file != NULL) {
68366f82ceeSKevin Wolf         bdrv_delete(bs->file);
68466f82ceeSKevin Wolf     }
68566f82ceeSKevin Wolf 
686f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
687b338082bSbellard     qemu_free(bs);
688fc01f7e7Sbellard }
689fc01f7e7Sbellard 
69018846deeSMarkus Armbruster int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
69118846deeSMarkus Armbruster {
69218846deeSMarkus Armbruster     if (bs->peer) {
69318846deeSMarkus Armbruster         return -EBUSY;
69418846deeSMarkus Armbruster     }
69518846deeSMarkus Armbruster     bs->peer = qdev;
69618846deeSMarkus Armbruster     return 0;
69718846deeSMarkus Armbruster }
69818846deeSMarkus Armbruster 
69918846deeSMarkus Armbruster void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
70018846deeSMarkus Armbruster {
70118846deeSMarkus Armbruster     assert(bs->peer == qdev);
70218846deeSMarkus Armbruster     bs->peer = NULL;
70318846deeSMarkus Armbruster }
70418846deeSMarkus Armbruster 
70518846deeSMarkus Armbruster DeviceState *bdrv_get_attached(BlockDriverState *bs)
70618846deeSMarkus Armbruster {
70718846deeSMarkus Armbruster     return bs->peer;
70818846deeSMarkus Armbruster }
70918846deeSMarkus Armbruster 
710e97fc193Saliguori /*
711e97fc193Saliguori  * Run consistency checks on an image
712e97fc193Saliguori  *
713e97fc193Saliguori  * Returns the number of errors or -errno when an internal error occurs
714e97fc193Saliguori  */
715e97fc193Saliguori int bdrv_check(BlockDriverState *bs)
716e97fc193Saliguori {
717e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
718e97fc193Saliguori         return -ENOTSUP;
719e97fc193Saliguori     }
720e97fc193Saliguori 
721e97fc193Saliguori     return bs->drv->bdrv_check(bs);
722e97fc193Saliguori }
723e97fc193Saliguori 
72433e3963eSbellard /* commit COW file into the raw image */
72533e3963eSbellard int bdrv_commit(BlockDriverState *bs)
72633e3963eSbellard {
72719cb3738Sbellard     BlockDriver *drv = bs->drv;
72883f64091Sbellard     int64_t i, total_sectors;
7294dca4b63SNaphtali Sprei     int n, j, ro, open_flags;
7304dca4b63SNaphtali Sprei     int ret = 0, rw_ret = 0;
731eb5a3165SJes Sorensen     unsigned char sector[BDRV_SECTOR_SIZE];
7324dca4b63SNaphtali Sprei     char filename[1024];
7334dca4b63SNaphtali Sprei     BlockDriverState *bs_rw, *bs_ro;
73433e3963eSbellard 
73519cb3738Sbellard     if (!drv)
73619cb3738Sbellard         return -ENOMEDIUM;
73733e3963eSbellard 
7384dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
7394dca4b63SNaphtali Sprei         return -ENOTSUP;
7404dca4b63SNaphtali Sprei     }
7414dca4b63SNaphtali Sprei 
7424dca4b63SNaphtali Sprei     if (bs->backing_hd->keep_read_only) {
743ea2384d3Sbellard         return -EACCES;
74433e3963eSbellard     }
74533e3963eSbellard 
7464dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
7474dca4b63SNaphtali Sprei     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
7484dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
7494dca4b63SNaphtali Sprei 
7504dca4b63SNaphtali Sprei     if (ro) {
7514dca4b63SNaphtali Sprei         /* re-open as RW */
7524dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
7534dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
7544dca4b63SNaphtali Sprei         bs_rw = bdrv_new("");
755c3349197SKevin Wolf         rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR, drv);
7564dca4b63SNaphtali Sprei         if (rw_ret < 0) {
7574dca4b63SNaphtali Sprei             bdrv_delete(bs_rw);
7584dca4b63SNaphtali Sprei             /* try to re-open read-only */
7594dca4b63SNaphtali Sprei             bs_ro = bdrv_new("");
760c3349197SKevin Wolf             ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
7614dca4b63SNaphtali Sprei             if (ret < 0) {
7624dca4b63SNaphtali Sprei                 bdrv_delete(bs_ro);
7634dca4b63SNaphtali Sprei                 /* drive not functional anymore */
7644dca4b63SNaphtali Sprei                 bs->drv = NULL;
7654dca4b63SNaphtali Sprei                 return ret;
7664dca4b63SNaphtali Sprei             }
7674dca4b63SNaphtali Sprei             bs->backing_hd = bs_ro;
7684dca4b63SNaphtali Sprei             return rw_ret;
7694dca4b63SNaphtali Sprei         }
7704dca4b63SNaphtali Sprei         bs->backing_hd = bs_rw;
771ea2384d3Sbellard     }
772ea2384d3Sbellard 
7736ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
77483f64091Sbellard     for (i = 0; i < total_sectors;) {
77519cb3738Sbellard         if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
776ea2384d3Sbellard             for(j = 0; j < n; j++) {
77733e3963eSbellard                 if (bdrv_read(bs, i, sector, 1) != 0) {
7784dca4b63SNaphtali Sprei                     ret = -EIO;
7794dca4b63SNaphtali Sprei                     goto ro_cleanup;
78033e3963eSbellard                 }
78133e3963eSbellard 
782ea2384d3Sbellard                 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
7834dca4b63SNaphtali Sprei                     ret = -EIO;
7844dca4b63SNaphtali Sprei                     goto ro_cleanup;
78533e3963eSbellard                 }
786ea2384d3Sbellard                 i++;
787ea2384d3Sbellard 	    }
788ea2384d3Sbellard 	} else {
789ea2384d3Sbellard             i += n;
79033e3963eSbellard         }
79133e3963eSbellard     }
79295389c86Sbellard 
7931d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
7941d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
7951d44952fSChristoph Hellwig         bdrv_flush(bs);
7961d44952fSChristoph Hellwig     }
79795389c86Sbellard 
7983f5075aeSChristoph Hellwig     /*
7993f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
8003f5075aeSChristoph Hellwig      * stable on disk.
8013f5075aeSChristoph Hellwig      */
8023f5075aeSChristoph Hellwig     if (bs->backing_hd)
8033f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
8044dca4b63SNaphtali Sprei 
8054dca4b63SNaphtali Sprei ro_cleanup:
8064dca4b63SNaphtali Sprei 
8074dca4b63SNaphtali Sprei     if (ro) {
8084dca4b63SNaphtali Sprei         /* re-open as RO */
8094dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
8104dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
8114dca4b63SNaphtali Sprei         bs_ro = bdrv_new("");
812c3349197SKevin Wolf         ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
8134dca4b63SNaphtali Sprei         if (ret < 0) {
8144dca4b63SNaphtali Sprei             bdrv_delete(bs_ro);
8154dca4b63SNaphtali Sprei             /* drive not functional anymore */
8164dca4b63SNaphtali Sprei             bs->drv = NULL;
8174dca4b63SNaphtali Sprei             return ret;
8184dca4b63SNaphtali Sprei         }
8194dca4b63SNaphtali Sprei         bs->backing_hd = bs_ro;
8204dca4b63SNaphtali Sprei         bs->backing_hd->keep_read_only = 0;
8214dca4b63SNaphtali Sprei     }
8224dca4b63SNaphtali Sprei 
8231d44952fSChristoph Hellwig     return ret;
82433e3963eSbellard }
82533e3963eSbellard 
8266ab4b5abSMarkus Armbruster void bdrv_commit_all(void)
8276ab4b5abSMarkus Armbruster {
8286ab4b5abSMarkus Armbruster     BlockDriverState *bs;
8296ab4b5abSMarkus Armbruster 
8306ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
8316ab4b5abSMarkus Armbruster         bdrv_commit(bs);
8326ab4b5abSMarkus Armbruster     }
8336ab4b5abSMarkus Armbruster }
8346ab4b5abSMarkus Armbruster 
835756e6736SKevin Wolf /*
836756e6736SKevin Wolf  * Return values:
837756e6736SKevin Wolf  * 0        - success
838756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
839756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
840756e6736SKevin Wolf  *            image file header
841756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
842756e6736SKevin Wolf  */
843756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
844756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
845756e6736SKevin Wolf {
846756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
847756e6736SKevin Wolf 
848756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
849756e6736SKevin Wolf         return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
850756e6736SKevin Wolf     } else {
851756e6736SKevin Wolf         return -ENOTSUP;
852756e6736SKevin Wolf     }
853756e6736SKevin Wolf }
854756e6736SKevin Wolf 
85571d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
85671d0770cSaliguori                                    size_t size)
85771d0770cSaliguori {
85871d0770cSaliguori     int64_t len;
85971d0770cSaliguori 
86071d0770cSaliguori     if (!bdrv_is_inserted(bs))
86171d0770cSaliguori         return -ENOMEDIUM;
86271d0770cSaliguori 
86371d0770cSaliguori     if (bs->growable)
86471d0770cSaliguori         return 0;
86571d0770cSaliguori 
86671d0770cSaliguori     len = bdrv_getlength(bs);
86771d0770cSaliguori 
868fbb7b4e0SKevin Wolf     if (offset < 0)
869fbb7b4e0SKevin Wolf         return -EIO;
870fbb7b4e0SKevin Wolf 
871fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
87271d0770cSaliguori         return -EIO;
87371d0770cSaliguori 
87471d0770cSaliguori     return 0;
87571d0770cSaliguori }
87671d0770cSaliguori 
87771d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
87871d0770cSaliguori                               int nb_sectors)
87971d0770cSaliguori {
880eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
881eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
88271d0770cSaliguori }
88371d0770cSaliguori 
88419cb3738Sbellard /* return < 0 if error. See bdrv_write() for the return codes */
885fc01f7e7Sbellard int bdrv_read(BlockDriverState *bs, int64_t sector_num,
886fc01f7e7Sbellard               uint8_t *buf, int nb_sectors)
887fc01f7e7Sbellard {
888ea2384d3Sbellard     BlockDriver *drv = bs->drv;
889fc01f7e7Sbellard 
89019cb3738Sbellard     if (!drv)
89119cb3738Sbellard         return -ENOMEDIUM;
89271d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
89371d0770cSaliguori         return -EIO;
894b338082bSbellard 
89583f64091Sbellard     return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
89683f64091Sbellard }
897fc01f7e7Sbellard 
8987cd1e32aSlirans@il.ibm.com static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
8997cd1e32aSlirans@il.ibm.com                              int nb_sectors, int dirty)
9007cd1e32aSlirans@il.ibm.com {
9017cd1e32aSlirans@il.ibm.com     int64_t start, end;
902c6d22830SJan Kiszka     unsigned long val, idx, bit;
903a55eb92cSJan Kiszka 
9046ea44308SJan Kiszka     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
905c6d22830SJan Kiszka     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
9067cd1e32aSlirans@il.ibm.com 
9077cd1e32aSlirans@il.ibm.com     for (; start <= end; start++) {
908c6d22830SJan Kiszka         idx = start / (sizeof(unsigned long) * 8);
909c6d22830SJan Kiszka         bit = start % (sizeof(unsigned long) * 8);
910c6d22830SJan Kiszka         val = bs->dirty_bitmap[idx];
911c6d22830SJan Kiszka         if (dirty) {
912aaa0eb75SLiran Schour             if (!(val & (1 << bit))) {
913aaa0eb75SLiran Schour                 bs->dirty_count++;
914c6d22830SJan Kiszka                 val |= 1 << bit;
915aaa0eb75SLiran Schour             }
916c6d22830SJan Kiszka         } else {
917aaa0eb75SLiran Schour             if (val & (1 << bit)) {
918aaa0eb75SLiran Schour                 bs->dirty_count--;
919c6d22830SJan Kiszka                 val &= ~(1 << bit);
920c6d22830SJan Kiszka             }
921aaa0eb75SLiran Schour         }
922c6d22830SJan Kiszka         bs->dirty_bitmap[idx] = val;
9237cd1e32aSlirans@il.ibm.com     }
9247cd1e32aSlirans@il.ibm.com }
9257cd1e32aSlirans@il.ibm.com 
92619cb3738Sbellard /* Return < 0 if error. Important errors are:
92719cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
92819cb3738Sbellard   -ENOMEDIUM   No media inserted.
92919cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
93019cb3738Sbellard   -EACCES      Trying to write a read-only device
93119cb3738Sbellard */
932fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
933fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
934fc01f7e7Sbellard {
93583f64091Sbellard     BlockDriver *drv = bs->drv;
93619cb3738Sbellard     if (!bs->drv)
93719cb3738Sbellard         return -ENOMEDIUM;
9380849bf08Sbellard     if (bs->read_only)
93919cb3738Sbellard         return -EACCES;
94071d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
94171d0770cSaliguori         return -EIO;
94271d0770cSaliguori 
943c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
9447cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
9457cd1e32aSlirans@il.ibm.com     }
9467cd1e32aSlirans@il.ibm.com 
947294cc35fSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
948294cc35fSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
949294cc35fSKevin Wolf     }
950294cc35fSKevin Wolf 
95183f64091Sbellard     return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
95283f64091Sbellard }
95383f64091Sbellard 
954eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
955eda578e5Saliguori                void *buf, int count1)
95683f64091Sbellard {
9576ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
95883f64091Sbellard     int len, nb_sectors, count;
95983f64091Sbellard     int64_t sector_num;
9609a8c4cceSKevin Wolf     int ret;
96183f64091Sbellard 
96283f64091Sbellard     count = count1;
96383f64091Sbellard     /* first read to align to sector start */
9646ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
96583f64091Sbellard     if (len > count)
96683f64091Sbellard         len = count;
9676ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
96883f64091Sbellard     if (len > 0) {
9699a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
9709a8c4cceSKevin Wolf             return ret;
9716ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
97283f64091Sbellard         count -= len;
97383f64091Sbellard         if (count == 0)
97483f64091Sbellard             return count1;
97583f64091Sbellard         sector_num++;
97683f64091Sbellard         buf += len;
97783f64091Sbellard     }
97883f64091Sbellard 
97983f64091Sbellard     /* read the sectors "in place" */
9806ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
98183f64091Sbellard     if (nb_sectors > 0) {
9829a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
9839a8c4cceSKevin Wolf             return ret;
98483f64091Sbellard         sector_num += nb_sectors;
9856ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
98683f64091Sbellard         buf += len;
98783f64091Sbellard         count -= len;
98883f64091Sbellard     }
98983f64091Sbellard 
99083f64091Sbellard     /* add data from the last sector */
99183f64091Sbellard     if (count > 0) {
9929a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
9939a8c4cceSKevin Wolf             return ret;
99483f64091Sbellard         memcpy(buf, tmp_buf, count);
99583f64091Sbellard     }
99683f64091Sbellard     return count1;
99783f64091Sbellard }
99883f64091Sbellard 
999eda578e5Saliguori int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1000eda578e5Saliguori                 const void *buf, int count1)
100183f64091Sbellard {
10026ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
100383f64091Sbellard     int len, nb_sectors, count;
100483f64091Sbellard     int64_t sector_num;
10059a8c4cceSKevin Wolf     int ret;
100683f64091Sbellard 
100783f64091Sbellard     count = count1;
100883f64091Sbellard     /* first write to align to sector start */
10096ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
101083f64091Sbellard     if (len > count)
101183f64091Sbellard         len = count;
10126ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
101383f64091Sbellard     if (len > 0) {
10149a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10159a8c4cceSKevin Wolf             return ret;
10166ea44308SJan Kiszka         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
10179a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
10189a8c4cceSKevin Wolf             return ret;
101983f64091Sbellard         count -= len;
102083f64091Sbellard         if (count == 0)
102183f64091Sbellard             return count1;
102283f64091Sbellard         sector_num++;
102383f64091Sbellard         buf += len;
102483f64091Sbellard     }
102583f64091Sbellard 
102683f64091Sbellard     /* write the sectors "in place" */
10276ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
102883f64091Sbellard     if (nb_sectors > 0) {
10299a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
10309a8c4cceSKevin Wolf             return ret;
103183f64091Sbellard         sector_num += nb_sectors;
10326ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
103383f64091Sbellard         buf += len;
103483f64091Sbellard         count -= len;
103583f64091Sbellard     }
103683f64091Sbellard 
103783f64091Sbellard     /* add data from the last sector */
103883f64091Sbellard     if (count > 0) {
10399a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
10409a8c4cceSKevin Wolf             return ret;
104183f64091Sbellard         memcpy(tmp_buf, buf, count);
10429a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
10439a8c4cceSKevin Wolf             return ret;
104483f64091Sbellard     }
104583f64091Sbellard     return count1;
104683f64091Sbellard }
104783f64091Sbellard 
1048f08145feSKevin Wolf /*
1049f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1050f08145feSKevin Wolf  * request (acts as a barrier)
1051f08145feSKevin Wolf  *
1052f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1053f08145feSKevin Wolf  */
1054f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1055f08145feSKevin Wolf     const void *buf, int count)
1056f08145feSKevin Wolf {
1057f08145feSKevin Wolf     int ret;
1058f08145feSKevin Wolf 
1059f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
1060f08145feSKevin Wolf     if (ret < 0) {
1061f08145feSKevin Wolf         return ret;
1062f08145feSKevin Wolf     }
1063f08145feSKevin Wolf 
1064f08145feSKevin Wolf     /* No flush needed for cache=writethrough, it uses O_DSYNC */
1065f08145feSKevin Wolf     if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1066f08145feSKevin Wolf         bdrv_flush(bs);
1067f08145feSKevin Wolf     }
1068f08145feSKevin Wolf 
1069f08145feSKevin Wolf     return 0;
1070f08145feSKevin Wolf }
1071f08145feSKevin Wolf 
1072f08145feSKevin Wolf /*
1073f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1074f08145feSKevin Wolf  * request (acts as a barrier)
1075f08145feSKevin Wolf  *
1076f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1077f08145feSKevin Wolf  */
1078f08145feSKevin Wolf int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1079f08145feSKevin Wolf     const uint8_t *buf, int nb_sectors)
1080f08145feSKevin Wolf {
1081f08145feSKevin Wolf     return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1082f08145feSKevin Wolf         buf, BDRV_SECTOR_SIZE * nb_sectors);
1083f08145feSKevin Wolf }
1084f08145feSKevin Wolf 
108583f64091Sbellard /**
108683f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
108783f64091Sbellard  */
108883f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
108983f64091Sbellard {
109083f64091Sbellard     BlockDriver *drv = bs->drv;
109151762288SStefan Hajnoczi     int ret;
109283f64091Sbellard     if (!drv)
109319cb3738Sbellard         return -ENOMEDIUM;
109483f64091Sbellard     if (!drv->bdrv_truncate)
109583f64091Sbellard         return -ENOTSUP;
109659f2689dSNaphtali Sprei     if (bs->read_only)
109759f2689dSNaphtali Sprei         return -EACCES;
109851762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
109951762288SStefan Hajnoczi     if (ret == 0) {
110051762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
110151762288SStefan Hajnoczi     }
110251762288SStefan Hajnoczi     return ret;
110383f64091Sbellard }
110483f64091Sbellard 
110583f64091Sbellard /**
110683f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
110783f64091Sbellard  */
110883f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
110983f64091Sbellard {
111083f64091Sbellard     BlockDriver *drv = bs->drv;
111183f64091Sbellard     if (!drv)
111219cb3738Sbellard         return -ENOMEDIUM;
111351762288SStefan Hajnoczi 
111451762288SStefan Hajnoczi     /* Fixed size devices use the total_sectors value for speed instead of
111551762288SStefan Hajnoczi        issuing a length query (like lseek) on each call.  Also, legacy block
111651762288SStefan Hajnoczi        drivers don't provide a bdrv_getlength function and must use
111751762288SStefan Hajnoczi        total_sectors. */
111851762288SStefan Hajnoczi     if (!bs->growable || !drv->bdrv_getlength) {
11196ea44308SJan Kiszka         return bs->total_sectors * BDRV_SECTOR_SIZE;
112083f64091Sbellard     }
112183f64091Sbellard     return drv->bdrv_getlength(bs);
1122fc01f7e7Sbellard }
1123fc01f7e7Sbellard 
112419cb3738Sbellard /* return 0 as number of sectors if no device present or error */
112596b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1126fc01f7e7Sbellard {
112719cb3738Sbellard     int64_t length;
112819cb3738Sbellard     length = bdrv_getlength(bs);
112919cb3738Sbellard     if (length < 0)
113019cb3738Sbellard         length = 0;
113119cb3738Sbellard     else
11326ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
113319cb3738Sbellard     *nb_sectors_ptr = length;
1134fc01f7e7Sbellard }
1135cf98951bSbellard 
1136f3d54fc4Saliguori struct partition {
1137f3d54fc4Saliguori         uint8_t boot_ind;           /* 0x80 - active */
1138f3d54fc4Saliguori         uint8_t head;               /* starting head */
1139f3d54fc4Saliguori         uint8_t sector;             /* starting sector */
1140f3d54fc4Saliguori         uint8_t cyl;                /* starting cylinder */
1141f3d54fc4Saliguori         uint8_t sys_ind;            /* What partition type */
1142f3d54fc4Saliguori         uint8_t end_head;           /* end head */
1143f3d54fc4Saliguori         uint8_t end_sector;         /* end sector */
1144f3d54fc4Saliguori         uint8_t end_cyl;            /* end cylinder */
1145f3d54fc4Saliguori         uint32_t start_sect;        /* starting sector counting from 0 */
1146f3d54fc4Saliguori         uint32_t nr_sects;          /* nr of sectors in partition */
1147f3d54fc4Saliguori } __attribute__((packed));
1148f3d54fc4Saliguori 
1149f3d54fc4Saliguori /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1150f3d54fc4Saliguori static int guess_disk_lchs(BlockDriverState *bs,
1151f3d54fc4Saliguori                            int *pcylinders, int *pheads, int *psectors)
1152f3d54fc4Saliguori {
1153eb5a3165SJes Sorensen     uint8_t buf[BDRV_SECTOR_SIZE];
1154f3d54fc4Saliguori     int ret, i, heads, sectors, cylinders;
1155f3d54fc4Saliguori     struct partition *p;
1156f3d54fc4Saliguori     uint32_t nr_sects;
1157a38131b6Sblueswir1     uint64_t nb_sectors;
1158f3d54fc4Saliguori 
1159f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1160f3d54fc4Saliguori 
1161f3d54fc4Saliguori     ret = bdrv_read(bs, 0, buf, 1);
1162f3d54fc4Saliguori     if (ret < 0)
1163f3d54fc4Saliguori         return -1;
1164f3d54fc4Saliguori     /* test msdos magic */
1165f3d54fc4Saliguori     if (buf[510] != 0x55 || buf[511] != 0xaa)
1166f3d54fc4Saliguori         return -1;
1167f3d54fc4Saliguori     for(i = 0; i < 4; i++) {
1168f3d54fc4Saliguori         p = ((struct partition *)(buf + 0x1be)) + i;
1169f3d54fc4Saliguori         nr_sects = le32_to_cpu(p->nr_sects);
1170f3d54fc4Saliguori         if (nr_sects && p->end_head) {
1171f3d54fc4Saliguori             /* We make the assumption that the partition terminates on
1172f3d54fc4Saliguori                a cylinder boundary */
1173f3d54fc4Saliguori             heads = p->end_head + 1;
1174f3d54fc4Saliguori             sectors = p->end_sector & 63;
1175f3d54fc4Saliguori             if (sectors == 0)
1176f3d54fc4Saliguori                 continue;
1177f3d54fc4Saliguori             cylinders = nb_sectors / (heads * sectors);
1178f3d54fc4Saliguori             if (cylinders < 1 || cylinders > 16383)
1179f3d54fc4Saliguori                 continue;
1180f3d54fc4Saliguori             *pheads = heads;
1181f3d54fc4Saliguori             *psectors = sectors;
1182f3d54fc4Saliguori             *pcylinders = cylinders;
1183f3d54fc4Saliguori #if 0
1184f3d54fc4Saliguori             printf("guessed geometry: LCHS=%d %d %d\n",
1185f3d54fc4Saliguori                    cylinders, heads, sectors);
1186f3d54fc4Saliguori #endif
1187f3d54fc4Saliguori             return 0;
1188f3d54fc4Saliguori         }
1189f3d54fc4Saliguori     }
1190f3d54fc4Saliguori     return -1;
1191f3d54fc4Saliguori }
1192f3d54fc4Saliguori 
1193f3d54fc4Saliguori void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1194f3d54fc4Saliguori {
1195f3d54fc4Saliguori     int translation, lba_detected = 0;
1196f3d54fc4Saliguori     int cylinders, heads, secs;
1197a38131b6Sblueswir1     uint64_t nb_sectors;
1198f3d54fc4Saliguori 
1199f3d54fc4Saliguori     /* if a geometry hint is available, use it */
1200f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
1201f3d54fc4Saliguori     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1202f3d54fc4Saliguori     translation = bdrv_get_translation_hint(bs);
1203f3d54fc4Saliguori     if (cylinders != 0) {
1204f3d54fc4Saliguori         *pcyls = cylinders;
1205f3d54fc4Saliguori         *pheads = heads;
1206f3d54fc4Saliguori         *psecs = secs;
1207f3d54fc4Saliguori     } else {
1208f3d54fc4Saliguori         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1209f3d54fc4Saliguori             if (heads > 16) {
1210f3d54fc4Saliguori                 /* if heads > 16, it means that a BIOS LBA
1211f3d54fc4Saliguori                    translation was active, so the default
1212f3d54fc4Saliguori                    hardware geometry is OK */
1213f3d54fc4Saliguori                 lba_detected = 1;
1214f3d54fc4Saliguori                 goto default_geometry;
1215f3d54fc4Saliguori             } else {
1216f3d54fc4Saliguori                 *pcyls = cylinders;
1217f3d54fc4Saliguori                 *pheads = heads;
1218f3d54fc4Saliguori                 *psecs = secs;
1219f3d54fc4Saliguori                 /* disable any translation to be in sync with
1220f3d54fc4Saliguori                    the logical geometry */
1221f3d54fc4Saliguori                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1222f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1223f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_NONE);
1224f3d54fc4Saliguori                 }
1225f3d54fc4Saliguori             }
1226f3d54fc4Saliguori         } else {
1227f3d54fc4Saliguori         default_geometry:
1228f3d54fc4Saliguori             /* if no geometry, use a standard physical disk geometry */
1229f3d54fc4Saliguori             cylinders = nb_sectors / (16 * 63);
1230f3d54fc4Saliguori 
1231f3d54fc4Saliguori             if (cylinders > 16383)
1232f3d54fc4Saliguori                 cylinders = 16383;
1233f3d54fc4Saliguori             else if (cylinders < 2)
1234f3d54fc4Saliguori                 cylinders = 2;
1235f3d54fc4Saliguori             *pcyls = cylinders;
1236f3d54fc4Saliguori             *pheads = 16;
1237f3d54fc4Saliguori             *psecs = 63;
1238f3d54fc4Saliguori             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1239f3d54fc4Saliguori                 if ((*pcyls * *pheads) <= 131072) {
1240f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1241f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LARGE);
1242f3d54fc4Saliguori                 } else {
1243f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
1244f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LBA);
1245f3d54fc4Saliguori                 }
1246f3d54fc4Saliguori             }
1247f3d54fc4Saliguori         }
1248f3d54fc4Saliguori         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1249f3d54fc4Saliguori     }
1250f3d54fc4Saliguori }
1251f3d54fc4Saliguori 
1252b338082bSbellard void bdrv_set_geometry_hint(BlockDriverState *bs,
1253b338082bSbellard                             int cyls, int heads, int secs)
1254b338082bSbellard {
1255b338082bSbellard     bs->cyls = cyls;
1256b338082bSbellard     bs->heads = heads;
1257b338082bSbellard     bs->secs = secs;
1258b338082bSbellard }
1259b338082bSbellard 
1260b338082bSbellard void bdrv_set_type_hint(BlockDriverState *bs, int type)
1261b338082bSbellard {
1262b338082bSbellard     bs->type = type;
1263b338082bSbellard     bs->removable = ((type == BDRV_TYPE_CDROM ||
1264b338082bSbellard                       type == BDRV_TYPE_FLOPPY));
1265b338082bSbellard }
1266b338082bSbellard 
126746d4767dSbellard void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
126846d4767dSbellard {
126946d4767dSbellard     bs->translation = translation;
127046d4767dSbellard }
127146d4767dSbellard 
1272b338082bSbellard void bdrv_get_geometry_hint(BlockDriverState *bs,
1273b338082bSbellard                             int *pcyls, int *pheads, int *psecs)
1274b338082bSbellard {
1275b338082bSbellard     *pcyls = bs->cyls;
1276b338082bSbellard     *pheads = bs->heads;
1277b338082bSbellard     *psecs = bs->secs;
1278b338082bSbellard }
1279b338082bSbellard 
1280b338082bSbellard int bdrv_get_type_hint(BlockDriverState *bs)
1281b338082bSbellard {
1282b338082bSbellard     return bs->type;
1283b338082bSbellard }
1284b338082bSbellard 
128546d4767dSbellard int bdrv_get_translation_hint(BlockDriverState *bs)
128646d4767dSbellard {
128746d4767dSbellard     return bs->translation;
128846d4767dSbellard }
128946d4767dSbellard 
1290abd7f68dSMarkus Armbruster void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1291abd7f68dSMarkus Armbruster                        BlockErrorAction on_write_error)
1292abd7f68dSMarkus Armbruster {
1293abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
1294abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
1295abd7f68dSMarkus Armbruster }
1296abd7f68dSMarkus Armbruster 
1297abd7f68dSMarkus Armbruster BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1298abd7f68dSMarkus Armbruster {
1299abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
1300abd7f68dSMarkus Armbruster }
1301abd7f68dSMarkus Armbruster 
1302*7d0d6950SMarkus Armbruster void bdrv_set_removable(BlockDriverState *bs, int removable)
1303*7d0d6950SMarkus Armbruster {
1304*7d0d6950SMarkus Armbruster     bs->removable = removable;
1305*7d0d6950SMarkus Armbruster     if (removable && bs == bs_snapshots) {
1306*7d0d6950SMarkus Armbruster         bs_snapshots = NULL;
1307*7d0d6950SMarkus Armbruster     }
1308*7d0d6950SMarkus Armbruster }
1309*7d0d6950SMarkus Armbruster 
1310b338082bSbellard int bdrv_is_removable(BlockDriverState *bs)
1311b338082bSbellard {
1312b338082bSbellard     return bs->removable;
1313b338082bSbellard }
1314b338082bSbellard 
1315b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
1316b338082bSbellard {
1317b338082bSbellard     return bs->read_only;
1318b338082bSbellard }
1319b338082bSbellard 
1320985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
1321985a03b0Sths {
1322985a03b0Sths     return bs->sg;
1323985a03b0Sths }
1324985a03b0Sths 
1325e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
1326e900a7b7SChristoph Hellwig {
1327e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
1328e900a7b7SChristoph Hellwig }
1329e900a7b7SChristoph Hellwig 
133019cb3738Sbellard /* XXX: no longer used */
1331b338082bSbellard void bdrv_set_change_cb(BlockDriverState *bs,
1332b338082bSbellard                         void (*change_cb)(void *opaque), void *opaque)
1333b338082bSbellard {
1334b338082bSbellard     bs->change_cb = change_cb;
1335b338082bSbellard     bs->change_opaque = opaque;
1336b338082bSbellard }
1337b338082bSbellard 
1338ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
1339ea2384d3Sbellard {
1340ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
1341ea2384d3Sbellard         return 1;
1342ea2384d3Sbellard     return bs->encrypted;
1343ea2384d3Sbellard }
1344ea2384d3Sbellard 
1345c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
1346c0f4ce77Saliguori {
1347c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
1348c0f4ce77Saliguori 
1349c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1350c0f4ce77Saliguori         return 1;
1351c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
1352c0f4ce77Saliguori }
1353c0f4ce77Saliguori 
1354ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
1355ea2384d3Sbellard {
1356ea2384d3Sbellard     int ret;
1357ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
1358ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
1359ea2384d3Sbellard         if (ret < 0)
1360ea2384d3Sbellard             return ret;
1361ea2384d3Sbellard         if (!bs->encrypted)
1362ea2384d3Sbellard             return 0;
1363ea2384d3Sbellard     }
1364fd04a2aeSShahar Havivi     if (!bs->encrypted) {
1365fd04a2aeSShahar Havivi         return -EINVAL;
1366fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1367fd04a2aeSShahar Havivi         return -ENOMEDIUM;
1368fd04a2aeSShahar Havivi     }
1369c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
1370bb5fc20fSaliguori     if (ret < 0) {
1371bb5fc20fSaliguori         bs->valid_key = 0;
1372bb5fc20fSaliguori     } else if (!bs->valid_key) {
1373bb5fc20fSaliguori         bs->valid_key = 1;
1374bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
1375bb5fc20fSaliguori         bs->media_changed = 1;
1376bb5fc20fSaliguori         if (bs->change_cb)
1377bb5fc20fSaliguori             bs->change_cb(bs->change_opaque);
1378bb5fc20fSaliguori     }
1379c0f4ce77Saliguori     return ret;
1380ea2384d3Sbellard }
1381ea2384d3Sbellard 
1382ea2384d3Sbellard void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1383ea2384d3Sbellard {
138419cb3738Sbellard     if (!bs->drv) {
1385ea2384d3Sbellard         buf[0] = '\0';
1386ea2384d3Sbellard     } else {
1387ea2384d3Sbellard         pstrcpy(buf, buf_size, bs->drv->format_name);
1388ea2384d3Sbellard     }
1389ea2384d3Sbellard }
1390ea2384d3Sbellard 
1391ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1392ea2384d3Sbellard                          void *opaque)
1393ea2384d3Sbellard {
1394ea2384d3Sbellard     BlockDriver *drv;
1395ea2384d3Sbellard 
13968a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
1397ea2384d3Sbellard         it(opaque, drv->format_name);
1398ea2384d3Sbellard     }
1399ea2384d3Sbellard }
1400ea2384d3Sbellard 
1401b338082bSbellard BlockDriverState *bdrv_find(const char *name)
1402b338082bSbellard {
1403b338082bSbellard     BlockDriverState *bs;
1404b338082bSbellard 
14051b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
14061b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
1407b338082bSbellard             return bs;
1408b338082bSbellard         }
14091b7bdbc1SStefan Hajnoczi     }
1410b338082bSbellard     return NULL;
1411b338082bSbellard }
1412b338082bSbellard 
14132f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
14142f399b0aSMarkus Armbruster {
14152f399b0aSMarkus Armbruster     if (!bs) {
14162f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
14172f399b0aSMarkus Armbruster     }
14182f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
14192f399b0aSMarkus Armbruster }
14202f399b0aSMarkus Armbruster 
142151de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
142281d0912dSbellard {
142381d0912dSbellard     BlockDriverState *bs;
142481d0912dSbellard 
14251b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
142651de9760Saliguori         it(opaque, bs);
142781d0912dSbellard     }
142881d0912dSbellard }
142981d0912dSbellard 
1430ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
1431ea2384d3Sbellard {
1432ea2384d3Sbellard     return bs->device_name;
1433ea2384d3Sbellard }
1434ea2384d3Sbellard 
14357a6cba61Spbrook void bdrv_flush(BlockDriverState *bs)
14367a6cba61Spbrook {
1437016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
1438016f5cf6SAlexander Graf         return;
1439016f5cf6SAlexander Graf     }
1440016f5cf6SAlexander Graf 
14413f5075aeSChristoph Hellwig     if (bs->drv && bs->drv->bdrv_flush)
14427a6cba61Spbrook         bs->drv->bdrv_flush(bs);
14437a6cba61Spbrook }
14447a6cba61Spbrook 
1445c6ca28d6Saliguori void bdrv_flush_all(void)
1446c6ca28d6Saliguori {
1447c6ca28d6Saliguori     BlockDriverState *bs;
1448c6ca28d6Saliguori 
14491b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1450c6ca28d6Saliguori         if (bs->drv && !bdrv_is_read_only(bs) &&
14511b7bdbc1SStefan Hajnoczi             (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1452c6ca28d6Saliguori             bdrv_flush(bs);
1453c6ca28d6Saliguori         }
14541b7bdbc1SStefan Hajnoczi     }
14551b7bdbc1SStefan Hajnoczi }
1456c6ca28d6Saliguori 
1457f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
1458f2feebbdSKevin Wolf {
1459f2feebbdSKevin Wolf     assert(bs->drv);
1460f2feebbdSKevin Wolf 
1461f2feebbdSKevin Wolf     if (bs->drv->no_zero_init) {
1462f2feebbdSKevin Wolf         return 0;
1463f2feebbdSKevin Wolf     } else if (bs->file) {
1464f2feebbdSKevin Wolf         return bdrv_has_zero_init(bs->file);
1465f2feebbdSKevin Wolf     }
1466f2feebbdSKevin Wolf 
1467f2feebbdSKevin Wolf     return 1;
1468f2feebbdSKevin Wolf }
1469f2feebbdSKevin Wolf 
1470f58c7b35Sths /*
1471f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
1472f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
1473f58c7b35Sths  * hence all their sectors are reported as allocated.
1474f58c7b35Sths  *
1475f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
1476f58c7b35Sths  * the specified sector) that are known to be in the same
1477f58c7b35Sths  * allocated/unallocated state.
1478f58c7b35Sths  *
1479f58c7b35Sths  * 'nb_sectors' is the max value 'pnum' should be set to.
1480f58c7b35Sths  */
1481f58c7b35Sths int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1482f58c7b35Sths 	int *pnum)
1483f58c7b35Sths {
1484f58c7b35Sths     int64_t n;
1485f58c7b35Sths     if (!bs->drv->bdrv_is_allocated) {
1486f58c7b35Sths         if (sector_num >= bs->total_sectors) {
1487f58c7b35Sths             *pnum = 0;
1488f58c7b35Sths             return 0;
1489f58c7b35Sths         }
1490f58c7b35Sths         n = bs->total_sectors - sector_num;
1491f58c7b35Sths         *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1492f58c7b35Sths         return 1;
1493f58c7b35Sths     }
1494f58c7b35Sths     return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1495f58c7b35Sths }
1496f58c7b35Sths 
14972582bfedSLuiz Capitulino void bdrv_mon_event(const BlockDriverState *bdrv,
14982582bfedSLuiz Capitulino                     BlockMonEventAction action, int is_read)
14992582bfedSLuiz Capitulino {
15002582bfedSLuiz Capitulino     QObject *data;
15012582bfedSLuiz Capitulino     const char *action_str;
15022582bfedSLuiz Capitulino 
15032582bfedSLuiz Capitulino     switch (action) {
15042582bfedSLuiz Capitulino     case BDRV_ACTION_REPORT:
15052582bfedSLuiz Capitulino         action_str = "report";
15062582bfedSLuiz Capitulino         break;
15072582bfedSLuiz Capitulino     case BDRV_ACTION_IGNORE:
15082582bfedSLuiz Capitulino         action_str = "ignore";
15092582bfedSLuiz Capitulino         break;
15102582bfedSLuiz Capitulino     case BDRV_ACTION_STOP:
15112582bfedSLuiz Capitulino         action_str = "stop";
15122582bfedSLuiz Capitulino         break;
15132582bfedSLuiz Capitulino     default:
15142582bfedSLuiz Capitulino         abort();
15152582bfedSLuiz Capitulino     }
15162582bfedSLuiz Capitulino 
15172582bfedSLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
15182582bfedSLuiz Capitulino                               bdrv->device_name,
15192582bfedSLuiz Capitulino                               action_str,
15202582bfedSLuiz Capitulino                               is_read ? "read" : "write");
15212582bfedSLuiz Capitulino     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
15222582bfedSLuiz Capitulino 
15232582bfedSLuiz Capitulino     qobject_decref(data);
15242582bfedSLuiz Capitulino }
15252582bfedSLuiz Capitulino 
1526d15e5465SLuiz Capitulino static void bdrv_print_dict(QObject *obj, void *opaque)
1527b338082bSbellard {
1528d15e5465SLuiz Capitulino     QDict *bs_dict;
1529d15e5465SLuiz Capitulino     Monitor *mon = opaque;
1530b338082bSbellard 
1531d15e5465SLuiz Capitulino     bs_dict = qobject_to_qdict(obj);
1532d15e5465SLuiz Capitulino 
1533d15e5465SLuiz Capitulino     monitor_printf(mon, "%s: type=%s removable=%d",
1534d15e5465SLuiz Capitulino                         qdict_get_str(bs_dict, "device"),
1535d15e5465SLuiz Capitulino                         qdict_get_str(bs_dict, "type"),
1536d15e5465SLuiz Capitulino                         qdict_get_bool(bs_dict, "removable"));
1537d15e5465SLuiz Capitulino 
1538d15e5465SLuiz Capitulino     if (qdict_get_bool(bs_dict, "removable")) {
1539d15e5465SLuiz Capitulino         monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1540b338082bSbellard     }
1541d15e5465SLuiz Capitulino 
1542d15e5465SLuiz Capitulino     if (qdict_haskey(bs_dict, "inserted")) {
1543d15e5465SLuiz Capitulino         QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1544d15e5465SLuiz Capitulino 
1545376253ecSaliguori         monitor_printf(mon, " file=");
1546d15e5465SLuiz Capitulino         monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1547d15e5465SLuiz Capitulino         if (qdict_haskey(qdict, "backing_file")) {
1548376253ecSaliguori             monitor_printf(mon, " backing_file=");
1549d15e5465SLuiz Capitulino             monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1550fef30743Sths         }
1551d15e5465SLuiz Capitulino         monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1552d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "ro"),
1553d15e5465SLuiz Capitulino                             qdict_get_str(qdict, "drv"),
1554d15e5465SLuiz Capitulino                             qdict_get_bool(qdict, "encrypted"));
1555b338082bSbellard     } else {
1556376253ecSaliguori         monitor_printf(mon, " [not inserted]");
1557b338082bSbellard     }
1558d15e5465SLuiz Capitulino 
1559376253ecSaliguori     monitor_printf(mon, "\n");
1560b338082bSbellard }
1561d15e5465SLuiz Capitulino 
1562d15e5465SLuiz Capitulino void bdrv_info_print(Monitor *mon, const QObject *data)
1563d15e5465SLuiz Capitulino {
1564d15e5465SLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1565d15e5465SLuiz Capitulino }
1566d15e5465SLuiz Capitulino 
1567d15e5465SLuiz Capitulino void bdrv_info(Monitor *mon, QObject **ret_data)
1568d15e5465SLuiz Capitulino {
1569d15e5465SLuiz Capitulino     QList *bs_list;
1570d15e5465SLuiz Capitulino     BlockDriverState *bs;
1571d15e5465SLuiz Capitulino 
1572d15e5465SLuiz Capitulino     bs_list = qlist_new();
1573d15e5465SLuiz Capitulino 
15741b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1575d15e5465SLuiz Capitulino         QObject *bs_obj;
1576d15e5465SLuiz Capitulino         const char *type = "unknown";
1577d15e5465SLuiz Capitulino 
1578d15e5465SLuiz Capitulino         switch(bs->type) {
1579d15e5465SLuiz Capitulino         case BDRV_TYPE_HD:
1580d15e5465SLuiz Capitulino             type = "hd";
1581d15e5465SLuiz Capitulino             break;
1582d15e5465SLuiz Capitulino         case BDRV_TYPE_CDROM:
1583d15e5465SLuiz Capitulino             type = "cdrom";
1584d15e5465SLuiz Capitulino             break;
1585d15e5465SLuiz Capitulino         case BDRV_TYPE_FLOPPY:
1586d15e5465SLuiz Capitulino             type = "floppy";
1587d15e5465SLuiz Capitulino             break;
1588d15e5465SLuiz Capitulino         }
1589d15e5465SLuiz Capitulino 
1590d15e5465SLuiz Capitulino         bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1591d15e5465SLuiz Capitulino                                     "'removable': %i, 'locked': %i }",
1592d15e5465SLuiz Capitulino                                     bs->device_name, type, bs->removable,
1593d15e5465SLuiz Capitulino                                     bs->locked);
1594d15e5465SLuiz Capitulino 
1595d15e5465SLuiz Capitulino         if (bs->drv) {
1596d15e5465SLuiz Capitulino             QObject *obj;
1597d15e5465SLuiz Capitulino             QDict *bs_dict = qobject_to_qdict(bs_obj);
1598d15e5465SLuiz Capitulino 
1599d15e5465SLuiz Capitulino             obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1600d15e5465SLuiz Capitulino                                      "'encrypted': %i }",
1601d15e5465SLuiz Capitulino                                      bs->filename, bs->read_only,
1602d15e5465SLuiz Capitulino                                      bs->drv->format_name,
1603d15e5465SLuiz Capitulino                                      bdrv_is_encrypted(bs));
1604d15e5465SLuiz Capitulino             if (bs->backing_file[0] != '\0') {
1605d15e5465SLuiz Capitulino                 QDict *qdict = qobject_to_qdict(obj);
1606d15e5465SLuiz Capitulino                 qdict_put(qdict, "backing_file",
1607d15e5465SLuiz Capitulino                           qstring_from_str(bs->backing_file));
1608d15e5465SLuiz Capitulino             }
1609d15e5465SLuiz Capitulino 
1610d15e5465SLuiz Capitulino             qdict_put_obj(bs_dict, "inserted", obj);
1611d15e5465SLuiz Capitulino         }
1612d15e5465SLuiz Capitulino         qlist_append_obj(bs_list, bs_obj);
1613d15e5465SLuiz Capitulino     }
1614d15e5465SLuiz Capitulino 
1615d15e5465SLuiz Capitulino     *ret_data = QOBJECT(bs_list);
1616b338082bSbellard }
1617a36e69ddSths 
1618218a536aSLuiz Capitulino static void bdrv_stats_iter(QObject *data, void *opaque)
1619a36e69ddSths {
1620218a536aSLuiz Capitulino     QDict *qdict;
1621218a536aSLuiz Capitulino     Monitor *mon = opaque;
1622218a536aSLuiz Capitulino 
1623218a536aSLuiz Capitulino     qdict = qobject_to_qdict(data);
1624218a536aSLuiz Capitulino     monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1625218a536aSLuiz Capitulino 
1626218a536aSLuiz Capitulino     qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1627218a536aSLuiz Capitulino     monitor_printf(mon, " rd_bytes=%" PRId64
1628218a536aSLuiz Capitulino                         " wr_bytes=%" PRId64
1629218a536aSLuiz Capitulino                         " rd_operations=%" PRId64
1630218a536aSLuiz Capitulino                         " wr_operations=%" PRId64
1631218a536aSLuiz Capitulino                         "\n",
1632218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_bytes"),
1633218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_bytes"),
1634218a536aSLuiz Capitulino                         qdict_get_int(qdict, "rd_operations"),
1635218a536aSLuiz Capitulino                         qdict_get_int(qdict, "wr_operations"));
1636218a536aSLuiz Capitulino }
1637218a536aSLuiz Capitulino 
1638218a536aSLuiz Capitulino void bdrv_stats_print(Monitor *mon, const QObject *data)
1639218a536aSLuiz Capitulino {
1640218a536aSLuiz Capitulino     qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1641218a536aSLuiz Capitulino }
1642218a536aSLuiz Capitulino 
1643294cc35fSKevin Wolf static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1644294cc35fSKevin Wolf {
1645294cc35fSKevin Wolf     QObject *res;
1646294cc35fSKevin Wolf     QDict *dict;
1647294cc35fSKevin Wolf 
1648294cc35fSKevin Wolf     res = qobject_from_jsonf("{ 'stats': {"
1649294cc35fSKevin Wolf                              "'rd_bytes': %" PRId64 ","
1650294cc35fSKevin Wolf                              "'wr_bytes': %" PRId64 ","
1651294cc35fSKevin Wolf                              "'rd_operations': %" PRId64 ","
1652294cc35fSKevin Wolf                              "'wr_operations': %" PRId64 ","
1653294cc35fSKevin Wolf                              "'wr_highest_offset': %" PRId64
1654294cc35fSKevin Wolf                              "} }",
1655294cc35fSKevin Wolf                              bs->rd_bytes, bs->wr_bytes,
1656294cc35fSKevin Wolf                              bs->rd_ops, bs->wr_ops,
16575ffbbc67SBlue Swirl                              bs->wr_highest_sector *
16585ffbbc67SBlue Swirl                              (uint64_t)BDRV_SECTOR_SIZE);
1659294cc35fSKevin Wolf     dict  = qobject_to_qdict(res);
1660294cc35fSKevin Wolf 
1661294cc35fSKevin Wolf     if (*bs->device_name) {
1662294cc35fSKevin Wolf         qdict_put(dict, "device", qstring_from_str(bs->device_name));
1663294cc35fSKevin Wolf     }
1664294cc35fSKevin Wolf 
1665294cc35fSKevin Wolf     if (bs->file) {
1666294cc35fSKevin Wolf         QObject *parent = bdrv_info_stats_bs(bs->file);
1667294cc35fSKevin Wolf         qdict_put_obj(dict, "parent", parent);
1668294cc35fSKevin Wolf     }
1669294cc35fSKevin Wolf 
1670294cc35fSKevin Wolf     return res;
1671294cc35fSKevin Wolf }
1672294cc35fSKevin Wolf 
1673218a536aSLuiz Capitulino void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1674218a536aSLuiz Capitulino {
1675218a536aSLuiz Capitulino     QObject *obj;
1676218a536aSLuiz Capitulino     QList *devices;
1677a36e69ddSths     BlockDriverState *bs;
1678a36e69ddSths 
1679218a536aSLuiz Capitulino     devices = qlist_new();
1680218a536aSLuiz Capitulino 
16811b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1682294cc35fSKevin Wolf         obj = bdrv_info_stats_bs(bs);
1683218a536aSLuiz Capitulino         qlist_append_obj(devices, obj);
1684a36e69ddSths     }
1685218a536aSLuiz Capitulino 
1686218a536aSLuiz Capitulino     *ret_data = QOBJECT(devices);
1687a36e69ddSths }
1688ea2384d3Sbellard 
1689045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1690045df330Saliguori {
1691045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
1692045df330Saliguori         return bs->backing_file;
1693045df330Saliguori     else if (bs->encrypted)
1694045df330Saliguori         return bs->filename;
1695045df330Saliguori     else
1696045df330Saliguori         return NULL;
1697045df330Saliguori }
1698045df330Saliguori 
169983f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
170083f64091Sbellard                                char *filename, int filename_size)
170183f64091Sbellard {
1702b783e409SKevin Wolf     if (!bs->backing_file) {
170383f64091Sbellard         pstrcpy(filename, filename_size, "");
170483f64091Sbellard     } else {
170583f64091Sbellard         pstrcpy(filename, filename_size, bs->backing_file);
170683f64091Sbellard     }
170783f64091Sbellard }
170883f64091Sbellard 
1709faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1710faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
1711faea38e7Sbellard {
1712faea38e7Sbellard     BlockDriver *drv = bs->drv;
1713faea38e7Sbellard     if (!drv)
171419cb3738Sbellard         return -ENOMEDIUM;
1715faea38e7Sbellard     if (!drv->bdrv_write_compressed)
1716faea38e7Sbellard         return -ENOTSUP;
1717fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
1718fbb7b4e0SKevin Wolf         return -EIO;
17197cd1e32aSlirans@il.ibm.com 
1720c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
17217cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
17227cd1e32aSlirans@il.ibm.com     }
17237cd1e32aSlirans@il.ibm.com 
1724faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1725faea38e7Sbellard }
1726faea38e7Sbellard 
1727faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1728faea38e7Sbellard {
1729faea38e7Sbellard     BlockDriver *drv = bs->drv;
1730faea38e7Sbellard     if (!drv)
173119cb3738Sbellard         return -ENOMEDIUM;
1732faea38e7Sbellard     if (!drv->bdrv_get_info)
1733faea38e7Sbellard         return -ENOTSUP;
1734faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
1735faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
1736faea38e7Sbellard }
1737faea38e7Sbellard 
173845566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
173945566e9cSChristoph Hellwig                       int64_t pos, int size)
1740178e08a5Saliguori {
1741178e08a5Saliguori     BlockDriver *drv = bs->drv;
1742178e08a5Saliguori     if (!drv)
1743178e08a5Saliguori         return -ENOMEDIUM;
17447cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
174545566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
17467cdb1f6dSMORITA Kazutaka     if (bs->file)
17477cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
17487cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1749178e08a5Saliguori }
1750178e08a5Saliguori 
175145566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
175245566e9cSChristoph Hellwig                       int64_t pos, int size)
1753178e08a5Saliguori {
1754178e08a5Saliguori     BlockDriver *drv = bs->drv;
1755178e08a5Saliguori     if (!drv)
1756178e08a5Saliguori         return -ENOMEDIUM;
17577cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
175845566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
17597cdb1f6dSMORITA Kazutaka     if (bs->file)
17607cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
17617cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1762178e08a5Saliguori }
1763178e08a5Saliguori 
17648b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
17658b9b0cc2SKevin Wolf {
17668b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
17678b9b0cc2SKevin Wolf 
17688b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
17698b9b0cc2SKevin Wolf         return;
17708b9b0cc2SKevin Wolf     }
17718b9b0cc2SKevin Wolf 
17728b9b0cc2SKevin Wolf     return drv->bdrv_debug_event(bs, event);
17738b9b0cc2SKevin Wolf 
17748b9b0cc2SKevin Wolf }
17758b9b0cc2SKevin Wolf 
1776faea38e7Sbellard /**************************************************************/
1777faea38e7Sbellard /* handling of snapshots */
1778faea38e7Sbellard 
1779feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
1780feeee5acSMiguel Di Ciurcio Filho {
1781feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
1782feeee5acSMiguel Di Ciurcio Filho     if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1783feeee5acSMiguel Di Ciurcio Filho         return 0;
1784feeee5acSMiguel Di Ciurcio Filho     }
1785feeee5acSMiguel Di Ciurcio Filho 
1786feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
1787feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
1788feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
1789feeee5acSMiguel Di Ciurcio Filho         }
1790feeee5acSMiguel Di Ciurcio Filho         return 0;
1791feeee5acSMiguel Di Ciurcio Filho     }
1792feeee5acSMiguel Di Ciurcio Filho 
1793feeee5acSMiguel Di Ciurcio Filho     return 1;
1794feeee5acSMiguel Di Ciurcio Filho }
1795feeee5acSMiguel Di Ciurcio Filho 
1796f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
1797f9092b10SMarkus Armbruster {
1798f9092b10SMarkus Armbruster     BlockDriverState *bs;
1799f9092b10SMarkus Armbruster 
18003ac906f7SMarkus Armbruster     if (bs_snapshots) {
1801f9092b10SMarkus Armbruster         return bs_snapshots;
18023ac906f7SMarkus Armbruster     }
1803f9092b10SMarkus Armbruster 
1804f9092b10SMarkus Armbruster     bs = NULL;
1805f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
1806f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
18073ac906f7SMarkus Armbruster             bs_snapshots = bs;
18083ac906f7SMarkus Armbruster             return bs;
1809f9092b10SMarkus Armbruster         }
1810f9092b10SMarkus Armbruster     }
1811f9092b10SMarkus Armbruster     return NULL;
1812f9092b10SMarkus Armbruster }
1813f9092b10SMarkus Armbruster 
1814faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
1815faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
1816faea38e7Sbellard {
1817faea38e7Sbellard     BlockDriver *drv = bs->drv;
1818faea38e7Sbellard     if (!drv)
181919cb3738Sbellard         return -ENOMEDIUM;
18207cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
1821faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
18227cdb1f6dSMORITA Kazutaka     if (bs->file)
18237cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
18247cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1825faea38e7Sbellard }
1826faea38e7Sbellard 
1827faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
1828faea38e7Sbellard                        const char *snapshot_id)
1829faea38e7Sbellard {
1830faea38e7Sbellard     BlockDriver *drv = bs->drv;
18317cdb1f6dSMORITA Kazutaka     int ret, open_ret;
18327cdb1f6dSMORITA Kazutaka 
1833faea38e7Sbellard     if (!drv)
183419cb3738Sbellard         return -ENOMEDIUM;
18357cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
1836faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
18377cdb1f6dSMORITA Kazutaka 
18387cdb1f6dSMORITA Kazutaka     if (bs->file) {
18397cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
18407cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
18417cdb1f6dSMORITA Kazutaka         open_ret = drv->bdrv_open(bs, bs->open_flags);
18427cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
18437cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
18447cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
18457cdb1f6dSMORITA Kazutaka             return open_ret;
18467cdb1f6dSMORITA Kazutaka         }
18477cdb1f6dSMORITA Kazutaka         return ret;
18487cdb1f6dSMORITA Kazutaka     }
18497cdb1f6dSMORITA Kazutaka 
18507cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1851faea38e7Sbellard }
1852faea38e7Sbellard 
1853faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1854faea38e7Sbellard {
1855faea38e7Sbellard     BlockDriver *drv = bs->drv;
1856faea38e7Sbellard     if (!drv)
185719cb3738Sbellard         return -ENOMEDIUM;
18587cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
1859faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
18607cdb1f6dSMORITA Kazutaka     if (bs->file)
18617cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
18627cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1863faea38e7Sbellard }
1864faea38e7Sbellard 
1865faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
1866faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
1867faea38e7Sbellard {
1868faea38e7Sbellard     BlockDriver *drv = bs->drv;
1869faea38e7Sbellard     if (!drv)
187019cb3738Sbellard         return -ENOMEDIUM;
18717cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
1872faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
18737cdb1f6dSMORITA Kazutaka     if (bs->file)
18747cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
18757cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
1876faea38e7Sbellard }
1877faea38e7Sbellard 
1878faea38e7Sbellard #define NB_SUFFIXES 4
1879faea38e7Sbellard 
1880faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1881faea38e7Sbellard {
1882faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
1883faea38e7Sbellard     int64_t base;
1884faea38e7Sbellard     int i;
1885faea38e7Sbellard 
1886faea38e7Sbellard     if (size <= 999) {
1887faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
1888faea38e7Sbellard     } else {
1889faea38e7Sbellard         base = 1024;
1890faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
1891faea38e7Sbellard             if (size < (10 * base)) {
1892faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
1893faea38e7Sbellard                          (double)size / base,
1894faea38e7Sbellard                          suffixes[i]);
1895faea38e7Sbellard                 break;
1896faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1897faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
1898faea38e7Sbellard                          ((size + (base >> 1)) / base),
1899faea38e7Sbellard                          suffixes[i]);
1900faea38e7Sbellard                 break;
1901faea38e7Sbellard             }
1902faea38e7Sbellard             base = base * 1024;
1903faea38e7Sbellard         }
1904faea38e7Sbellard     }
1905faea38e7Sbellard     return buf;
1906faea38e7Sbellard }
1907faea38e7Sbellard 
1908faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1909faea38e7Sbellard {
1910faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
19113b9f94e1Sbellard #ifdef _WIN32
19123b9f94e1Sbellard     struct tm *ptm;
19133b9f94e1Sbellard #else
1914faea38e7Sbellard     struct tm tm;
19153b9f94e1Sbellard #endif
1916faea38e7Sbellard     time_t ti;
1917faea38e7Sbellard     int64_t secs;
1918faea38e7Sbellard 
1919faea38e7Sbellard     if (!sn) {
1920faea38e7Sbellard         snprintf(buf, buf_size,
1921faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
1922faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1923faea38e7Sbellard     } else {
1924faea38e7Sbellard         ti = sn->date_sec;
19253b9f94e1Sbellard #ifdef _WIN32
19263b9f94e1Sbellard         ptm = localtime(&ti);
19273b9f94e1Sbellard         strftime(date_buf, sizeof(date_buf),
19283b9f94e1Sbellard                  "%Y-%m-%d %H:%M:%S", ptm);
19293b9f94e1Sbellard #else
1930faea38e7Sbellard         localtime_r(&ti, &tm);
1931faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
1932faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
19333b9f94e1Sbellard #endif
1934faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
1935faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
1936faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
1937faea38e7Sbellard                  (int)(secs / 3600),
1938faea38e7Sbellard                  (int)((secs / 60) % 60),
1939faea38e7Sbellard                  (int)(secs % 60),
1940faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
1941faea38e7Sbellard         snprintf(buf, buf_size,
1942faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
1943faea38e7Sbellard                  sn->id_str, sn->name,
1944faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1945faea38e7Sbellard                  date_buf,
1946faea38e7Sbellard                  clock_buf);
1947faea38e7Sbellard     }
1948faea38e7Sbellard     return buf;
1949faea38e7Sbellard }
1950faea38e7Sbellard 
195183f64091Sbellard 
1952ea2384d3Sbellard /**************************************************************/
195383f64091Sbellard /* async I/Os */
1954ea2384d3Sbellard 
19553b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1956f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
195783f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
1958ea2384d3Sbellard {
195983f64091Sbellard     BlockDriver *drv = bs->drv;
1960a36e69ddSths     BlockDriverAIOCB *ret;
1961ea2384d3Sbellard 
196219cb3738Sbellard     if (!drv)
1963ce1a14dcSpbrook         return NULL;
196471d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
196571d0770cSaliguori         return NULL;
196683f64091Sbellard 
1967f141eafeSaliguori     ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1968f141eafeSaliguori                               cb, opaque);
1969a36e69ddSths 
1970a36e69ddSths     if (ret) {
1971a36e69ddSths 	/* Update stats even though technically transfer has not happened. */
19726ea44308SJan Kiszka 	bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1973a36e69ddSths 	bs->rd_ops ++;
1974a36e69ddSths     }
1975a36e69ddSths 
1976a36e69ddSths     return ret;
197783f64091Sbellard }
197883f64091Sbellard 
1979f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1980f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
198183f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
19827674e7bfSbellard {
198383f64091Sbellard     BlockDriver *drv = bs->drv;
1984a36e69ddSths     BlockDriverAIOCB *ret;
198583f64091Sbellard 
198619cb3738Sbellard     if (!drv)
1987ce1a14dcSpbrook         return NULL;
198883f64091Sbellard     if (bs->read_only)
1989ce1a14dcSpbrook         return NULL;
199071d0770cSaliguori     if (bdrv_check_request(bs, sector_num, nb_sectors))
199171d0770cSaliguori         return NULL;
199283f64091Sbellard 
1993c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
19947cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
19957cd1e32aSlirans@il.ibm.com     }
19967cd1e32aSlirans@il.ibm.com 
1997f141eafeSaliguori     ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1998f141eafeSaliguori                                cb, opaque);
1999a36e69ddSths 
2000a36e69ddSths     if (ret) {
2001a36e69ddSths         /* Update stats even though technically transfer has not happened. */
20026ea44308SJan Kiszka         bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2003a36e69ddSths         bs->wr_ops ++;
2004294cc35fSKevin Wolf         if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2005294cc35fSKevin Wolf             bs->wr_highest_sector = sector_num + nb_sectors - 1;
2006294cc35fSKevin Wolf         }
2007a36e69ddSths     }
2008a36e69ddSths 
2009a36e69ddSths     return ret;
201083f64091Sbellard }
201183f64091Sbellard 
201240b4f539SKevin Wolf 
201340b4f539SKevin Wolf typedef struct MultiwriteCB {
201440b4f539SKevin Wolf     int error;
201540b4f539SKevin Wolf     int num_requests;
201640b4f539SKevin Wolf     int num_callbacks;
201740b4f539SKevin Wolf     struct {
201840b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
201940b4f539SKevin Wolf         void *opaque;
202040b4f539SKevin Wolf         QEMUIOVector *free_qiov;
202140b4f539SKevin Wolf         void *free_buf;
202240b4f539SKevin Wolf     } callbacks[];
202340b4f539SKevin Wolf } MultiwriteCB;
202440b4f539SKevin Wolf 
202540b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
202640b4f539SKevin Wolf {
202740b4f539SKevin Wolf     int i;
202840b4f539SKevin Wolf 
202940b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
203040b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
20311e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
20321e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
20331e1ea48dSStefan Hajnoczi         }
203440b4f539SKevin Wolf         qemu_free(mcb->callbacks[i].free_qiov);
2035f8a83245SHerve Poussineau         qemu_vfree(mcb->callbacks[i].free_buf);
203640b4f539SKevin Wolf     }
203740b4f539SKevin Wolf }
203840b4f539SKevin Wolf 
203940b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
204040b4f539SKevin Wolf {
204140b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
204240b4f539SKevin Wolf 
2043cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
204440b4f539SKevin Wolf         mcb->error = ret;
204540b4f539SKevin Wolf         multiwrite_user_cb(mcb);
204640b4f539SKevin Wolf     }
204740b4f539SKevin Wolf 
204840b4f539SKevin Wolf     mcb->num_requests--;
204940b4f539SKevin Wolf     if (mcb->num_requests == 0) {
205040b4f539SKevin Wolf         if (mcb->error == 0) {
205140b4f539SKevin Wolf             multiwrite_user_cb(mcb);
205240b4f539SKevin Wolf         }
205340b4f539SKevin Wolf         qemu_free(mcb);
205440b4f539SKevin Wolf     }
205540b4f539SKevin Wolf }
205640b4f539SKevin Wolf 
205740b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
205840b4f539SKevin Wolf {
205977be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
206077be4366SChristoph Hellwig 
206177be4366SChristoph Hellwig     /*
206277be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
206377be4366SChristoph Hellwig      * here as that could overflow the return value.
206477be4366SChristoph Hellwig      */
206577be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
206677be4366SChristoph Hellwig         return 1;
206777be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
206877be4366SChristoph Hellwig         return -1;
206977be4366SChristoph Hellwig     } else {
207077be4366SChristoph Hellwig         return 0;
207177be4366SChristoph Hellwig     }
207240b4f539SKevin Wolf }
207340b4f539SKevin Wolf 
207440b4f539SKevin Wolf /*
207540b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
207640b4f539SKevin Wolf  * requests that remain after merging.
207740b4f539SKevin Wolf  */
207840b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
207940b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
208040b4f539SKevin Wolf {
208140b4f539SKevin Wolf     int i, outidx;
208240b4f539SKevin Wolf 
208340b4f539SKevin Wolf     // Sort requests by start sector
208440b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
208540b4f539SKevin Wolf 
208640b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
208740b4f539SKevin Wolf     // filling up gaps with zero sectors.
208840b4f539SKevin Wolf     outidx = 0;
208940b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
209040b4f539SKevin Wolf         int merge = 0;
209140b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
209240b4f539SKevin Wolf 
209340b4f539SKevin Wolf         // This handles the cases that are valid for all block drivers, namely
209440b4f539SKevin Wolf         // exactly sequential writes and overlapping writes.
209540b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
209640b4f539SKevin Wolf             merge = 1;
209740b4f539SKevin Wolf         }
209840b4f539SKevin Wolf 
209940b4f539SKevin Wolf         // The block driver may decide that it makes sense to combine requests
210040b4f539SKevin Wolf         // even if there is a gap of some sectors between them. In this case,
210140b4f539SKevin Wolf         // the gap is filled with zeros (therefore only applicable for yet
210240b4f539SKevin Wolf         // unused space in format like qcow2).
210340b4f539SKevin Wolf         if (!merge && bs->drv->bdrv_merge_requests) {
210440b4f539SKevin Wolf             merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
210540b4f539SKevin Wolf         }
210640b4f539SKevin Wolf 
2107e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2108e2a305fbSChristoph Hellwig             merge = 0;
2109e2a305fbSChristoph Hellwig         }
2110e2a305fbSChristoph Hellwig 
211140b4f539SKevin Wolf         if (merge) {
211240b4f539SKevin Wolf             size_t size;
211340b4f539SKevin Wolf             QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
211440b4f539SKevin Wolf             qemu_iovec_init(qiov,
211540b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
211640b4f539SKevin Wolf 
211740b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
211840b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
211940b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
212040b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
212140b4f539SKevin Wolf 
212240b4f539SKevin Wolf             // We might need to add some zeros between the two requests
212340b4f539SKevin Wolf             if (reqs[i].sector > oldreq_last) {
212440b4f539SKevin Wolf                 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
212540b4f539SKevin Wolf                 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
212640b4f539SKevin Wolf                 memset(buf, 0, zero_bytes);
212740b4f539SKevin Wolf                 qemu_iovec_add(qiov, buf, zero_bytes);
212840b4f539SKevin Wolf                 mcb->callbacks[i].free_buf = buf;
212940b4f539SKevin Wolf             }
213040b4f539SKevin Wolf 
213140b4f539SKevin Wolf             // Add the second request
213240b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
213340b4f539SKevin Wolf 
2134cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
213540b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
213640b4f539SKevin Wolf 
213740b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
213840b4f539SKevin Wolf         } else {
213940b4f539SKevin Wolf             outidx++;
214040b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
214140b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
214240b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
214340b4f539SKevin Wolf         }
214440b4f539SKevin Wolf     }
214540b4f539SKevin Wolf 
214640b4f539SKevin Wolf     return outidx + 1;
214740b4f539SKevin Wolf }
214840b4f539SKevin Wolf 
214940b4f539SKevin Wolf /*
215040b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
215140b4f539SKevin Wolf  *
215240b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
215340b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
215440b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
215540b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
215640b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
215740b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
215840b4f539SKevin Wolf  *
215940b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
216040b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
216140b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
216240b4f539SKevin Wolf  */
216340b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
216440b4f539SKevin Wolf {
216540b4f539SKevin Wolf     BlockDriverAIOCB *acb;
216640b4f539SKevin Wolf     MultiwriteCB *mcb;
216740b4f539SKevin Wolf     int i;
216840b4f539SKevin Wolf 
216940b4f539SKevin Wolf     if (num_reqs == 0) {
217040b4f539SKevin Wolf         return 0;
217140b4f539SKevin Wolf     }
217240b4f539SKevin Wolf 
217340b4f539SKevin Wolf     // Create MultiwriteCB structure
217440b4f539SKevin Wolf     mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
217540b4f539SKevin Wolf     mcb->num_requests = 0;
217640b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
217740b4f539SKevin Wolf 
217840b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
217940b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
218040b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
218140b4f539SKevin Wolf     }
218240b4f539SKevin Wolf 
218340b4f539SKevin Wolf     // Check for mergable requests
218440b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
218540b4f539SKevin Wolf 
218640b4f539SKevin Wolf     // Run the aio requests
218740b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
218840b4f539SKevin Wolf         acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
218940b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
219040b4f539SKevin Wolf 
219140b4f539SKevin Wolf         if (acb == NULL) {
219240b4f539SKevin Wolf             // We can only fail the whole thing if no request has been
219340b4f539SKevin Wolf             // submitted yet. Otherwise we'll wait for the submitted AIOs to
219440b4f539SKevin Wolf             // complete and report the error in the callback.
219540b4f539SKevin Wolf             if (mcb->num_requests == 0) {
21960f0b604bSKevin Wolf                 reqs[i].error = -EIO;
219740b4f539SKevin Wolf                 goto fail;
219840b4f539SKevin Wolf             } else {
21997eb58a6cSKevin Wolf                 mcb->num_requests++;
22007eb58a6cSKevin Wolf                 multiwrite_cb(mcb, -EIO);
220140b4f539SKevin Wolf                 break;
220240b4f539SKevin Wolf             }
220340b4f539SKevin Wolf         } else {
220440b4f539SKevin Wolf             mcb->num_requests++;
220540b4f539SKevin Wolf         }
220640b4f539SKevin Wolf     }
220740b4f539SKevin Wolf 
220840b4f539SKevin Wolf     return 0;
220940b4f539SKevin Wolf 
221040b4f539SKevin Wolf fail:
2211af474591SBruce Rogers     qemu_free(mcb);
221240b4f539SKevin Wolf     return -1;
221340b4f539SKevin Wolf }
221440b4f539SKevin Wolf 
2215b2e12bc6SChristoph Hellwig BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2216b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2217b2e12bc6SChristoph Hellwig {
2218b2e12bc6SChristoph Hellwig     BlockDriver *drv = bs->drv;
2219b2e12bc6SChristoph Hellwig 
2220016f5cf6SAlexander Graf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2221016f5cf6SAlexander Graf         return bdrv_aio_noop_em(bs, cb, opaque);
2222016f5cf6SAlexander Graf     }
2223016f5cf6SAlexander Graf 
2224b2e12bc6SChristoph Hellwig     if (!drv)
2225b2e12bc6SChristoph Hellwig         return NULL;
2226b2e12bc6SChristoph Hellwig     return drv->bdrv_aio_flush(bs, cb, opaque);
2227b2e12bc6SChristoph Hellwig }
2228b2e12bc6SChristoph Hellwig 
222983f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
223083f64091Sbellard {
22316bbff9a0Saliguori     acb->pool->cancel(acb);
223283f64091Sbellard }
223383f64091Sbellard 
223483f64091Sbellard 
223583f64091Sbellard /**************************************************************/
223683f64091Sbellard /* async block device emulation */
223783f64091Sbellard 
2238c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
2239c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
2240c16b5a2cSChristoph Hellwig     QEMUBH *bh;
2241c16b5a2cSChristoph Hellwig     int ret;
2242c16b5a2cSChristoph Hellwig     /* vector translation state */
2243c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
2244c16b5a2cSChristoph Hellwig     uint8_t *bounce;
2245c16b5a2cSChristoph Hellwig     int is_write;
2246c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
2247c16b5a2cSChristoph Hellwig 
2248c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2249c16b5a2cSChristoph Hellwig {
2250b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
2251b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
22526a7ad299SDor Laor     qemu_bh_delete(acb->bh);
225336afc451SAvi Kivity     acb->bh = NULL;
2254c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
2255c16b5a2cSChristoph Hellwig }
2256c16b5a2cSChristoph Hellwig 
2257c16b5a2cSChristoph Hellwig static AIOPool bdrv_em_aio_pool = {
2258c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2259c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
2260c16b5a2cSChristoph Hellwig };
2261c16b5a2cSChristoph Hellwig 
226283f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
2263beac80cdSbellard {
2264ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
2265f141eafeSaliguori 
2266f141eafeSaliguori     if (!acb->is_write)
2267f141eafeSaliguori         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2268ceb42de8Saliguori     qemu_vfree(acb->bounce);
2269ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
22706a7ad299SDor Laor     qemu_bh_delete(acb->bh);
227136afc451SAvi Kivity     acb->bh = NULL;
2272ce1a14dcSpbrook     qemu_aio_release(acb);
2273beac80cdSbellard }
2274beac80cdSbellard 
2275f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2276f141eafeSaliguori                                             int64_t sector_num,
2277f141eafeSaliguori                                             QEMUIOVector *qiov,
2278f141eafeSaliguori                                             int nb_sectors,
2279f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
2280f141eafeSaliguori                                             void *opaque,
2281f141eafeSaliguori                                             int is_write)
2282f141eafeSaliguori 
2283ea2384d3Sbellard {
2284ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
228583f64091Sbellard 
2286c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2287f141eafeSaliguori     acb->is_write = is_write;
2288f141eafeSaliguori     acb->qiov = qiov;
2289e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
2290f141eafeSaliguori 
2291ce1a14dcSpbrook     if (!acb->bh)
2292ce1a14dcSpbrook         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2293f141eafeSaliguori 
2294f141eafeSaliguori     if (is_write) {
2295f141eafeSaliguori         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2296f141eafeSaliguori         acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2297f141eafeSaliguori     } else {
2298f141eafeSaliguori         acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2299f141eafeSaliguori     }
2300f141eafeSaliguori 
2301ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
2302f141eafeSaliguori 
2303ce1a14dcSpbrook     return &acb->common;
23047a6cba61Spbrook }
23057a6cba61Spbrook 
2306f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2307f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2308ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
230983f64091Sbellard {
2310f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
231183f64091Sbellard }
231283f64091Sbellard 
2313f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2314f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2315f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
2316f141eafeSaliguori {
2317f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2318f141eafeSaliguori }
2319f141eafeSaliguori 
2320b2e12bc6SChristoph Hellwig static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2321b2e12bc6SChristoph Hellwig         BlockDriverCompletionFunc *cb, void *opaque)
2322b2e12bc6SChristoph Hellwig {
2323b2e12bc6SChristoph Hellwig     BlockDriverAIOCBSync *acb;
2324b2e12bc6SChristoph Hellwig 
2325b2e12bc6SChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2326b2e12bc6SChristoph Hellwig     acb->is_write = 1; /* don't bounce in the completion hadler */
2327b2e12bc6SChristoph Hellwig     acb->qiov = NULL;
2328b2e12bc6SChristoph Hellwig     acb->bounce = NULL;
2329b2e12bc6SChristoph Hellwig     acb->ret = 0;
2330b2e12bc6SChristoph Hellwig 
2331b2e12bc6SChristoph Hellwig     if (!acb->bh)
2332b2e12bc6SChristoph Hellwig         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2333b2e12bc6SChristoph Hellwig 
2334b2e12bc6SChristoph Hellwig     bdrv_flush(bs);
2335b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
2336b2e12bc6SChristoph Hellwig     return &acb->common;
2337b2e12bc6SChristoph Hellwig }
2338b2e12bc6SChristoph Hellwig 
2339016f5cf6SAlexander Graf static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2340016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
2341016f5cf6SAlexander Graf {
2342016f5cf6SAlexander Graf     BlockDriverAIOCBSync *acb;
2343016f5cf6SAlexander Graf 
2344016f5cf6SAlexander Graf     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2345016f5cf6SAlexander Graf     acb->is_write = 1; /* don't bounce in the completion handler */
2346016f5cf6SAlexander Graf     acb->qiov = NULL;
2347016f5cf6SAlexander Graf     acb->bounce = NULL;
2348016f5cf6SAlexander Graf     acb->ret = 0;
2349016f5cf6SAlexander Graf 
2350016f5cf6SAlexander Graf     if (!acb->bh) {
2351016f5cf6SAlexander Graf         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2352016f5cf6SAlexander Graf     }
2353016f5cf6SAlexander Graf 
2354016f5cf6SAlexander Graf     qemu_bh_schedule(acb->bh);
2355016f5cf6SAlexander Graf     return &acb->common;
2356016f5cf6SAlexander Graf }
2357016f5cf6SAlexander Graf 
235883f64091Sbellard /**************************************************************/
235983f64091Sbellard /* sync block device emulation */
236083f64091Sbellard 
236183f64091Sbellard static void bdrv_rw_em_cb(void *opaque, int ret)
236283f64091Sbellard {
236383f64091Sbellard     *(int *)opaque = ret;
236483f64091Sbellard }
236583f64091Sbellard 
236683f64091Sbellard #define NOT_DONE 0x7fffffff
236783f64091Sbellard 
236883f64091Sbellard static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
236983f64091Sbellard                         uint8_t *buf, int nb_sectors)
237083f64091Sbellard {
2371ce1a14dcSpbrook     int async_ret;
2372ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2373f141eafeSaliguori     struct iovec iov;
2374f141eafeSaliguori     QEMUIOVector qiov;
237583f64091Sbellard 
237665d6b3d8SKevin Wolf     async_context_push();
237765d6b3d8SKevin Wolf 
237883f64091Sbellard     async_ret = NOT_DONE;
23793f4cb3d3Sblueswir1     iov.iov_base = (void *)buf;
2380eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2381f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2382f141eafeSaliguori     acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
238383f64091Sbellard         bdrv_rw_em_cb, &async_ret);
238465d6b3d8SKevin Wolf     if (acb == NULL) {
238565d6b3d8SKevin Wolf         async_ret = -1;
238665d6b3d8SKevin Wolf         goto fail;
238765d6b3d8SKevin Wolf     }
2388baf35cb9Saliguori 
238983f64091Sbellard     while (async_ret == NOT_DONE) {
239083f64091Sbellard         qemu_aio_wait();
239183f64091Sbellard     }
2392baf35cb9Saliguori 
239365d6b3d8SKevin Wolf 
239465d6b3d8SKevin Wolf fail:
239565d6b3d8SKevin Wolf     async_context_pop();
239683f64091Sbellard     return async_ret;
239783f64091Sbellard }
239883f64091Sbellard 
239983f64091Sbellard static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
240083f64091Sbellard                          const uint8_t *buf, int nb_sectors)
240183f64091Sbellard {
2402ce1a14dcSpbrook     int async_ret;
2403ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2404f141eafeSaliguori     struct iovec iov;
2405f141eafeSaliguori     QEMUIOVector qiov;
240683f64091Sbellard 
240765d6b3d8SKevin Wolf     async_context_push();
240865d6b3d8SKevin Wolf 
240983f64091Sbellard     async_ret = NOT_DONE;
2410f141eafeSaliguori     iov.iov_base = (void *)buf;
2411eb5a3165SJes Sorensen     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2412f141eafeSaliguori     qemu_iovec_init_external(&qiov, &iov, 1);
2413f141eafeSaliguori     acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
241483f64091Sbellard         bdrv_rw_em_cb, &async_ret);
241565d6b3d8SKevin Wolf     if (acb == NULL) {
241665d6b3d8SKevin Wolf         async_ret = -1;
241765d6b3d8SKevin Wolf         goto fail;
241865d6b3d8SKevin Wolf     }
241983f64091Sbellard     while (async_ret == NOT_DONE) {
242083f64091Sbellard         qemu_aio_wait();
242183f64091Sbellard     }
242265d6b3d8SKevin Wolf 
242365d6b3d8SKevin Wolf fail:
242465d6b3d8SKevin Wolf     async_context_pop();
242583f64091Sbellard     return async_ret;
242683f64091Sbellard }
2427ea2384d3Sbellard 
2428ea2384d3Sbellard void bdrv_init(void)
2429ea2384d3Sbellard {
24305efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
2431ea2384d3Sbellard }
2432ce1a14dcSpbrook 
2433eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
2434eb852011SMarkus Armbruster {
2435eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
2436eb852011SMarkus Armbruster     bdrv_init();
2437eb852011SMarkus Armbruster }
2438eb852011SMarkus Armbruster 
2439c16b5a2cSChristoph Hellwig void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
24406bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
24416bbff9a0Saliguori {
2442ce1a14dcSpbrook     BlockDriverAIOCB *acb;
2443ce1a14dcSpbrook 
24446bbff9a0Saliguori     if (pool->free_aiocb) {
24456bbff9a0Saliguori         acb = pool->free_aiocb;
24466bbff9a0Saliguori         pool->free_aiocb = acb->next;
2447ce1a14dcSpbrook     } else {
24486bbff9a0Saliguori         acb = qemu_mallocz(pool->aiocb_size);
24496bbff9a0Saliguori         acb->pool = pool;
2450ce1a14dcSpbrook     }
2451ce1a14dcSpbrook     acb->bs = bs;
2452ce1a14dcSpbrook     acb->cb = cb;
2453ce1a14dcSpbrook     acb->opaque = opaque;
2454ce1a14dcSpbrook     return acb;
2455ce1a14dcSpbrook }
2456ce1a14dcSpbrook 
2457ce1a14dcSpbrook void qemu_aio_release(void *p)
2458ce1a14dcSpbrook {
24596bbff9a0Saliguori     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
24606bbff9a0Saliguori     AIOPool *pool = acb->pool;
24616bbff9a0Saliguori     acb->next = pool->free_aiocb;
24626bbff9a0Saliguori     pool->free_aiocb = acb;
2463ce1a14dcSpbrook }
246419cb3738Sbellard 
246519cb3738Sbellard /**************************************************************/
246619cb3738Sbellard /* removable device support */
246719cb3738Sbellard 
246819cb3738Sbellard /**
246919cb3738Sbellard  * Return TRUE if the media is present
247019cb3738Sbellard  */
247119cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
247219cb3738Sbellard {
247319cb3738Sbellard     BlockDriver *drv = bs->drv;
247419cb3738Sbellard     int ret;
247519cb3738Sbellard     if (!drv)
247619cb3738Sbellard         return 0;
247719cb3738Sbellard     if (!drv->bdrv_is_inserted)
247819cb3738Sbellard         return 1;
247919cb3738Sbellard     ret = drv->bdrv_is_inserted(bs);
248019cb3738Sbellard     return ret;
248119cb3738Sbellard }
248219cb3738Sbellard 
248319cb3738Sbellard /**
248419cb3738Sbellard  * Return TRUE if the media changed since the last call to this
248519cb3738Sbellard  * function. It is currently only used for floppy disks
248619cb3738Sbellard  */
248719cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
248819cb3738Sbellard {
248919cb3738Sbellard     BlockDriver *drv = bs->drv;
249019cb3738Sbellard     int ret;
249119cb3738Sbellard 
249219cb3738Sbellard     if (!drv || !drv->bdrv_media_changed)
249319cb3738Sbellard         ret = -ENOTSUP;
249419cb3738Sbellard     else
249519cb3738Sbellard         ret = drv->bdrv_media_changed(bs);
249619cb3738Sbellard     if (ret == -ENOTSUP)
249719cb3738Sbellard         ret = bs->media_changed;
249819cb3738Sbellard     bs->media_changed = 0;
249919cb3738Sbellard     return ret;
250019cb3738Sbellard }
250119cb3738Sbellard 
250219cb3738Sbellard /**
250319cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
250419cb3738Sbellard  */
2505aea2a33cSMark McLoughlin int bdrv_eject(BlockDriverState *bs, int eject_flag)
250619cb3738Sbellard {
250719cb3738Sbellard     BlockDriver *drv = bs->drv;
250819cb3738Sbellard     int ret;
250919cb3738Sbellard 
2510aea2a33cSMark McLoughlin     if (bs->locked) {
2511aea2a33cSMark McLoughlin         return -EBUSY;
2512aea2a33cSMark McLoughlin     }
2513aea2a33cSMark McLoughlin 
251419cb3738Sbellard     if (!drv || !drv->bdrv_eject) {
251519cb3738Sbellard         ret = -ENOTSUP;
251619cb3738Sbellard     } else {
251719cb3738Sbellard         ret = drv->bdrv_eject(bs, eject_flag);
251819cb3738Sbellard     }
251919cb3738Sbellard     if (ret == -ENOTSUP) {
252019cb3738Sbellard         if (eject_flag)
252119cb3738Sbellard             bdrv_close(bs);
2522aea2a33cSMark McLoughlin         ret = 0;
252319cb3738Sbellard     }
2524aea2a33cSMark McLoughlin 
2525aea2a33cSMark McLoughlin     return ret;
252619cb3738Sbellard }
252719cb3738Sbellard 
252819cb3738Sbellard int bdrv_is_locked(BlockDriverState *bs)
252919cb3738Sbellard {
253019cb3738Sbellard     return bs->locked;
253119cb3738Sbellard }
253219cb3738Sbellard 
253319cb3738Sbellard /**
253419cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
253519cb3738Sbellard  * to eject it manually).
253619cb3738Sbellard  */
253719cb3738Sbellard void bdrv_set_locked(BlockDriverState *bs, int locked)
253819cb3738Sbellard {
253919cb3738Sbellard     BlockDriver *drv = bs->drv;
254019cb3738Sbellard 
254119cb3738Sbellard     bs->locked = locked;
254219cb3738Sbellard     if (drv && drv->bdrv_set_locked) {
254319cb3738Sbellard         drv->bdrv_set_locked(bs, locked);
254419cb3738Sbellard     }
254519cb3738Sbellard }
2546985a03b0Sths 
2547985a03b0Sths /* needed for generic scsi interface */
2548985a03b0Sths 
2549985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2550985a03b0Sths {
2551985a03b0Sths     BlockDriver *drv = bs->drv;
2552985a03b0Sths 
2553985a03b0Sths     if (drv && drv->bdrv_ioctl)
2554985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
2555985a03b0Sths     return -ENOTSUP;
2556985a03b0Sths }
25577d780669Saliguori 
2558221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2559221f715dSaliguori         unsigned long int req, void *buf,
25607d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
25617d780669Saliguori {
2562221f715dSaliguori     BlockDriver *drv = bs->drv;
25637d780669Saliguori 
2564221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
2565221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2566221f715dSaliguori     return NULL;
25677d780669Saliguori }
2568e268ca52Saliguori 
25697cd1e32aSlirans@il.ibm.com 
25707cd1e32aSlirans@il.ibm.com 
2571e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
2572e268ca52Saliguori {
2573e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2574e268ca52Saliguori }
25757cd1e32aSlirans@il.ibm.com 
25767cd1e32aSlirans@il.ibm.com void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
25777cd1e32aSlirans@il.ibm.com {
25787cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
2579a55eb92cSJan Kiszka 
2580aaa0eb75SLiran Schour     bs->dirty_count = 0;
25817cd1e32aSlirans@il.ibm.com     if (enable) {
2582c6d22830SJan Kiszka         if (!bs->dirty_bitmap) {
2583c6d22830SJan Kiszka             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2584c6d22830SJan Kiszka                     BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2585c6d22830SJan Kiszka             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
25867cd1e32aSlirans@il.ibm.com 
25877cd1e32aSlirans@il.ibm.com             bs->dirty_bitmap = qemu_mallocz(bitmap_size);
25887cd1e32aSlirans@il.ibm.com         }
25897cd1e32aSlirans@il.ibm.com     } else {
2590c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
25917cd1e32aSlirans@il.ibm.com             qemu_free(bs->dirty_bitmap);
2592c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
25937cd1e32aSlirans@il.ibm.com         }
25947cd1e32aSlirans@il.ibm.com     }
25957cd1e32aSlirans@il.ibm.com }
25967cd1e32aSlirans@il.ibm.com 
25977cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
25987cd1e32aSlirans@il.ibm.com {
25996ea44308SJan Kiszka     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
26007cd1e32aSlirans@il.ibm.com 
2601c6d22830SJan Kiszka     if (bs->dirty_bitmap &&
2602c6d22830SJan Kiszka         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2603c6d22830SJan Kiszka         return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2604c6d22830SJan Kiszka             (1 << (chunk % (sizeof(unsigned long) * 8)));
26057cd1e32aSlirans@il.ibm.com     } else {
26067cd1e32aSlirans@il.ibm.com         return 0;
26077cd1e32aSlirans@il.ibm.com     }
26087cd1e32aSlirans@il.ibm.com }
26097cd1e32aSlirans@il.ibm.com 
26107cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
26117cd1e32aSlirans@il.ibm.com                       int nr_sectors)
26127cd1e32aSlirans@il.ibm.com {
26137cd1e32aSlirans@il.ibm.com     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
26147cd1e32aSlirans@il.ibm.com }
2615aaa0eb75SLiran Schour 
2616aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2617aaa0eb75SLiran Schour {
2618aaa0eb75SLiran Schour     return bs->dirty_count;
2619aaa0eb75SLiran Schour }
2620