Statistics
| Branch: | Revision:

root / block.c @ 00a152b4

History | View | Annotate | Download (81.6 kB)

1 fc01f7e7 bellard
/*
2 fc01f7e7 bellard
 * QEMU System Emulator block driver
3 5fafdf24 ths
 *
4 fc01f7e7 bellard
 * Copyright (c) 2003 Fabrice Bellard
5 5fafdf24 ths
 *
6 fc01f7e7 bellard
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 fc01f7e7 bellard
 * of this software and associated documentation files (the "Software"), to deal
8 fc01f7e7 bellard
 * in the Software without restriction, including without limitation the rights
9 fc01f7e7 bellard
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 fc01f7e7 bellard
 * copies of the Software, and to permit persons to whom the Software is
11 fc01f7e7 bellard
 * furnished to do so, subject to the following conditions:
12 fc01f7e7 bellard
 *
13 fc01f7e7 bellard
 * The above copyright notice and this permission notice shall be included in
14 fc01f7e7 bellard
 * all copies or substantial portions of the Software.
15 fc01f7e7 bellard
 *
16 fc01f7e7 bellard
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 fc01f7e7 bellard
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 fc01f7e7 bellard
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 fc01f7e7 bellard
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 fc01f7e7 bellard
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 fc01f7e7 bellard
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 fc01f7e7 bellard
 * THE SOFTWARE.
23 fc01f7e7 bellard
 */
24 3990d09a blueswir1
#include "config-host.h"
25 faf07963 pbrook
#include "qemu-common.h"
26 6d519a5f Stefan Hajnoczi
#include "trace.h"
27 376253ec aliguori
#include "monitor.h"
28 ea2384d3 bellard
#include "block_int.h"
29 5efa9d5a Anthony Liguori
#include "module.h"
30 d15e5465 Luiz Capitulino
#include "qemu-objects.h"
31 fc01f7e7 bellard
32 71e72a19 Juan Quintela
#ifdef CONFIG_BSD
33 7674e7bf bellard
#include <sys/types.h>
34 7674e7bf bellard
#include <sys/stat.h>
35 7674e7bf bellard
#include <sys/ioctl.h>
36 72cf2d4f Blue Swirl
#include <sys/queue.h>
37 c5e97233 blueswir1
#ifndef __DragonFly__
38 7674e7bf bellard
#include <sys/disk.h>
39 7674e7bf bellard
#endif
40 c5e97233 blueswir1
#endif
41 7674e7bf bellard
42 49dc768d aliguori
#ifdef _WIN32
43 49dc768d aliguori
#include <windows.h>
44 49dc768d aliguori
#endif
45 49dc768d aliguori
46 f141eafe aliguori
static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
47 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
48 c87c0672 aliguori
        BlockDriverCompletionFunc *cb, void *opaque);
49 f141eafe aliguori
static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
50 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
51 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque);
52 b2e12bc6 Christoph Hellwig
static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
53 b2e12bc6 Christoph Hellwig
        BlockDriverCompletionFunc *cb, void *opaque);
54 016f5cf6 Alexander Graf
static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
55 016f5cf6 Alexander Graf
        BlockDriverCompletionFunc *cb, void *opaque);
56 5fafdf24 ths
static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
57 83f64091 bellard
                        uint8_t *buf, int nb_sectors);
58 83f64091 bellard
static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
59 83f64091 bellard
                         const uint8_t *buf, int nb_sectors);
60 ec530c81 bellard
61 1b7bdbc1 Stefan Hajnoczi
static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
62 1b7bdbc1 Stefan Hajnoczi
    QTAILQ_HEAD_INITIALIZER(bdrv_states);
63 7ee930d0 blueswir1
64 8a22f02a Stefan Hajnoczi
static QLIST_HEAD(, BlockDriver) bdrv_drivers =
65 8a22f02a Stefan Hajnoczi
    QLIST_HEAD_INITIALIZER(bdrv_drivers);
66 ea2384d3 bellard
67 f9092b10 Markus Armbruster
/* The device to use for VM snapshots */
68 f9092b10 Markus Armbruster
static BlockDriverState *bs_snapshots;
69 f9092b10 Markus Armbruster
70 eb852011 Markus Armbruster
/* If non-zero, use only whitelisted block drivers */
71 eb852011 Markus Armbruster
static int use_bdrv_whitelist;
72 eb852011 Markus Armbruster
73 9e0b22f4 Stefan Hajnoczi
#ifdef _WIN32
74 9e0b22f4 Stefan Hajnoczi
static int is_windows_drive_prefix(const char *filename)
75 9e0b22f4 Stefan Hajnoczi
{
76 9e0b22f4 Stefan Hajnoczi
    return (((filename[0] >= 'a' && filename[0] <= 'z') ||
77 9e0b22f4 Stefan Hajnoczi
             (filename[0] >= 'A' && filename[0] <= 'Z')) &&
78 9e0b22f4 Stefan Hajnoczi
            filename[1] == ':');
79 9e0b22f4 Stefan Hajnoczi
}
80 9e0b22f4 Stefan Hajnoczi
81 9e0b22f4 Stefan Hajnoczi
int is_windows_drive(const char *filename)
82 9e0b22f4 Stefan Hajnoczi
{
83 9e0b22f4 Stefan Hajnoczi
    if (is_windows_drive_prefix(filename) &&
84 9e0b22f4 Stefan Hajnoczi
        filename[2] == '\0')
85 9e0b22f4 Stefan Hajnoczi
        return 1;
86 9e0b22f4 Stefan Hajnoczi
    if (strstart(filename, "\\\\.\\", NULL) ||
87 9e0b22f4 Stefan Hajnoczi
        strstart(filename, "//./", NULL))
88 9e0b22f4 Stefan Hajnoczi
        return 1;
89 9e0b22f4 Stefan Hajnoczi
    return 0;
90 9e0b22f4 Stefan Hajnoczi
}
91 9e0b22f4 Stefan Hajnoczi
#endif
92 9e0b22f4 Stefan Hajnoczi
93 9e0b22f4 Stefan Hajnoczi
/* check if the path starts with "<protocol>:" */
94 9e0b22f4 Stefan Hajnoczi
static int path_has_protocol(const char *path)
95 9e0b22f4 Stefan Hajnoczi
{
96 9e0b22f4 Stefan Hajnoczi
#ifdef _WIN32
97 9e0b22f4 Stefan Hajnoczi
    if (is_windows_drive(path) ||
98 9e0b22f4 Stefan Hajnoczi
        is_windows_drive_prefix(path)) {
99 9e0b22f4 Stefan Hajnoczi
        return 0;
100 9e0b22f4 Stefan Hajnoczi
    }
101 9e0b22f4 Stefan Hajnoczi
#endif
102 9e0b22f4 Stefan Hajnoczi
103 9e0b22f4 Stefan Hajnoczi
    return strchr(path, ':') != NULL;
104 9e0b22f4 Stefan Hajnoczi
}
105 9e0b22f4 Stefan Hajnoczi
106 83f64091 bellard
int path_is_absolute(const char *path)
107 3b0d4f61 bellard
{
108 83f64091 bellard
    const char *p;
109 21664424 bellard
#ifdef _WIN32
110 21664424 bellard
    /* specific case for names like: "\\.\d:" */
111 21664424 bellard
    if (*path == '/' || *path == '\\')
112 21664424 bellard
        return 1;
113 21664424 bellard
#endif
114 83f64091 bellard
    p = strchr(path, ':');
115 83f64091 bellard
    if (p)
116 83f64091 bellard
        p++;
117 83f64091 bellard
    else
118 83f64091 bellard
        p = path;
119 3b9f94e1 bellard
#ifdef _WIN32
120 3b9f94e1 bellard
    return (*p == '/' || *p == '\\');
121 3b9f94e1 bellard
#else
122 3b9f94e1 bellard
    return (*p == '/');
123 3b9f94e1 bellard
#endif
124 3b0d4f61 bellard
}
125 3b0d4f61 bellard
126 83f64091 bellard
/* if filename is absolute, just copy it to dest. Otherwise, build a
127 83f64091 bellard
   path to it by considering it is relative to base_path. URL are
128 83f64091 bellard
   supported. */
129 83f64091 bellard
void path_combine(char *dest, int dest_size,
130 83f64091 bellard
                  const char *base_path,
131 83f64091 bellard
                  const char *filename)
132 3b0d4f61 bellard
{
133 83f64091 bellard
    const char *p, *p1;
134 83f64091 bellard
    int len;
135 83f64091 bellard
136 83f64091 bellard
    if (dest_size <= 0)
137 83f64091 bellard
        return;
138 83f64091 bellard
    if (path_is_absolute(filename)) {
139 83f64091 bellard
        pstrcpy(dest, dest_size, filename);
140 83f64091 bellard
    } else {
141 83f64091 bellard
        p = strchr(base_path, ':');
142 83f64091 bellard
        if (p)
143 83f64091 bellard
            p++;
144 83f64091 bellard
        else
145 83f64091 bellard
            p = base_path;
146 3b9f94e1 bellard
        p1 = strrchr(base_path, '/');
147 3b9f94e1 bellard
#ifdef _WIN32
148 3b9f94e1 bellard
        {
149 3b9f94e1 bellard
            const char *p2;
150 3b9f94e1 bellard
            p2 = strrchr(base_path, '\\');
151 3b9f94e1 bellard
            if (!p1 || p2 > p1)
152 3b9f94e1 bellard
                p1 = p2;
153 3b9f94e1 bellard
        }
154 3b9f94e1 bellard
#endif
155 83f64091 bellard
        if (p1)
156 83f64091 bellard
            p1++;
157 83f64091 bellard
        else
158 83f64091 bellard
            p1 = base_path;
159 83f64091 bellard
        if (p1 > p)
160 83f64091 bellard
            p = p1;
161 83f64091 bellard
        len = p - base_path;
162 83f64091 bellard
        if (len > dest_size - 1)
163 83f64091 bellard
            len = dest_size - 1;
164 83f64091 bellard
        memcpy(dest, base_path, len);
165 83f64091 bellard
        dest[len] = '\0';
166 83f64091 bellard
        pstrcat(dest, dest_size, filename);
167 3b0d4f61 bellard
    }
168 3b0d4f61 bellard
}
169 3b0d4f61 bellard
170 5efa9d5a Anthony Liguori
void bdrv_register(BlockDriver *bdrv)
171 ea2384d3 bellard
{
172 f141eafe aliguori
    if (!bdrv->bdrv_aio_readv) {
173 83f64091 bellard
        /* add AIO emulation layer */
174 f141eafe aliguori
        bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
175 f141eafe aliguori
        bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
176 eda578e5 aliguori
    } else if (!bdrv->bdrv_read) {
177 83f64091 bellard
        /* add synchronous IO emulation layer */
178 83f64091 bellard
        bdrv->bdrv_read = bdrv_read_em;
179 83f64091 bellard
        bdrv->bdrv_write = bdrv_write_em;
180 83f64091 bellard
    }
181 b2e12bc6 Christoph Hellwig
182 b2e12bc6 Christoph Hellwig
    if (!bdrv->bdrv_aio_flush)
183 b2e12bc6 Christoph Hellwig
        bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
184 b2e12bc6 Christoph Hellwig
185 8a22f02a Stefan Hajnoczi
    QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
186 ea2384d3 bellard
}
187 b338082b bellard
188 b338082b bellard
/* create a new block device (by default it is empty) */
189 b338082b bellard
BlockDriverState *bdrv_new(const char *device_name)
190 b338082b bellard
{
191 1b7bdbc1 Stefan Hajnoczi
    BlockDriverState *bs;
192 b338082b bellard
193 b338082b bellard
    bs = qemu_mallocz(sizeof(BlockDriverState));
194 b338082b bellard
    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
195 ea2384d3 bellard
    if (device_name[0] != '\0') {
196 1b7bdbc1 Stefan Hajnoczi
        QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
197 ea2384d3 bellard
    }
198 b338082b bellard
    return bs;
199 b338082b bellard
}
200 b338082b bellard
201 ea2384d3 bellard
BlockDriver *bdrv_find_format(const char *format_name)
202 ea2384d3 bellard
{
203 ea2384d3 bellard
    BlockDriver *drv1;
204 8a22f02a Stefan Hajnoczi
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
205 8a22f02a Stefan Hajnoczi
        if (!strcmp(drv1->format_name, format_name)) {
206 ea2384d3 bellard
            return drv1;
207 8a22f02a Stefan Hajnoczi
        }
208 ea2384d3 bellard
    }
209 ea2384d3 bellard
    return NULL;
210 ea2384d3 bellard
}
211 ea2384d3 bellard
212 eb852011 Markus Armbruster
static int bdrv_is_whitelisted(BlockDriver *drv)
213 eb852011 Markus Armbruster
{
214 eb852011 Markus Armbruster
    static const char *whitelist[] = {
215 eb852011 Markus Armbruster
        CONFIG_BDRV_WHITELIST
216 eb852011 Markus Armbruster
    };
217 eb852011 Markus Armbruster
    const char **p;
218 eb852011 Markus Armbruster
219 eb852011 Markus Armbruster
    if (!whitelist[0])
220 eb852011 Markus Armbruster
        return 1;               /* no whitelist, anything goes */
221 eb852011 Markus Armbruster
222 eb852011 Markus Armbruster
    for (p = whitelist; *p; p++) {
223 eb852011 Markus Armbruster
        if (!strcmp(drv->format_name, *p)) {
224 eb852011 Markus Armbruster
            return 1;
225 eb852011 Markus Armbruster
        }
226 eb852011 Markus Armbruster
    }
227 eb852011 Markus Armbruster
    return 0;
228 eb852011 Markus Armbruster
}
229 eb852011 Markus Armbruster
230 eb852011 Markus Armbruster
BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
231 eb852011 Markus Armbruster
{
232 eb852011 Markus Armbruster
    BlockDriver *drv = bdrv_find_format(format_name);
233 eb852011 Markus Armbruster
    return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
234 eb852011 Markus Armbruster
}
235 eb852011 Markus Armbruster
236 0e7e1989 Kevin Wolf
int bdrv_create(BlockDriver *drv, const char* filename,
237 0e7e1989 Kevin Wolf
    QEMUOptionParameter *options)
238 ea2384d3 bellard
{
239 ea2384d3 bellard
    if (!drv->bdrv_create)
240 ea2384d3 bellard
        return -ENOTSUP;
241 0e7e1989 Kevin Wolf
242 0e7e1989 Kevin Wolf
    return drv->bdrv_create(filename, options);
243 ea2384d3 bellard
}
244 ea2384d3 bellard
245 84a12e66 Christoph Hellwig
int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
246 84a12e66 Christoph Hellwig
{
247 84a12e66 Christoph Hellwig
    BlockDriver *drv;
248 84a12e66 Christoph Hellwig
249 b50cbabc MORITA Kazutaka
    drv = bdrv_find_protocol(filename);
250 84a12e66 Christoph Hellwig
    if (drv == NULL) {
251 16905d71 Stefan Hajnoczi
        return -ENOENT;
252 84a12e66 Christoph Hellwig
    }
253 84a12e66 Christoph Hellwig
254 84a12e66 Christoph Hellwig
    return bdrv_create(drv, filename, options);
255 84a12e66 Christoph Hellwig
}
256 84a12e66 Christoph Hellwig
257 d5249393 bellard
#ifdef _WIN32
258 95389c86 bellard
void get_tmp_filename(char *filename, int size)
259 d5249393 bellard
{
260 3b9f94e1 bellard
    char temp_dir[MAX_PATH];
261 3b46e624 ths
262 3b9f94e1 bellard
    GetTempPath(MAX_PATH, temp_dir);
263 3b9f94e1 bellard
    GetTempFileName(temp_dir, "qem", 0, filename);
264 d5249393 bellard
}
265 d5249393 bellard
#else
266 95389c86 bellard
void get_tmp_filename(char *filename, int size)
267 fc01f7e7 bellard
{
268 67b915a5 bellard
    int fd;
269 7ccfb2eb blueswir1
    const char *tmpdir;
270 d5249393 bellard
    /* XXX: race condition possible */
271 0badc1ee aurel32
    tmpdir = getenv("TMPDIR");
272 0badc1ee aurel32
    if (!tmpdir)
273 0badc1ee aurel32
        tmpdir = "/tmp";
274 0badc1ee aurel32
    snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
275 ea2384d3 bellard
    fd = mkstemp(filename);
276 ea2384d3 bellard
    close(fd);
277 ea2384d3 bellard
}
278 d5249393 bellard
#endif
279 fc01f7e7 bellard
280 84a12e66 Christoph Hellwig
/*
281 84a12e66 Christoph Hellwig
 * Detect host devices. By convention, /dev/cdrom[N] is always
282 84a12e66 Christoph Hellwig
 * recognized as a host CDROM.
283 84a12e66 Christoph Hellwig
 */
284 84a12e66 Christoph Hellwig
static BlockDriver *find_hdev_driver(const char *filename)
285 84a12e66 Christoph Hellwig
{
286 84a12e66 Christoph Hellwig
    int score_max = 0, score;
287 84a12e66 Christoph Hellwig
    BlockDriver *drv = NULL, *d;
288 84a12e66 Christoph Hellwig
289 84a12e66 Christoph Hellwig
    QLIST_FOREACH(d, &bdrv_drivers, list) {
290 84a12e66 Christoph Hellwig
        if (d->bdrv_probe_device) {
291 84a12e66 Christoph Hellwig
            score = d->bdrv_probe_device(filename);
292 84a12e66 Christoph Hellwig
            if (score > score_max) {
293 84a12e66 Christoph Hellwig
                score_max = score;
294 84a12e66 Christoph Hellwig
                drv = d;
295 84a12e66 Christoph Hellwig
            }
296 84a12e66 Christoph Hellwig
        }
297 84a12e66 Christoph Hellwig
    }
298 84a12e66 Christoph Hellwig
299 84a12e66 Christoph Hellwig
    return drv;
300 84a12e66 Christoph Hellwig
}
301 84a12e66 Christoph Hellwig
302 b50cbabc MORITA Kazutaka
BlockDriver *bdrv_find_protocol(const char *filename)
303 83f64091 bellard
{
304 83f64091 bellard
    BlockDriver *drv1;
305 83f64091 bellard
    char protocol[128];
306 1cec71e3 Anthony Liguori
    int len;
307 83f64091 bellard
    const char *p;
308 19cb3738 bellard
309 66f82cee Kevin Wolf
    /* TODO Drivers without bdrv_file_open must be specified explicitly */
310 66f82cee Kevin Wolf
311 39508e7a Christoph Hellwig
    /*
312 39508e7a Christoph Hellwig
     * XXX(hch): we really should not let host device detection
313 39508e7a Christoph Hellwig
     * override an explicit protocol specification, but moving this
314 39508e7a Christoph Hellwig
     * later breaks access to device names with colons in them.
315 39508e7a Christoph Hellwig
     * Thanks to the brain-dead persistent naming schemes on udev-
316 39508e7a Christoph Hellwig
     * based Linux systems those actually are quite common.
317 39508e7a Christoph Hellwig
     */
318 39508e7a Christoph Hellwig
    drv1 = find_hdev_driver(filename);
319 39508e7a Christoph Hellwig
    if (drv1) {
320 39508e7a Christoph Hellwig
        return drv1;
321 39508e7a Christoph Hellwig
    }
322 39508e7a Christoph Hellwig
323 9e0b22f4 Stefan Hajnoczi
    if (!path_has_protocol(filename)) {
324 39508e7a Christoph Hellwig
        return bdrv_find_format("file");
325 84a12e66 Christoph Hellwig
    }
326 9e0b22f4 Stefan Hajnoczi
    p = strchr(filename, ':');
327 9e0b22f4 Stefan Hajnoczi
    assert(p != NULL);
328 1cec71e3 Anthony Liguori
    len = p - filename;
329 1cec71e3 Anthony Liguori
    if (len > sizeof(protocol) - 1)
330 1cec71e3 Anthony Liguori
        len = sizeof(protocol) - 1;
331 1cec71e3 Anthony Liguori
    memcpy(protocol, filename, len);
332 1cec71e3 Anthony Liguori
    protocol[len] = '\0';
333 8a22f02a Stefan Hajnoczi
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
334 5fafdf24 ths
        if (drv1->protocol_name &&
335 8a22f02a Stefan Hajnoczi
            !strcmp(drv1->protocol_name, protocol)) {
336 83f64091 bellard
            return drv1;
337 8a22f02a Stefan Hajnoczi
        }
338 83f64091 bellard
    }
339 83f64091 bellard
    return NULL;
340 83f64091 bellard
}
341 83f64091 bellard
342 c98ac35d Stefan Weil
static int find_image_format(const char *filename, BlockDriver **pdrv)
343 f3a5d3f8 Christoph Hellwig
{
344 f3a5d3f8 Christoph Hellwig
    int ret, score, score_max;
345 f3a5d3f8 Christoph Hellwig
    BlockDriver *drv1, *drv;
346 f3a5d3f8 Christoph Hellwig
    uint8_t buf[2048];
347 f3a5d3f8 Christoph Hellwig
    BlockDriverState *bs;
348 f3a5d3f8 Christoph Hellwig
349 f5edb014 Naphtali Sprei
    ret = bdrv_file_open(&bs, filename, 0);
350 c98ac35d Stefan Weil
    if (ret < 0) {
351 c98ac35d Stefan Weil
        *pdrv = NULL;
352 c98ac35d Stefan Weil
        return ret;
353 c98ac35d Stefan Weil
    }
354 f8ea0b00 Nicholas Bellinger
355 08a00559 Kevin Wolf
    /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
356 08a00559 Kevin Wolf
    if (bs->sg || !bdrv_is_inserted(bs)) {
357 1a396859 Nicholas A. Bellinger
        bdrv_delete(bs);
358 c98ac35d Stefan Weil
        drv = bdrv_find_format("raw");
359 c98ac35d Stefan Weil
        if (!drv) {
360 c98ac35d Stefan Weil
            ret = -ENOENT;
361 c98ac35d Stefan Weil
        }
362 c98ac35d Stefan Weil
        *pdrv = drv;
363 c98ac35d Stefan Weil
        return ret;
364 1a396859 Nicholas A. Bellinger
    }
365 f8ea0b00 Nicholas Bellinger
366 83f64091 bellard
    ret = bdrv_pread(bs, 0, buf, sizeof(buf));
367 83f64091 bellard
    bdrv_delete(bs);
368 83f64091 bellard
    if (ret < 0) {
369 c98ac35d Stefan Weil
        *pdrv = NULL;
370 c98ac35d Stefan Weil
        return ret;
371 83f64091 bellard
    }
372 83f64091 bellard
373 ea2384d3 bellard
    score_max = 0;
374 84a12e66 Christoph Hellwig
    drv = NULL;
375 8a22f02a Stefan Hajnoczi
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
376 83f64091 bellard
        if (drv1->bdrv_probe) {
377 83f64091 bellard
            score = drv1->bdrv_probe(buf, ret, filename);
378 83f64091 bellard
            if (score > score_max) {
379 83f64091 bellard
                score_max = score;
380 83f64091 bellard
                drv = drv1;
381 83f64091 bellard
            }
382 0849bf08 bellard
        }
383 fc01f7e7 bellard
    }
384 c98ac35d Stefan Weil
    if (!drv) {
385 c98ac35d Stefan Weil
        ret = -ENOENT;
386 c98ac35d Stefan Weil
    }
387 c98ac35d Stefan Weil
    *pdrv = drv;
388 c98ac35d Stefan Weil
    return ret;
389 ea2384d3 bellard
}
390 ea2384d3 bellard
391 51762288 Stefan Hajnoczi
/**
392 51762288 Stefan Hajnoczi
 * Set the current 'total_sectors' value
393 51762288 Stefan Hajnoczi
 */
394 51762288 Stefan Hajnoczi
static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
395 51762288 Stefan Hajnoczi
{
396 51762288 Stefan Hajnoczi
    BlockDriver *drv = bs->drv;
397 51762288 Stefan Hajnoczi
398 396759ad Nicholas Bellinger
    /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
399 396759ad Nicholas Bellinger
    if (bs->sg)
400 396759ad Nicholas Bellinger
        return 0;
401 396759ad Nicholas Bellinger
402 51762288 Stefan Hajnoczi
    /* query actual device if possible, otherwise just trust the hint */
403 51762288 Stefan Hajnoczi
    if (drv->bdrv_getlength) {
404 51762288 Stefan Hajnoczi
        int64_t length = drv->bdrv_getlength(bs);
405 51762288 Stefan Hajnoczi
        if (length < 0) {
406 51762288 Stefan Hajnoczi
            return length;
407 51762288 Stefan Hajnoczi
        }
408 51762288 Stefan Hajnoczi
        hint = length >> BDRV_SECTOR_BITS;
409 51762288 Stefan Hajnoczi
    }
410 51762288 Stefan Hajnoczi
411 51762288 Stefan Hajnoczi
    bs->total_sectors = hint;
412 51762288 Stefan Hajnoczi
    return 0;
413 51762288 Stefan Hajnoczi
}
414 51762288 Stefan Hajnoczi
415 b6ce07aa Kevin Wolf
/*
416 57915332 Kevin Wolf
 * Common part for opening disk images and files
417 57915332 Kevin Wolf
 */
418 57915332 Kevin Wolf
static int bdrv_open_common(BlockDriverState *bs, const char *filename,
419 57915332 Kevin Wolf
    int flags, BlockDriver *drv)
420 57915332 Kevin Wolf
{
421 57915332 Kevin Wolf
    int ret, open_flags;
422 57915332 Kevin Wolf
423 57915332 Kevin Wolf
    assert(drv != NULL);
424 57915332 Kevin Wolf
425 66f82cee Kevin Wolf
    bs->file = NULL;
426 51762288 Stefan Hajnoczi
    bs->total_sectors = 0;
427 57915332 Kevin Wolf
    bs->encrypted = 0;
428 57915332 Kevin Wolf
    bs->valid_key = 0;
429 57915332 Kevin Wolf
    bs->open_flags = flags;
430 57915332 Kevin Wolf
    /* buffer_alignment defaulted to 512, drivers can change this value */
431 57915332 Kevin Wolf
    bs->buffer_alignment = 512;
432 57915332 Kevin Wolf
433 57915332 Kevin Wolf
    pstrcpy(bs->filename, sizeof(bs->filename), filename);
434 57915332 Kevin Wolf
435 57915332 Kevin Wolf
    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
436 57915332 Kevin Wolf
        return -ENOTSUP;
437 57915332 Kevin Wolf
    }
438 57915332 Kevin Wolf
439 57915332 Kevin Wolf
    bs->drv = drv;
440 57915332 Kevin Wolf
    bs->opaque = qemu_mallocz(drv->instance_size);
441 57915332 Kevin Wolf
442 57915332 Kevin Wolf
    /*
443 57915332 Kevin Wolf
     * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
444 57915332 Kevin Wolf
     * write cache to the guest.  We do need the fdatasync to flush
445 57915332 Kevin Wolf
     * out transactions for block allocations, and we maybe have a
446 57915332 Kevin Wolf
     * volatile write cache in our backing device to deal with.
447 57915332 Kevin Wolf
     */
448 57915332 Kevin Wolf
    if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
449 57915332 Kevin Wolf
        bs->enable_write_cache = 1;
450 57915332 Kevin Wolf
451 57915332 Kevin Wolf
    /*
452 57915332 Kevin Wolf
     * Clear flags that are internal to the block layer before opening the
453 57915332 Kevin Wolf
     * image.
454 57915332 Kevin Wolf
     */
455 57915332 Kevin Wolf
    open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
456 57915332 Kevin Wolf
457 57915332 Kevin Wolf
    /*
458 57915332 Kevin Wolf
     * Snapshots should be writeable.
459 57915332 Kevin Wolf
     */
460 57915332 Kevin Wolf
    if (bs->is_temporary) {
461 57915332 Kevin Wolf
        open_flags |= BDRV_O_RDWR;
462 57915332 Kevin Wolf
    }
463 57915332 Kevin Wolf
464 66f82cee Kevin Wolf
    /* Open the image, either directly or using a protocol */
465 66f82cee Kevin Wolf
    if (drv->bdrv_file_open) {
466 66f82cee Kevin Wolf
        ret = drv->bdrv_file_open(bs, filename, open_flags);
467 66f82cee Kevin Wolf
    } else {
468 66f82cee Kevin Wolf
        ret = bdrv_file_open(&bs->file, filename, open_flags);
469 66f82cee Kevin Wolf
        if (ret >= 0) {
470 66f82cee Kevin Wolf
            ret = drv->bdrv_open(bs, open_flags);
471 66f82cee Kevin Wolf
        }
472 66f82cee Kevin Wolf
    }
473 66f82cee Kevin Wolf
474 57915332 Kevin Wolf
    if (ret < 0) {
475 57915332 Kevin Wolf
        goto free_and_fail;
476 57915332 Kevin Wolf
    }
477 57915332 Kevin Wolf
478 57915332 Kevin Wolf
    bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
479 51762288 Stefan Hajnoczi
480 51762288 Stefan Hajnoczi
    ret = refresh_total_sectors(bs, bs->total_sectors);
481 51762288 Stefan Hajnoczi
    if (ret < 0) {
482 51762288 Stefan Hajnoczi
        goto free_and_fail;
483 57915332 Kevin Wolf
    }
484 51762288 Stefan Hajnoczi
485 57915332 Kevin Wolf
#ifndef _WIN32
486 57915332 Kevin Wolf
    if (bs->is_temporary) {
487 57915332 Kevin Wolf
        unlink(filename);
488 57915332 Kevin Wolf
    }
489 57915332 Kevin Wolf
#endif
490 57915332 Kevin Wolf
    return 0;
491 57915332 Kevin Wolf
492 57915332 Kevin Wolf
free_and_fail:
493 66f82cee Kevin Wolf
    if (bs->file) {
494 66f82cee Kevin Wolf
        bdrv_delete(bs->file);
495 66f82cee Kevin Wolf
        bs->file = NULL;
496 66f82cee Kevin Wolf
    }
497 57915332 Kevin Wolf
    qemu_free(bs->opaque);
498 57915332 Kevin Wolf
    bs->opaque = NULL;
499 57915332 Kevin Wolf
    bs->drv = NULL;
500 57915332 Kevin Wolf
    return ret;
501 57915332 Kevin Wolf
}
502 57915332 Kevin Wolf
503 57915332 Kevin Wolf
/*
504 b6ce07aa Kevin Wolf
 * Opens a file using a protocol (file, host_device, nbd, ...)
505 b6ce07aa Kevin Wolf
 */
506 83f64091 bellard
int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
507 ea2384d3 bellard
{
508 83f64091 bellard
    BlockDriverState *bs;
509 6db95603 Christoph Hellwig
    BlockDriver *drv;
510 83f64091 bellard
    int ret;
511 83f64091 bellard
512 b50cbabc MORITA Kazutaka
    drv = bdrv_find_protocol(filename);
513 6db95603 Christoph Hellwig
    if (!drv) {
514 6db95603 Christoph Hellwig
        return -ENOENT;
515 6db95603 Christoph Hellwig
    }
516 6db95603 Christoph Hellwig
517 83f64091 bellard
    bs = bdrv_new("");
518 b6ce07aa Kevin Wolf
    ret = bdrv_open_common(bs, filename, flags, drv);
519 83f64091 bellard
    if (ret < 0) {
520 83f64091 bellard
        bdrv_delete(bs);
521 83f64091 bellard
        return ret;
522 3b0d4f61 bellard
    }
523 71d0770c aliguori
    bs->growable = 1;
524 83f64091 bellard
    *pbs = bs;
525 83f64091 bellard
    return 0;
526 83f64091 bellard
}
527 83f64091 bellard
528 b6ce07aa Kevin Wolf
/*
529 b6ce07aa Kevin Wolf
 * Opens a disk image (raw, qcow2, vmdk, ...)
530 b6ce07aa Kevin Wolf
 */
531 d6e9098e Kevin Wolf
int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
532 d6e9098e Kevin Wolf
              BlockDriver *drv)
533 ea2384d3 bellard
{
534 b6ce07aa Kevin Wolf
    int ret;
535 712e7874 bellard
536 83f64091 bellard
    if (flags & BDRV_O_SNAPSHOT) {
537 ea2384d3 bellard
        BlockDriverState *bs1;
538 ea2384d3 bellard
        int64_t total_size;
539 7c96d46e aliguori
        int is_protocol = 0;
540 91a073a9 Kevin Wolf
        BlockDriver *bdrv_qcow2;
541 91a073a9 Kevin Wolf
        QEMUOptionParameter *options;
542 b6ce07aa Kevin Wolf
        char tmp_filename[PATH_MAX];
543 b6ce07aa Kevin Wolf
        char backing_filename[PATH_MAX];
544 3b46e624 ths
545 ea2384d3 bellard
        /* if snapshot, we create a temporary backing file and open it
546 ea2384d3 bellard
           instead of opening 'filename' directly */
547 33e3963e bellard
548 ea2384d3 bellard
        /* if there is a backing file, use it */
549 ea2384d3 bellard
        bs1 = bdrv_new("");
550 d6e9098e Kevin Wolf
        ret = bdrv_open(bs1, filename, 0, drv);
551 51d7c00c aliguori
        if (ret < 0) {
552 ea2384d3 bellard
            bdrv_delete(bs1);
553 51d7c00c aliguori
            return ret;
554 ea2384d3 bellard
        }
555 3e82990b Jes Sorensen
        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
556 7c96d46e aliguori
557 7c96d46e aliguori
        if (bs1->drv && bs1->drv->protocol_name)
558 7c96d46e aliguori
            is_protocol = 1;
559 7c96d46e aliguori
560 ea2384d3 bellard
        bdrv_delete(bs1);
561 3b46e624 ths
562 ea2384d3 bellard
        get_tmp_filename(tmp_filename, sizeof(tmp_filename));
563 7c96d46e aliguori
564 7c96d46e aliguori
        /* Real path is meaningless for protocols */
565 7c96d46e aliguori
        if (is_protocol)
566 7c96d46e aliguori
            snprintf(backing_filename, sizeof(backing_filename),
567 7c96d46e aliguori
                     "%s", filename);
568 114cdfa9 Kirill A. Shutemov
        else if (!realpath(filename, backing_filename))
569 114cdfa9 Kirill A. Shutemov
            return -errno;
570 7c96d46e aliguori
571 91a073a9 Kevin Wolf
        bdrv_qcow2 = bdrv_find_format("qcow2");
572 91a073a9 Kevin Wolf
        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
573 91a073a9 Kevin Wolf
574 3e82990b Jes Sorensen
        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
575 91a073a9 Kevin Wolf
        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
576 91a073a9 Kevin Wolf
        if (drv) {
577 91a073a9 Kevin Wolf
            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
578 91a073a9 Kevin Wolf
                drv->format_name);
579 91a073a9 Kevin Wolf
        }
580 91a073a9 Kevin Wolf
581 91a073a9 Kevin Wolf
        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
582 d748768c Jan Kiszka
        free_option_parameters(options);
583 51d7c00c aliguori
        if (ret < 0) {
584 51d7c00c aliguori
            return ret;
585 ea2384d3 bellard
        }
586 91a073a9 Kevin Wolf
587 ea2384d3 bellard
        filename = tmp_filename;
588 91a073a9 Kevin Wolf
        drv = bdrv_qcow2;
589 ea2384d3 bellard
        bs->is_temporary = 1;
590 ea2384d3 bellard
    }
591 712e7874 bellard
592 b6ce07aa Kevin Wolf
    /* Find the right image format driver */
593 6db95603 Christoph Hellwig
    if (!drv) {
594 c98ac35d Stefan Weil
        ret = find_image_format(filename, &drv);
595 51d7c00c aliguori
    }
596 6987307c Christoph Hellwig
597 51d7c00c aliguori
    if (!drv) {
598 51d7c00c aliguori
        goto unlink_and_fail;
599 ea2384d3 bellard
    }
600 b6ce07aa Kevin Wolf
601 b6ce07aa Kevin Wolf
    /* Open the image */
602 b6ce07aa Kevin Wolf
    ret = bdrv_open_common(bs, filename, flags, drv);
603 b6ce07aa Kevin Wolf
    if (ret < 0) {
604 6987307c Christoph Hellwig
        goto unlink_and_fail;
605 6987307c Christoph Hellwig
    }
606 6987307c Christoph Hellwig
607 b6ce07aa Kevin Wolf
    /* If there is a backing file, use it */
608 b6ce07aa Kevin Wolf
    if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
609 b6ce07aa Kevin Wolf
        char backing_filename[PATH_MAX];
610 b6ce07aa Kevin Wolf
        int back_flags;
611 b6ce07aa Kevin Wolf
        BlockDriver *back_drv = NULL;
612 b6ce07aa Kevin Wolf
613 b6ce07aa Kevin Wolf
        bs->backing_hd = bdrv_new("");
614 df2dbb4a Stefan Hajnoczi
615 df2dbb4a Stefan Hajnoczi
        if (path_has_protocol(bs->backing_file)) {
616 df2dbb4a Stefan Hajnoczi
            pstrcpy(backing_filename, sizeof(backing_filename),
617 df2dbb4a Stefan Hajnoczi
                    bs->backing_file);
618 df2dbb4a Stefan Hajnoczi
        } else {
619 df2dbb4a Stefan Hajnoczi
            path_combine(backing_filename, sizeof(backing_filename),
620 df2dbb4a Stefan Hajnoczi
                         filename, bs->backing_file);
621 df2dbb4a Stefan Hajnoczi
        }
622 df2dbb4a Stefan Hajnoczi
623 df2dbb4a Stefan Hajnoczi
        if (bs->backing_format[0] != '\0') {
624 b6ce07aa Kevin Wolf
            back_drv = bdrv_find_format(bs->backing_format);
625 df2dbb4a Stefan Hajnoczi
        }
626 b6ce07aa Kevin Wolf
627 b6ce07aa Kevin Wolf
        /* backing files always opened read-only */
628 b6ce07aa Kevin Wolf
        back_flags =
629 b6ce07aa Kevin Wolf
            flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
630 b6ce07aa Kevin Wolf
631 b6ce07aa Kevin Wolf
        ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
632 b6ce07aa Kevin Wolf
        if (ret < 0) {
633 b6ce07aa Kevin Wolf
            bdrv_close(bs);
634 b6ce07aa Kevin Wolf
            return ret;
635 b6ce07aa Kevin Wolf
        }
636 b6ce07aa Kevin Wolf
        if (bs->is_temporary) {
637 b6ce07aa Kevin Wolf
            bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
638 b6ce07aa Kevin Wolf
        } else {
639 b6ce07aa Kevin Wolf
            /* base image inherits from "parent" */
640 b6ce07aa Kevin Wolf
            bs->backing_hd->keep_read_only = bs->keep_read_only;
641 b6ce07aa Kevin Wolf
        }
642 b6ce07aa Kevin Wolf
    }
643 b6ce07aa Kevin Wolf
644 b6ce07aa Kevin Wolf
    if (!bdrv_key_required(bs)) {
645 b6ce07aa Kevin Wolf
        /* call the change callback */
646 b6ce07aa Kevin Wolf
        bs->media_changed = 1;
647 b6ce07aa Kevin Wolf
        if (bs->change_cb)
648 db97ee6a Christoph Hellwig
            bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
649 b6ce07aa Kevin Wolf
    }
650 b6ce07aa Kevin Wolf
651 b6ce07aa Kevin Wolf
    return 0;
652 b6ce07aa Kevin Wolf
653 b6ce07aa Kevin Wolf
unlink_and_fail:
654 b6ce07aa Kevin Wolf
    if (bs->is_temporary) {
655 b6ce07aa Kevin Wolf
        unlink(filename);
656 b6ce07aa Kevin Wolf
    }
657 b6ce07aa Kevin Wolf
    return ret;
658 b6ce07aa Kevin Wolf
}
659 b6ce07aa Kevin Wolf
660 fc01f7e7 bellard
void bdrv_close(BlockDriverState *bs)
661 fc01f7e7 bellard
{
662 19cb3738 bellard
    if (bs->drv) {
663 f9092b10 Markus Armbruster
        if (bs == bs_snapshots) {
664 f9092b10 Markus Armbruster
            bs_snapshots = NULL;
665 f9092b10 Markus Armbruster
        }
666 557df6ac Stefan Hajnoczi
        if (bs->backing_hd) {
667 ea2384d3 bellard
            bdrv_delete(bs->backing_hd);
668 557df6ac Stefan Hajnoczi
            bs->backing_hd = NULL;
669 557df6ac Stefan Hajnoczi
        }
670 ea2384d3 bellard
        bs->drv->bdrv_close(bs);
671 ea2384d3 bellard
        qemu_free(bs->opaque);
672 ea2384d3 bellard
#ifdef _WIN32
673 ea2384d3 bellard
        if (bs->is_temporary) {
674 ea2384d3 bellard
            unlink(bs->filename);
675 ea2384d3 bellard
        }
676 67b915a5 bellard
#endif
677 ea2384d3 bellard
        bs->opaque = NULL;
678 ea2384d3 bellard
        bs->drv = NULL;
679 b338082b bellard
680 66f82cee Kevin Wolf
        if (bs->file != NULL) {
681 66f82cee Kevin Wolf
            bdrv_close(bs->file);
682 66f82cee Kevin Wolf
        }
683 66f82cee Kevin Wolf
684 b338082b bellard
        /* call the change callback */
685 19cb3738 bellard
        bs->media_changed = 1;
686 b338082b bellard
        if (bs->change_cb)
687 db97ee6a Christoph Hellwig
            bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
688 b338082b bellard
    }
689 b338082b bellard
}
690 b338082b bellard
691 2bc93fed MORITA Kazutaka
void bdrv_close_all(void)
692 2bc93fed MORITA Kazutaka
{
693 2bc93fed MORITA Kazutaka
    BlockDriverState *bs;
694 2bc93fed MORITA Kazutaka
695 2bc93fed MORITA Kazutaka
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
696 2bc93fed MORITA Kazutaka
        bdrv_close(bs);
697 2bc93fed MORITA Kazutaka
    }
698 2bc93fed MORITA Kazutaka
}
699 2bc93fed MORITA Kazutaka
700 d22b2f41 Ryan Harper
/* make a BlockDriverState anonymous by removing from bdrv_state list.
701 d22b2f41 Ryan Harper
   Also, NULL terminate the device_name to prevent double remove */
702 d22b2f41 Ryan Harper
void bdrv_make_anon(BlockDriverState *bs)
703 d22b2f41 Ryan Harper
{
704 d22b2f41 Ryan Harper
    if (bs->device_name[0] != '\0') {
705 d22b2f41 Ryan Harper
        QTAILQ_REMOVE(&bdrv_states, bs, list);
706 d22b2f41 Ryan Harper
    }
707 d22b2f41 Ryan Harper
    bs->device_name[0] = '\0';
708 d22b2f41 Ryan Harper
}
709 d22b2f41 Ryan Harper
710 b338082b bellard
void bdrv_delete(BlockDriverState *bs)
711 b338082b bellard
{
712 18846dee Markus Armbruster
    assert(!bs->peer);
713 18846dee Markus Armbruster
714 1b7bdbc1 Stefan Hajnoczi
    /* remove from list, if necessary */
715 d22b2f41 Ryan Harper
    bdrv_make_anon(bs);
716 34c6f050 aurel32
717 b338082b bellard
    bdrv_close(bs);
718 66f82cee Kevin Wolf
    if (bs->file != NULL) {
719 66f82cee Kevin Wolf
        bdrv_delete(bs->file);
720 66f82cee Kevin Wolf
    }
721 66f82cee Kevin Wolf
722 f9092b10 Markus Armbruster
    assert(bs != bs_snapshots);
723 b338082b bellard
    qemu_free(bs);
724 fc01f7e7 bellard
}
725 fc01f7e7 bellard
726 18846dee Markus Armbruster
int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
727 18846dee Markus Armbruster
{
728 18846dee Markus Armbruster
    if (bs->peer) {
729 18846dee Markus Armbruster
        return -EBUSY;
730 18846dee Markus Armbruster
    }
731 18846dee Markus Armbruster
    bs->peer = qdev;
732 18846dee Markus Armbruster
    return 0;
733 18846dee Markus Armbruster
}
734 18846dee Markus Armbruster
735 18846dee Markus Armbruster
void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
736 18846dee Markus Armbruster
{
737 18846dee Markus Armbruster
    assert(bs->peer == qdev);
738 18846dee Markus Armbruster
    bs->peer = NULL;
739 18846dee Markus Armbruster
}
740 18846dee Markus Armbruster
741 18846dee Markus Armbruster
DeviceState *bdrv_get_attached(BlockDriverState *bs)
742 18846dee Markus Armbruster
{
743 18846dee Markus Armbruster
    return bs->peer;
744 18846dee Markus Armbruster
}
745 18846dee Markus Armbruster
746 e97fc193 aliguori
/*
747 e97fc193 aliguori
 * Run consistency checks on an image
748 e97fc193 aliguori
 *
749 e076f338 Kevin Wolf
 * Returns 0 if the check could be completed (it doesn't mean that the image is
750 e076f338 Kevin Wolf
 * free of errors) or -errno when an internal error occured. The results of the
751 e076f338 Kevin Wolf
 * check are stored in res.
752 e97fc193 aliguori
 */
753 e076f338 Kevin Wolf
int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
754 e97fc193 aliguori
{
755 e97fc193 aliguori
    if (bs->drv->bdrv_check == NULL) {
756 e97fc193 aliguori
        return -ENOTSUP;
757 e97fc193 aliguori
    }
758 e97fc193 aliguori
759 e076f338 Kevin Wolf
    memset(res, 0, sizeof(*res));
760 9ac228e0 Kevin Wolf
    return bs->drv->bdrv_check(bs, res);
761 e97fc193 aliguori
}
762 e97fc193 aliguori
763 8a426614 Kevin Wolf
#define COMMIT_BUF_SECTORS 2048
764 8a426614 Kevin Wolf
765 33e3963e bellard
/* commit COW file into the raw image */
766 33e3963e bellard
int bdrv_commit(BlockDriverState *bs)
767 33e3963e bellard
{
768 19cb3738 bellard
    BlockDriver *drv = bs->drv;
769 ee181196 Kevin Wolf
    BlockDriver *backing_drv;
770 8a426614 Kevin Wolf
    int64_t sector, total_sectors;
771 8a426614 Kevin Wolf
    int n, ro, open_flags;
772 4dca4b63 Naphtali Sprei
    int ret = 0, rw_ret = 0;
773 8a426614 Kevin Wolf
    uint8_t *buf;
774 4dca4b63 Naphtali Sprei
    char filename[1024];
775 4dca4b63 Naphtali Sprei
    BlockDriverState *bs_rw, *bs_ro;
776 33e3963e bellard
777 19cb3738 bellard
    if (!drv)
778 19cb3738 bellard
        return -ENOMEDIUM;
779 4dca4b63 Naphtali Sprei
    
780 4dca4b63 Naphtali Sprei
    if (!bs->backing_hd) {
781 4dca4b63 Naphtali Sprei
        return -ENOTSUP;
782 33e3963e bellard
    }
783 33e3963e bellard
784 4dca4b63 Naphtali Sprei
    if (bs->backing_hd->keep_read_only) {
785 4dca4b63 Naphtali Sprei
        return -EACCES;
786 4dca4b63 Naphtali Sprei
    }
787 ee181196 Kevin Wolf
788 ee181196 Kevin Wolf
    backing_drv = bs->backing_hd->drv;
789 4dca4b63 Naphtali Sprei
    ro = bs->backing_hd->read_only;
790 4dca4b63 Naphtali Sprei
    strncpy(filename, bs->backing_hd->filename, sizeof(filename));
791 4dca4b63 Naphtali Sprei
    open_flags =  bs->backing_hd->open_flags;
792 4dca4b63 Naphtali Sprei
793 4dca4b63 Naphtali Sprei
    if (ro) {
794 4dca4b63 Naphtali Sprei
        /* re-open as RW */
795 4dca4b63 Naphtali Sprei
        bdrv_delete(bs->backing_hd);
796 4dca4b63 Naphtali Sprei
        bs->backing_hd = NULL;
797 4dca4b63 Naphtali Sprei
        bs_rw = bdrv_new("");
798 ee181196 Kevin Wolf
        rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
799 ee181196 Kevin Wolf
            backing_drv);
800 4dca4b63 Naphtali Sprei
        if (rw_ret < 0) {
801 4dca4b63 Naphtali Sprei
            bdrv_delete(bs_rw);
802 4dca4b63 Naphtali Sprei
            /* try to re-open read-only */
803 4dca4b63 Naphtali Sprei
            bs_ro = bdrv_new("");
804 ee181196 Kevin Wolf
            ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
805 ee181196 Kevin Wolf
                backing_drv);
806 4dca4b63 Naphtali Sprei
            if (ret < 0) {
807 4dca4b63 Naphtali Sprei
                bdrv_delete(bs_ro);
808 4dca4b63 Naphtali Sprei
                /* drive not functional anymore */
809 4dca4b63 Naphtali Sprei
                bs->drv = NULL;
810 4dca4b63 Naphtali Sprei
                return ret;
811 4dca4b63 Naphtali Sprei
            }
812 4dca4b63 Naphtali Sprei
            bs->backing_hd = bs_ro;
813 4dca4b63 Naphtali Sprei
            return rw_ret;
814 4dca4b63 Naphtali Sprei
        }
815 4dca4b63 Naphtali Sprei
        bs->backing_hd = bs_rw;
816 ea2384d3 bellard
    }
817 33e3963e bellard
818 6ea44308 Jan Kiszka
    total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
819 8a426614 Kevin Wolf
    buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
820 8a426614 Kevin Wolf
821 8a426614 Kevin Wolf
    for (sector = 0; sector < total_sectors; sector += n) {
822 8a426614 Kevin Wolf
        if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
823 8a426614 Kevin Wolf
824 8a426614 Kevin Wolf
            if (bdrv_read(bs, sector, buf, n) != 0) {
825 8a426614 Kevin Wolf
                ret = -EIO;
826 8a426614 Kevin Wolf
                goto ro_cleanup;
827 8a426614 Kevin Wolf
            }
828 8a426614 Kevin Wolf
829 8a426614 Kevin Wolf
            if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
830 8a426614 Kevin Wolf
                ret = -EIO;
831 8a426614 Kevin Wolf
                goto ro_cleanup;
832 8a426614 Kevin Wolf
            }
833 ea2384d3 bellard
        }
834 33e3963e bellard
    }
835 95389c86 bellard
836 1d44952f Christoph Hellwig
    if (drv->bdrv_make_empty) {
837 1d44952f Christoph Hellwig
        ret = drv->bdrv_make_empty(bs);
838 1d44952f Christoph Hellwig
        bdrv_flush(bs);
839 1d44952f Christoph Hellwig
    }
840 95389c86 bellard
841 3f5075ae Christoph Hellwig
    /*
842 3f5075ae Christoph Hellwig
     * Make sure all data we wrote to the backing device is actually
843 3f5075ae Christoph Hellwig
     * stable on disk.
844 3f5075ae Christoph Hellwig
     */
845 3f5075ae Christoph Hellwig
    if (bs->backing_hd)
846 3f5075ae Christoph Hellwig
        bdrv_flush(bs->backing_hd);
847 4dca4b63 Naphtali Sprei
848 4dca4b63 Naphtali Sprei
ro_cleanup:
849 8a426614 Kevin Wolf
    qemu_free(buf);
850 4dca4b63 Naphtali Sprei
851 4dca4b63 Naphtali Sprei
    if (ro) {
852 4dca4b63 Naphtali Sprei
        /* re-open as RO */
853 4dca4b63 Naphtali Sprei
        bdrv_delete(bs->backing_hd);
854 4dca4b63 Naphtali Sprei
        bs->backing_hd = NULL;
855 4dca4b63 Naphtali Sprei
        bs_ro = bdrv_new("");
856 ee181196 Kevin Wolf
        ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
857 ee181196 Kevin Wolf
            backing_drv);
858 4dca4b63 Naphtali Sprei
        if (ret < 0) {
859 4dca4b63 Naphtali Sprei
            bdrv_delete(bs_ro);
860 4dca4b63 Naphtali Sprei
            /* drive not functional anymore */
861 4dca4b63 Naphtali Sprei
            bs->drv = NULL;
862 4dca4b63 Naphtali Sprei
            return ret;
863 4dca4b63 Naphtali Sprei
        }
864 4dca4b63 Naphtali Sprei
        bs->backing_hd = bs_ro;
865 4dca4b63 Naphtali Sprei
        bs->backing_hd->keep_read_only = 0;
866 4dca4b63 Naphtali Sprei
    }
867 4dca4b63 Naphtali Sprei
868 1d44952f Christoph Hellwig
    return ret;
869 33e3963e bellard
}
870 33e3963e bellard
871 6ab4b5ab Markus Armbruster
void bdrv_commit_all(void)
872 6ab4b5ab Markus Armbruster
{
873 6ab4b5ab Markus Armbruster
    BlockDriverState *bs;
874 6ab4b5ab Markus Armbruster
875 6ab4b5ab Markus Armbruster
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
876 6ab4b5ab Markus Armbruster
        bdrv_commit(bs);
877 6ab4b5ab Markus Armbruster
    }
878 6ab4b5ab Markus Armbruster
}
879 6ab4b5ab Markus Armbruster
880 756e6736 Kevin Wolf
/*
881 756e6736 Kevin Wolf
 * Return values:
882 756e6736 Kevin Wolf
 * 0        - success
883 756e6736 Kevin Wolf
 * -EINVAL  - backing format specified, but no file
884 756e6736 Kevin Wolf
 * -ENOSPC  - can't update the backing file because no space is left in the
885 756e6736 Kevin Wolf
 *            image file header
886 756e6736 Kevin Wolf
 * -ENOTSUP - format driver doesn't support changing the backing file
887 756e6736 Kevin Wolf
 */
888 756e6736 Kevin Wolf
int bdrv_change_backing_file(BlockDriverState *bs,
889 756e6736 Kevin Wolf
    const char *backing_file, const char *backing_fmt)
890 756e6736 Kevin Wolf
{
891 756e6736 Kevin Wolf
    BlockDriver *drv = bs->drv;
892 756e6736 Kevin Wolf
893 756e6736 Kevin Wolf
    if (drv->bdrv_change_backing_file != NULL) {
894 756e6736 Kevin Wolf
        return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
895 756e6736 Kevin Wolf
    } else {
896 756e6736 Kevin Wolf
        return -ENOTSUP;
897 756e6736 Kevin Wolf
    }
898 756e6736 Kevin Wolf
}
899 756e6736 Kevin Wolf
900 71d0770c aliguori
static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
901 71d0770c aliguori
                                   size_t size)
902 71d0770c aliguori
{
903 71d0770c aliguori
    int64_t len;
904 71d0770c aliguori
905 71d0770c aliguori
    if (!bdrv_is_inserted(bs))
906 71d0770c aliguori
        return -ENOMEDIUM;
907 71d0770c aliguori
908 71d0770c aliguori
    if (bs->growable)
909 71d0770c aliguori
        return 0;
910 71d0770c aliguori
911 71d0770c aliguori
    len = bdrv_getlength(bs);
912 71d0770c aliguori
913 fbb7b4e0 Kevin Wolf
    if (offset < 0)
914 fbb7b4e0 Kevin Wolf
        return -EIO;
915 fbb7b4e0 Kevin Wolf
916 fbb7b4e0 Kevin Wolf
    if ((offset > len) || (len - offset < size))
917 71d0770c aliguori
        return -EIO;
918 71d0770c aliguori
919 71d0770c aliguori
    return 0;
920 71d0770c aliguori
}
921 71d0770c aliguori
922 71d0770c aliguori
static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
923 71d0770c aliguori
                              int nb_sectors)
924 71d0770c aliguori
{
925 eb5a3165 Jes Sorensen
    return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
926 eb5a3165 Jes Sorensen
                                   nb_sectors * BDRV_SECTOR_SIZE);
927 71d0770c aliguori
}
928 71d0770c aliguori
929 19cb3738 bellard
/* return < 0 if error. See bdrv_write() for the return codes */
930 5fafdf24 ths
int bdrv_read(BlockDriverState *bs, int64_t sector_num,
931 fc01f7e7 bellard
              uint8_t *buf, int nb_sectors)
932 fc01f7e7 bellard
{
933 ea2384d3 bellard
    BlockDriver *drv = bs->drv;
934 ea2384d3 bellard
935 19cb3738 bellard
    if (!drv)
936 19cb3738 bellard
        return -ENOMEDIUM;
937 71d0770c aliguori
    if (bdrv_check_request(bs, sector_num, nb_sectors))
938 71d0770c aliguori
        return -EIO;
939 b338082b bellard
940 eda578e5 aliguori
    return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
941 fc01f7e7 bellard
}
942 fc01f7e7 bellard
943 7cd1e32a lirans@il.ibm.com
static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
944 a55eb92c Jan Kiszka
                             int nb_sectors, int dirty)
945 7cd1e32a lirans@il.ibm.com
{
946 7cd1e32a lirans@il.ibm.com
    int64_t start, end;
947 c6d22830 Jan Kiszka
    unsigned long val, idx, bit;
948 a55eb92c Jan Kiszka
949 6ea44308 Jan Kiszka
    start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
950 c6d22830 Jan Kiszka
    end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
951 a55eb92c Jan Kiszka
952 a55eb92c Jan Kiszka
    for (; start <= end; start++) {
953 c6d22830 Jan Kiszka
        idx = start / (sizeof(unsigned long) * 8);
954 c6d22830 Jan Kiszka
        bit = start % (sizeof(unsigned long) * 8);
955 c6d22830 Jan Kiszka
        val = bs->dirty_bitmap[idx];
956 c6d22830 Jan Kiszka
        if (dirty) {
957 6d59fec1 Marcelo Tosatti
            if (!(val & (1UL << bit))) {
958 aaa0eb75 Liran Schour
                bs->dirty_count++;
959 6d59fec1 Marcelo Tosatti
                val |= 1UL << bit;
960 aaa0eb75 Liran Schour
            }
961 c6d22830 Jan Kiszka
        } else {
962 6d59fec1 Marcelo Tosatti
            if (val & (1UL << bit)) {
963 aaa0eb75 Liran Schour
                bs->dirty_count--;
964 6d59fec1 Marcelo Tosatti
                val &= ~(1UL << bit);
965 aaa0eb75 Liran Schour
            }
966 c6d22830 Jan Kiszka
        }
967 c6d22830 Jan Kiszka
        bs->dirty_bitmap[idx] = val;
968 7cd1e32a lirans@il.ibm.com
    }
969 7cd1e32a lirans@il.ibm.com
}
970 7cd1e32a lirans@il.ibm.com
971 5fafdf24 ths
/* Return < 0 if error. Important errors are:
972 19cb3738 bellard
  -EIO         generic I/O error (may happen for all errors)
973 19cb3738 bellard
  -ENOMEDIUM   No media inserted.
974 19cb3738 bellard
  -EINVAL      Invalid sector number or nb_sectors
975 19cb3738 bellard
  -EACCES      Trying to write a read-only device
976 19cb3738 bellard
*/
977 5fafdf24 ths
int bdrv_write(BlockDriverState *bs, int64_t sector_num,
978 fc01f7e7 bellard
               const uint8_t *buf, int nb_sectors)
979 fc01f7e7 bellard
{
980 83f64091 bellard
    BlockDriver *drv = bs->drv;
981 19cb3738 bellard
    if (!bs->drv)
982 19cb3738 bellard
        return -ENOMEDIUM;
983 0849bf08 bellard
    if (bs->read_only)
984 19cb3738 bellard
        return -EACCES;
985 71d0770c aliguori
    if (bdrv_check_request(bs, sector_num, nb_sectors))
986 71d0770c aliguori
        return -EIO;
987 a55eb92c Jan Kiszka
988 c6d22830 Jan Kiszka
    if (bs->dirty_bitmap) {
989 7cd1e32a lirans@il.ibm.com
        set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
990 7cd1e32a lirans@il.ibm.com
    }
991 a55eb92c Jan Kiszka
992 294cc35f Kevin Wolf
    if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
993 294cc35f Kevin Wolf
        bs->wr_highest_sector = sector_num + nb_sectors - 1;
994 294cc35f Kevin Wolf
    }
995 294cc35f Kevin Wolf
996 42fb2807 aliguori
    return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
997 83f64091 bellard
}
998 83f64091 bellard
999 eda578e5 aliguori
int bdrv_pread(BlockDriverState *bs, int64_t offset,
1000 eda578e5 aliguori
               void *buf, int count1)
1001 83f64091 bellard
{
1002 6ea44308 Jan Kiszka
    uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1003 83f64091 bellard
    int len, nb_sectors, count;
1004 83f64091 bellard
    int64_t sector_num;
1005 9a8c4cce Kevin Wolf
    int ret;
1006 83f64091 bellard
1007 83f64091 bellard
    count = count1;
1008 83f64091 bellard
    /* first read to align to sector start */
1009 6ea44308 Jan Kiszka
    len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1010 83f64091 bellard
    if (len > count)
1011 83f64091 bellard
        len = count;
1012 6ea44308 Jan Kiszka
    sector_num = offset >> BDRV_SECTOR_BITS;
1013 83f64091 bellard
    if (len > 0) {
1014 9a8c4cce Kevin Wolf
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1015 9a8c4cce Kevin Wolf
            return ret;
1016 6ea44308 Jan Kiszka
        memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
1017 83f64091 bellard
        count -= len;
1018 83f64091 bellard
        if (count == 0)
1019 83f64091 bellard
            return count1;
1020 83f64091 bellard
        sector_num++;
1021 83f64091 bellard
        buf += len;
1022 83f64091 bellard
    }
1023 83f64091 bellard
1024 83f64091 bellard
    /* read the sectors "in place" */
1025 6ea44308 Jan Kiszka
    nb_sectors = count >> BDRV_SECTOR_BITS;
1026 83f64091 bellard
    if (nb_sectors > 0) {
1027 9a8c4cce Kevin Wolf
        if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1028 9a8c4cce Kevin Wolf
            return ret;
1029 83f64091 bellard
        sector_num += nb_sectors;
1030 6ea44308 Jan Kiszka
        len = nb_sectors << BDRV_SECTOR_BITS;
1031 83f64091 bellard
        buf += len;
1032 83f64091 bellard
        count -= len;
1033 83f64091 bellard
    }
1034 83f64091 bellard
1035 83f64091 bellard
    /* add data from the last sector */
1036 83f64091 bellard
    if (count > 0) {
1037 9a8c4cce Kevin Wolf
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1038 9a8c4cce Kevin Wolf
            return ret;
1039 83f64091 bellard
        memcpy(buf, tmp_buf, count);
1040 83f64091 bellard
    }
1041 83f64091 bellard
    return count1;
1042 83f64091 bellard
}
1043 83f64091 bellard
1044 eda578e5 aliguori
int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1045 eda578e5 aliguori
                const void *buf, int count1)
1046 83f64091 bellard
{
1047 6ea44308 Jan Kiszka
    uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1048 83f64091 bellard
    int len, nb_sectors, count;
1049 83f64091 bellard
    int64_t sector_num;
1050 9a8c4cce Kevin Wolf
    int ret;
1051 83f64091 bellard
1052 83f64091 bellard
    count = count1;
1053 83f64091 bellard
    /* first write to align to sector start */
1054 6ea44308 Jan Kiszka
    len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1055 83f64091 bellard
    if (len > count)
1056 83f64091 bellard
        len = count;
1057 6ea44308 Jan Kiszka
    sector_num = offset >> BDRV_SECTOR_BITS;
1058 83f64091 bellard
    if (len > 0) {
1059 9a8c4cce Kevin Wolf
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1060 9a8c4cce Kevin Wolf
            return ret;
1061 6ea44308 Jan Kiszka
        memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1062 9a8c4cce Kevin Wolf
        if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1063 9a8c4cce Kevin Wolf
            return ret;
1064 83f64091 bellard
        count -= len;
1065 83f64091 bellard
        if (count == 0)
1066 83f64091 bellard
            return count1;
1067 83f64091 bellard
        sector_num++;
1068 83f64091 bellard
        buf += len;
1069 83f64091 bellard
    }
1070 83f64091 bellard
1071 83f64091 bellard
    /* write the sectors "in place" */
1072 6ea44308 Jan Kiszka
    nb_sectors = count >> BDRV_SECTOR_BITS;
1073 83f64091 bellard
    if (nb_sectors > 0) {
1074 9a8c4cce Kevin Wolf
        if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1075 9a8c4cce Kevin Wolf
            return ret;
1076 83f64091 bellard
        sector_num += nb_sectors;
1077 6ea44308 Jan Kiszka
        len = nb_sectors << BDRV_SECTOR_BITS;
1078 83f64091 bellard
        buf += len;
1079 83f64091 bellard
        count -= len;
1080 83f64091 bellard
    }
1081 83f64091 bellard
1082 83f64091 bellard
    /* add data from the last sector */
1083 83f64091 bellard
    if (count > 0) {
1084 9a8c4cce Kevin Wolf
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1085 9a8c4cce Kevin Wolf
            return ret;
1086 83f64091 bellard
        memcpy(tmp_buf, buf, count);
1087 9a8c4cce Kevin Wolf
        if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1088 9a8c4cce Kevin Wolf
            return ret;
1089 83f64091 bellard
    }
1090 83f64091 bellard
    return count1;
1091 83f64091 bellard
}
1092 83f64091 bellard
1093 f08145fe Kevin Wolf
/*
1094 f08145fe Kevin Wolf
 * Writes to the file and ensures that no writes are reordered across this
1095 f08145fe Kevin Wolf
 * request (acts as a barrier)
1096 f08145fe Kevin Wolf
 *
1097 f08145fe Kevin Wolf
 * Returns 0 on success, -errno in error cases.
1098 f08145fe Kevin Wolf
 */
1099 f08145fe Kevin Wolf
int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1100 f08145fe Kevin Wolf
    const void *buf, int count)
1101 f08145fe Kevin Wolf
{
1102 f08145fe Kevin Wolf
    int ret;
1103 f08145fe Kevin Wolf
1104 f08145fe Kevin Wolf
    ret = bdrv_pwrite(bs, offset, buf, count);
1105 f08145fe Kevin Wolf
    if (ret < 0) {
1106 f08145fe Kevin Wolf
        return ret;
1107 f08145fe Kevin Wolf
    }
1108 f08145fe Kevin Wolf
1109 f08145fe Kevin Wolf
    /* No flush needed for cache=writethrough, it uses O_DSYNC */
1110 f08145fe Kevin Wolf
    if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1111 f08145fe Kevin Wolf
        bdrv_flush(bs);
1112 f08145fe Kevin Wolf
    }
1113 f08145fe Kevin Wolf
1114 f08145fe Kevin Wolf
    return 0;
1115 f08145fe Kevin Wolf
}
1116 f08145fe Kevin Wolf
1117 f08145fe Kevin Wolf
/*
1118 f08145fe Kevin Wolf
 * Writes to the file and ensures that no writes are reordered across this
1119 f08145fe Kevin Wolf
 * request (acts as a barrier)
1120 f08145fe Kevin Wolf
 *
1121 f08145fe Kevin Wolf
 * Returns 0 on success, -errno in error cases.
1122 f08145fe Kevin Wolf
 */
1123 f08145fe Kevin Wolf
int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1124 f08145fe Kevin Wolf
    const uint8_t *buf, int nb_sectors)
1125 f08145fe Kevin Wolf
{
1126 f08145fe Kevin Wolf
    return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1127 f08145fe Kevin Wolf
        buf, BDRV_SECTOR_SIZE * nb_sectors);
1128 f08145fe Kevin Wolf
}
1129 f08145fe Kevin Wolf
1130 83f64091 bellard
/**
1131 83f64091 bellard
 * Truncate file to 'offset' bytes (needed only for file protocols)
1132 83f64091 bellard
 */
1133 83f64091 bellard
int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1134 83f64091 bellard
{
1135 83f64091 bellard
    BlockDriver *drv = bs->drv;
1136 51762288 Stefan Hajnoczi
    int ret;
1137 83f64091 bellard
    if (!drv)
1138 19cb3738 bellard
        return -ENOMEDIUM;
1139 83f64091 bellard
    if (!drv->bdrv_truncate)
1140 83f64091 bellard
        return -ENOTSUP;
1141 59f2689d Naphtali Sprei
    if (bs->read_only)
1142 59f2689d Naphtali Sprei
        return -EACCES;
1143 8591675f Marcelo Tosatti
    if (bdrv_in_use(bs))
1144 8591675f Marcelo Tosatti
        return -EBUSY;
1145 51762288 Stefan Hajnoczi
    ret = drv->bdrv_truncate(bs, offset);
1146 51762288 Stefan Hajnoczi
    if (ret == 0) {
1147 51762288 Stefan Hajnoczi
        ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1148 db97ee6a Christoph Hellwig
        if (bs->change_cb) {
1149 db97ee6a Christoph Hellwig
            bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1150 db97ee6a Christoph Hellwig
        }
1151 51762288 Stefan Hajnoczi
    }
1152 51762288 Stefan Hajnoczi
    return ret;
1153 83f64091 bellard
}
1154 83f64091 bellard
1155 83f64091 bellard
/**
1156 83f64091 bellard
 * Length of a file in bytes. Return < 0 if error or unknown.
1157 83f64091 bellard
 */
1158 83f64091 bellard
int64_t bdrv_getlength(BlockDriverState *bs)
1159 83f64091 bellard
{
1160 83f64091 bellard
    BlockDriver *drv = bs->drv;
1161 83f64091 bellard
    if (!drv)
1162 19cb3738 bellard
        return -ENOMEDIUM;
1163 51762288 Stefan Hajnoczi
1164 46a4e4e6 Stefan Hajnoczi
    if (bs->growable || bs->removable) {
1165 46a4e4e6 Stefan Hajnoczi
        if (drv->bdrv_getlength) {
1166 46a4e4e6 Stefan Hajnoczi
            return drv->bdrv_getlength(bs);
1167 46a4e4e6 Stefan Hajnoczi
        }
1168 83f64091 bellard
    }
1169 46a4e4e6 Stefan Hajnoczi
    return bs->total_sectors * BDRV_SECTOR_SIZE;
1170 fc01f7e7 bellard
}
1171 fc01f7e7 bellard
1172 19cb3738 bellard
/* return 0 as number of sectors if no device present or error */
1173 96b8f136 ths
void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1174 fc01f7e7 bellard
{
1175 19cb3738 bellard
    int64_t length;
1176 19cb3738 bellard
    length = bdrv_getlength(bs);
1177 19cb3738 bellard
    if (length < 0)
1178 19cb3738 bellard
        length = 0;
1179 19cb3738 bellard
    else
1180 6ea44308 Jan Kiszka
        length = length >> BDRV_SECTOR_BITS;
1181 19cb3738 bellard
    *nb_sectors_ptr = length;
1182 fc01f7e7 bellard
}
1183 cf98951b bellard
1184 f3d54fc4 aliguori
struct partition {
1185 f3d54fc4 aliguori
        uint8_t boot_ind;           /* 0x80 - active */
1186 f3d54fc4 aliguori
        uint8_t head;               /* starting head */
1187 f3d54fc4 aliguori
        uint8_t sector;             /* starting sector */
1188 f3d54fc4 aliguori
        uint8_t cyl;                /* starting cylinder */
1189 f3d54fc4 aliguori
        uint8_t sys_ind;            /* What partition type */
1190 f3d54fc4 aliguori
        uint8_t end_head;           /* end head */
1191 f3d54fc4 aliguori
        uint8_t end_sector;         /* end sector */
1192 f3d54fc4 aliguori
        uint8_t end_cyl;            /* end cylinder */
1193 f3d54fc4 aliguori
        uint32_t start_sect;        /* starting sector counting from 0 */
1194 f3d54fc4 aliguori
        uint32_t nr_sects;          /* nr of sectors in partition */
1195 f3d54fc4 aliguori
} __attribute__((packed));
1196 f3d54fc4 aliguori
1197 f3d54fc4 aliguori
/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1198 f3d54fc4 aliguori
static int guess_disk_lchs(BlockDriverState *bs,
1199 f3d54fc4 aliguori
                           int *pcylinders, int *pheads, int *psectors)
1200 f3d54fc4 aliguori
{
1201 eb5a3165 Jes Sorensen
    uint8_t buf[BDRV_SECTOR_SIZE];
1202 f3d54fc4 aliguori
    int ret, i, heads, sectors, cylinders;
1203 f3d54fc4 aliguori
    struct partition *p;
1204 f3d54fc4 aliguori
    uint32_t nr_sects;
1205 a38131b6 blueswir1
    uint64_t nb_sectors;
1206 f3d54fc4 aliguori
1207 f3d54fc4 aliguori
    bdrv_get_geometry(bs, &nb_sectors);
1208 f3d54fc4 aliguori
1209 f3d54fc4 aliguori
    ret = bdrv_read(bs, 0, buf, 1);
1210 f3d54fc4 aliguori
    if (ret < 0)
1211 f3d54fc4 aliguori
        return -1;
1212 f3d54fc4 aliguori
    /* test msdos magic */
1213 f3d54fc4 aliguori
    if (buf[510] != 0x55 || buf[511] != 0xaa)
1214 f3d54fc4 aliguori
        return -1;
1215 f3d54fc4 aliguori
    for(i = 0; i < 4; i++) {
1216 f3d54fc4 aliguori
        p = ((struct partition *)(buf + 0x1be)) + i;
1217 f3d54fc4 aliguori
        nr_sects = le32_to_cpu(p->nr_sects);
1218 f3d54fc4 aliguori
        if (nr_sects && p->end_head) {
1219 f3d54fc4 aliguori
            /* We make the assumption that the partition terminates on
1220 f3d54fc4 aliguori
               a cylinder boundary */
1221 f3d54fc4 aliguori
            heads = p->end_head + 1;
1222 f3d54fc4 aliguori
            sectors = p->end_sector & 63;
1223 f3d54fc4 aliguori
            if (sectors == 0)
1224 f3d54fc4 aliguori
                continue;
1225 f3d54fc4 aliguori
            cylinders = nb_sectors / (heads * sectors);
1226 f3d54fc4 aliguori
            if (cylinders < 1 || cylinders > 16383)
1227 f3d54fc4 aliguori
                continue;
1228 f3d54fc4 aliguori
            *pheads = heads;
1229 f3d54fc4 aliguori
            *psectors = sectors;
1230 f3d54fc4 aliguori
            *pcylinders = cylinders;
1231 f3d54fc4 aliguori
#if 0
1232 f3d54fc4 aliguori
            printf("guessed geometry: LCHS=%d %d %d\n",
1233 f3d54fc4 aliguori
                   cylinders, heads, sectors);
1234 f3d54fc4 aliguori
#endif
1235 f3d54fc4 aliguori
            return 0;
1236 f3d54fc4 aliguori
        }
1237 f3d54fc4 aliguori
    }
1238 f3d54fc4 aliguori
    return -1;
1239 f3d54fc4 aliguori
}
1240 f3d54fc4 aliguori
1241 f3d54fc4 aliguori
void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1242 f3d54fc4 aliguori
{
1243 f3d54fc4 aliguori
    int translation, lba_detected = 0;
1244 f3d54fc4 aliguori
    int cylinders, heads, secs;
1245 a38131b6 blueswir1
    uint64_t nb_sectors;
1246 f3d54fc4 aliguori
1247 f3d54fc4 aliguori
    /* if a geometry hint is available, use it */
1248 f3d54fc4 aliguori
    bdrv_get_geometry(bs, &nb_sectors);
1249 f3d54fc4 aliguori
    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1250 f3d54fc4 aliguori
    translation = bdrv_get_translation_hint(bs);
1251 f3d54fc4 aliguori
    if (cylinders != 0) {
1252 f3d54fc4 aliguori
        *pcyls = cylinders;
1253 f3d54fc4 aliguori
        *pheads = heads;
1254 f3d54fc4 aliguori
        *psecs = secs;
1255 f3d54fc4 aliguori
    } else {
1256 f3d54fc4 aliguori
        if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1257 f3d54fc4 aliguori
            if (heads > 16) {
1258 f3d54fc4 aliguori
                /* if heads > 16, it means that a BIOS LBA
1259 f3d54fc4 aliguori
                   translation was active, so the default
1260 f3d54fc4 aliguori
                   hardware geometry is OK */
1261 f3d54fc4 aliguori
                lba_detected = 1;
1262 f3d54fc4 aliguori
                goto default_geometry;
1263 f3d54fc4 aliguori
            } else {
1264 f3d54fc4 aliguori
                *pcyls = cylinders;
1265 f3d54fc4 aliguori
                *pheads = heads;
1266 f3d54fc4 aliguori
                *psecs = secs;
1267 f3d54fc4 aliguori
                /* disable any translation to be in sync with
1268 f3d54fc4 aliguori
                   the logical geometry */
1269 f3d54fc4 aliguori
                if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1270 f3d54fc4 aliguori
                    bdrv_set_translation_hint(bs,
1271 f3d54fc4 aliguori
                                              BIOS_ATA_TRANSLATION_NONE);
1272 f3d54fc4 aliguori
                }
1273 f3d54fc4 aliguori
            }
1274 f3d54fc4 aliguori
        } else {
1275 f3d54fc4 aliguori
        default_geometry:
1276 f3d54fc4 aliguori
            /* if no geometry, use a standard physical disk geometry */
1277 f3d54fc4 aliguori
            cylinders = nb_sectors / (16 * 63);
1278 f3d54fc4 aliguori
1279 f3d54fc4 aliguori
            if (cylinders > 16383)
1280 f3d54fc4 aliguori
                cylinders = 16383;
1281 f3d54fc4 aliguori
            else if (cylinders < 2)
1282 f3d54fc4 aliguori
                cylinders = 2;
1283 f3d54fc4 aliguori
            *pcyls = cylinders;
1284 f3d54fc4 aliguori
            *pheads = 16;
1285 f3d54fc4 aliguori
            *psecs = 63;
1286 f3d54fc4 aliguori
            if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1287 f3d54fc4 aliguori
                if ((*pcyls * *pheads) <= 131072) {
1288 f3d54fc4 aliguori
                    bdrv_set_translation_hint(bs,
1289 f3d54fc4 aliguori
                                              BIOS_ATA_TRANSLATION_LARGE);
1290 f3d54fc4 aliguori
                } else {
1291 f3d54fc4 aliguori
                    bdrv_set_translation_hint(bs,
1292 f3d54fc4 aliguori
                                              BIOS_ATA_TRANSLATION_LBA);
1293 f3d54fc4 aliguori
                }
1294 f3d54fc4 aliguori
            }
1295 f3d54fc4 aliguori
        }
1296 f3d54fc4 aliguori
        bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1297 f3d54fc4 aliguori
    }
1298 f3d54fc4 aliguori
}
1299 f3d54fc4 aliguori
1300 5fafdf24 ths
void bdrv_set_geometry_hint(BlockDriverState *bs,
1301 b338082b bellard
                            int cyls, int heads, int secs)
1302 b338082b bellard
{
1303 b338082b bellard
    bs->cyls = cyls;
1304 b338082b bellard
    bs->heads = heads;
1305 b338082b bellard
    bs->secs = secs;
1306 b338082b bellard
}
1307 b338082b bellard
1308 b338082b bellard
void bdrv_set_type_hint(BlockDriverState *bs, int type)
1309 b338082b bellard
{
1310 b338082b bellard
    bs->type = type;
1311 b338082b bellard
    bs->removable = ((type == BDRV_TYPE_CDROM ||
1312 b338082b bellard
                      type == BDRV_TYPE_FLOPPY));
1313 b338082b bellard
}
1314 b338082b bellard
1315 46d4767d bellard
void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1316 46d4767d bellard
{
1317 46d4767d bellard
    bs->translation = translation;
1318 46d4767d bellard
}
1319 46d4767d bellard
1320 5fafdf24 ths
void bdrv_get_geometry_hint(BlockDriverState *bs,
1321 b338082b bellard
                            int *pcyls, int *pheads, int *psecs)
1322 b338082b bellard
{
1323 b338082b bellard
    *pcyls = bs->cyls;
1324 b338082b bellard
    *pheads = bs->heads;
1325 b338082b bellard
    *psecs = bs->secs;
1326 b338082b bellard
}
1327 b338082b bellard
1328 5bbdbb46 Blue Swirl
/* Recognize floppy formats */
1329 5bbdbb46 Blue Swirl
typedef struct FDFormat {
1330 5bbdbb46 Blue Swirl
    FDriveType drive;
1331 5bbdbb46 Blue Swirl
    uint8_t last_sect;
1332 5bbdbb46 Blue Swirl
    uint8_t max_track;
1333 5bbdbb46 Blue Swirl
    uint8_t max_head;
1334 5bbdbb46 Blue Swirl
} FDFormat;
1335 5bbdbb46 Blue Swirl
1336 5bbdbb46 Blue Swirl
static const FDFormat fd_formats[] = {
1337 5bbdbb46 Blue Swirl
    /* First entry is default format */
1338 5bbdbb46 Blue Swirl
    /* 1.44 MB 3"1/2 floppy disks */
1339 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 18, 80, 1, },
1340 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 20, 80, 1, },
1341 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 21, 80, 1, },
1342 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 21, 82, 1, },
1343 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 21, 83, 1, },
1344 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 22, 80, 1, },
1345 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 23, 80, 1, },
1346 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 24, 80, 1, },
1347 5bbdbb46 Blue Swirl
    /* 2.88 MB 3"1/2 floppy disks */
1348 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_288, 36, 80, 1, },
1349 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_288, 39, 80, 1, },
1350 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_288, 40, 80, 1, },
1351 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_288, 44, 80, 1, },
1352 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_288, 48, 80, 1, },
1353 5bbdbb46 Blue Swirl
    /* 720 kB 3"1/2 floppy disks */
1354 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144,  9, 80, 1, },
1355 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 10, 80, 1, },
1356 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 10, 82, 1, },
1357 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 10, 83, 1, },
1358 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 13, 80, 1, },
1359 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144, 14, 80, 1, },
1360 5bbdbb46 Blue Swirl
    /* 1.2 MB 5"1/4 floppy disks */
1361 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 15, 80, 1, },
1362 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 18, 80, 1, },
1363 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 18, 82, 1, },
1364 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 18, 83, 1, },
1365 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 20, 80, 1, },
1366 5bbdbb46 Blue Swirl
    /* 720 kB 5"1/4 floppy disks */
1367 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120,  9, 80, 1, },
1368 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 11, 80, 1, },
1369 5bbdbb46 Blue Swirl
    /* 360 kB 5"1/4 floppy disks */
1370 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120,  9, 40, 1, },
1371 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120,  9, 40, 0, },
1372 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 10, 41, 1, },
1373 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120, 10, 42, 1, },
1374 5bbdbb46 Blue Swirl
    /* 320 kB 5"1/4 floppy disks */
1375 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120,  8, 40, 1, },
1376 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_120,  8, 40, 0, },
1377 5bbdbb46 Blue Swirl
    /* 360 kB must match 5"1/4 better than 3"1/2... */
1378 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_144,  9, 80, 0, },
1379 5bbdbb46 Blue Swirl
    /* end */
1380 5bbdbb46 Blue Swirl
    { FDRIVE_DRV_NONE, -1, -1, 0, },
1381 5bbdbb46 Blue Swirl
};
1382 5bbdbb46 Blue Swirl
1383 5bbdbb46 Blue Swirl
void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1384 5bbdbb46 Blue Swirl
                                   int *max_track, int *last_sect,
1385 5bbdbb46 Blue Swirl
                                   FDriveType drive_in, FDriveType *drive)
1386 5bbdbb46 Blue Swirl
{
1387 5bbdbb46 Blue Swirl
    const FDFormat *parse;
1388 5bbdbb46 Blue Swirl
    uint64_t nb_sectors, size;
1389 5bbdbb46 Blue Swirl
    int i, first_match, match;
1390 5bbdbb46 Blue Swirl
1391 5bbdbb46 Blue Swirl
    bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1392 5bbdbb46 Blue Swirl
    if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1393 5bbdbb46 Blue Swirl
        /* User defined disk */
1394 5bbdbb46 Blue Swirl
    } else {
1395 5bbdbb46 Blue Swirl
        bdrv_get_geometry(bs, &nb_sectors);
1396 5bbdbb46 Blue Swirl
        match = -1;
1397 5bbdbb46 Blue Swirl
        first_match = -1;
1398 5bbdbb46 Blue Swirl
        for (i = 0; ; i++) {
1399 5bbdbb46 Blue Swirl
            parse = &fd_formats[i];
1400 5bbdbb46 Blue Swirl
            if (parse->drive == FDRIVE_DRV_NONE) {
1401 5bbdbb46 Blue Swirl
                break;
1402 5bbdbb46 Blue Swirl
            }
1403 5bbdbb46 Blue Swirl
            if (drive_in == parse->drive ||
1404 5bbdbb46 Blue Swirl
                drive_in == FDRIVE_DRV_NONE) {
1405 5bbdbb46 Blue Swirl
                size = (parse->max_head + 1) * parse->max_track *
1406 5bbdbb46 Blue Swirl
                    parse->last_sect;
1407 5bbdbb46 Blue Swirl
                if (nb_sectors == size) {
1408 5bbdbb46 Blue Swirl
                    match = i;
1409 5bbdbb46 Blue Swirl
                    break;
1410 5bbdbb46 Blue Swirl
                }
1411 5bbdbb46 Blue Swirl
                if (first_match == -1) {
1412 5bbdbb46 Blue Swirl
                    first_match = i;
1413 5bbdbb46 Blue Swirl
                }
1414 5bbdbb46 Blue Swirl
            }
1415 5bbdbb46 Blue Swirl
        }
1416 5bbdbb46 Blue Swirl
        if (match == -1) {
1417 5bbdbb46 Blue Swirl
            if (first_match == -1) {
1418 5bbdbb46 Blue Swirl
                match = 1;
1419 5bbdbb46 Blue Swirl
            } else {
1420 5bbdbb46 Blue Swirl
                match = first_match;
1421 5bbdbb46 Blue Swirl
            }
1422 5bbdbb46 Blue Swirl
            parse = &fd_formats[match];
1423 5bbdbb46 Blue Swirl
        }
1424 5bbdbb46 Blue Swirl
        *nb_heads = parse->max_head + 1;
1425 5bbdbb46 Blue Swirl
        *max_track = parse->max_track;
1426 5bbdbb46 Blue Swirl
        *last_sect = parse->last_sect;
1427 5bbdbb46 Blue Swirl
        *drive = parse->drive;
1428 5bbdbb46 Blue Swirl
    }
1429 5bbdbb46 Blue Swirl
}
1430 5bbdbb46 Blue Swirl
1431 b338082b bellard
int bdrv_get_type_hint(BlockDriverState *bs)
1432 b338082b bellard
{
1433 b338082b bellard
    return bs->type;
1434 b338082b bellard
}
1435 b338082b bellard
1436 46d4767d bellard
int bdrv_get_translation_hint(BlockDriverState *bs)
1437 46d4767d bellard
{
1438 46d4767d bellard
    return bs->translation;
1439 46d4767d bellard
}
1440 46d4767d bellard
1441 abd7f68d Markus Armbruster
void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1442 abd7f68d Markus Armbruster
                       BlockErrorAction on_write_error)
1443 abd7f68d Markus Armbruster
{
1444 abd7f68d Markus Armbruster
    bs->on_read_error = on_read_error;
1445 abd7f68d Markus Armbruster
    bs->on_write_error = on_write_error;
1446 abd7f68d Markus Armbruster
}
1447 abd7f68d Markus Armbruster
1448 abd7f68d Markus Armbruster
BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1449 abd7f68d Markus Armbruster
{
1450 abd7f68d Markus Armbruster
    return is_read ? bs->on_read_error : bs->on_write_error;
1451 abd7f68d Markus Armbruster
}
1452 abd7f68d Markus Armbruster
1453 7d0d6950 Markus Armbruster
void bdrv_set_removable(BlockDriverState *bs, int removable)
1454 7d0d6950 Markus Armbruster
{
1455 7d0d6950 Markus Armbruster
    bs->removable = removable;
1456 7d0d6950 Markus Armbruster
    if (removable && bs == bs_snapshots) {
1457 7d0d6950 Markus Armbruster
        bs_snapshots = NULL;
1458 7d0d6950 Markus Armbruster
    }
1459 7d0d6950 Markus Armbruster
}
1460 7d0d6950 Markus Armbruster
1461 b338082b bellard
int bdrv_is_removable(BlockDriverState *bs)
1462 b338082b bellard
{
1463 b338082b bellard
    return bs->removable;
1464 b338082b bellard
}
1465 b338082b bellard
1466 b338082b bellard
int bdrv_is_read_only(BlockDriverState *bs)
1467 b338082b bellard
{
1468 b338082b bellard
    return bs->read_only;
1469 b338082b bellard
}
1470 b338082b bellard
1471 985a03b0 ths
int bdrv_is_sg(BlockDriverState *bs)
1472 985a03b0 ths
{
1473 985a03b0 ths
    return bs->sg;
1474 985a03b0 ths
}
1475 985a03b0 ths
1476 e900a7b7 Christoph Hellwig
int bdrv_enable_write_cache(BlockDriverState *bs)
1477 e900a7b7 Christoph Hellwig
{
1478 e900a7b7 Christoph Hellwig
    return bs->enable_write_cache;
1479 e900a7b7 Christoph Hellwig
}
1480 e900a7b7 Christoph Hellwig
1481 19cb3738 bellard
/* XXX: no longer used */
1482 5fafdf24 ths
void bdrv_set_change_cb(BlockDriverState *bs,
1483 db97ee6a Christoph Hellwig
                        void (*change_cb)(void *opaque, int reason),
1484 db97ee6a Christoph Hellwig
                        void *opaque)
1485 b338082b bellard
{
1486 b338082b bellard
    bs->change_cb = change_cb;
1487 b338082b bellard
    bs->change_opaque = opaque;
1488 b338082b bellard
}
1489 b338082b bellard
1490 ea2384d3 bellard
int bdrv_is_encrypted(BlockDriverState *bs)
1491 ea2384d3 bellard
{
1492 ea2384d3 bellard
    if (bs->backing_hd && bs->backing_hd->encrypted)
1493 ea2384d3 bellard
        return 1;
1494 ea2384d3 bellard
    return bs->encrypted;
1495 ea2384d3 bellard
}
1496 ea2384d3 bellard
1497 c0f4ce77 aliguori
int bdrv_key_required(BlockDriverState *bs)
1498 c0f4ce77 aliguori
{
1499 c0f4ce77 aliguori
    BlockDriverState *backing_hd = bs->backing_hd;
1500 c0f4ce77 aliguori
1501 c0f4ce77 aliguori
    if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1502 c0f4ce77 aliguori
        return 1;
1503 c0f4ce77 aliguori
    return (bs->encrypted && !bs->valid_key);
1504 c0f4ce77 aliguori
}
1505 c0f4ce77 aliguori
1506 ea2384d3 bellard
int bdrv_set_key(BlockDriverState *bs, const char *key)
1507 ea2384d3 bellard
{
1508 ea2384d3 bellard
    int ret;
1509 ea2384d3 bellard
    if (bs->backing_hd && bs->backing_hd->encrypted) {
1510 ea2384d3 bellard
        ret = bdrv_set_key(bs->backing_hd, key);
1511 ea2384d3 bellard
        if (ret < 0)
1512 ea2384d3 bellard
            return ret;
1513 ea2384d3 bellard
        if (!bs->encrypted)
1514 ea2384d3 bellard
            return 0;
1515 ea2384d3 bellard
    }
1516 fd04a2ae Shahar Havivi
    if (!bs->encrypted) {
1517 fd04a2ae Shahar Havivi
        return -EINVAL;
1518 fd04a2ae Shahar Havivi
    } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1519 fd04a2ae Shahar Havivi
        return -ENOMEDIUM;
1520 fd04a2ae Shahar Havivi
    }
1521 c0f4ce77 aliguori
    ret = bs->drv->bdrv_set_key(bs, key);
1522 bb5fc20f aliguori
    if (ret < 0) {
1523 bb5fc20f aliguori
        bs->valid_key = 0;
1524 bb5fc20f aliguori
    } else if (!bs->valid_key) {
1525 bb5fc20f aliguori
        bs->valid_key = 1;
1526 bb5fc20f aliguori
        /* call the change callback now, we skipped it on open */
1527 bb5fc20f aliguori
        bs->media_changed = 1;
1528 bb5fc20f aliguori
        if (bs->change_cb)
1529 db97ee6a Christoph Hellwig
            bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
1530 bb5fc20f aliguori
    }
1531 c0f4ce77 aliguori
    return ret;
1532 ea2384d3 bellard
}
1533 ea2384d3 bellard
1534 ea2384d3 bellard
void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1535 ea2384d3 bellard
{
1536 19cb3738 bellard
    if (!bs->drv) {
1537 ea2384d3 bellard
        buf[0] = '\0';
1538 ea2384d3 bellard
    } else {
1539 ea2384d3 bellard
        pstrcpy(buf, buf_size, bs->drv->format_name);
1540 ea2384d3 bellard
    }
1541 ea2384d3 bellard
}
1542 ea2384d3 bellard
1543 5fafdf24 ths
void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1544 ea2384d3 bellard
                         void *opaque)
1545 ea2384d3 bellard
{
1546 ea2384d3 bellard
    BlockDriver *drv;
1547 ea2384d3 bellard
1548 8a22f02a Stefan Hajnoczi
    QLIST_FOREACH(drv, &bdrv_drivers, list) {
1549 ea2384d3 bellard
        it(opaque, drv->format_name);
1550 ea2384d3 bellard
    }
1551 ea2384d3 bellard
}
1552 ea2384d3 bellard
1553 b338082b bellard
BlockDriverState *bdrv_find(const char *name)
1554 b338082b bellard
{
1555 b338082b bellard
    BlockDriverState *bs;
1556 b338082b bellard
1557 1b7bdbc1 Stefan Hajnoczi
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1558 1b7bdbc1 Stefan Hajnoczi
        if (!strcmp(name, bs->device_name)) {
1559 b338082b bellard
            return bs;
1560 1b7bdbc1 Stefan Hajnoczi
        }
1561 b338082b bellard
    }
1562 b338082b bellard
    return NULL;
1563 b338082b bellard
}
1564 b338082b bellard
1565 2f399b0a Markus Armbruster
BlockDriverState *bdrv_next(BlockDriverState *bs)
1566 2f399b0a Markus Armbruster
{
1567 2f399b0a Markus Armbruster
    if (!bs) {
1568 2f399b0a Markus Armbruster
        return QTAILQ_FIRST(&bdrv_states);
1569 2f399b0a Markus Armbruster
    }
1570 2f399b0a Markus Armbruster
    return QTAILQ_NEXT(bs, list);
1571 2f399b0a Markus Armbruster
}
1572 2f399b0a Markus Armbruster
1573 51de9760 aliguori
void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1574 81d0912d bellard
{
1575 81d0912d bellard
    BlockDriverState *bs;
1576 81d0912d bellard
1577 1b7bdbc1 Stefan Hajnoczi
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1578 51de9760 aliguori
        it(opaque, bs);
1579 81d0912d bellard
    }
1580 81d0912d bellard
}
1581 81d0912d bellard
1582 ea2384d3 bellard
const char *bdrv_get_device_name(BlockDriverState *bs)
1583 ea2384d3 bellard
{
1584 ea2384d3 bellard
    return bs->device_name;
1585 ea2384d3 bellard
}
1586 ea2384d3 bellard
1587 205ef796 Kevin Wolf
int bdrv_flush(BlockDriverState *bs)
1588 7a6cba61 pbrook
{
1589 016f5cf6 Alexander Graf
    if (bs->open_flags & BDRV_O_NO_FLUSH) {
1590 205ef796 Kevin Wolf
        return 0;
1591 205ef796 Kevin Wolf
    }
1592 205ef796 Kevin Wolf
1593 205ef796 Kevin Wolf
    if (bs->drv && bs->drv->bdrv_flush) {
1594 205ef796 Kevin Wolf
        return bs->drv->bdrv_flush(bs);
1595 016f5cf6 Alexander Graf
    }
1596 016f5cf6 Alexander Graf
1597 205ef796 Kevin Wolf
    /*
1598 205ef796 Kevin Wolf
     * Some block drivers always operate in either writethrough or unsafe mode
1599 205ef796 Kevin Wolf
     * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1600 205ef796 Kevin Wolf
     * the server works (because the behaviour is hardcoded or depends on
1601 205ef796 Kevin Wolf
     * server-side configuration), so we can't ensure that everything is safe
1602 205ef796 Kevin Wolf
     * on disk. Returning an error doesn't work because that would break guests
1603 205ef796 Kevin Wolf
     * even if the server operates in writethrough mode.
1604 205ef796 Kevin Wolf
     *
1605 205ef796 Kevin Wolf
     * Let's hope the user knows what he's doing.
1606 205ef796 Kevin Wolf
     */
1607 205ef796 Kevin Wolf
    return 0;
1608 7a6cba61 pbrook
}
1609 7a6cba61 pbrook
1610 c6ca28d6 aliguori
void bdrv_flush_all(void)
1611 c6ca28d6 aliguori
{
1612 c6ca28d6 aliguori
    BlockDriverState *bs;
1613 c6ca28d6 aliguori
1614 1b7bdbc1 Stefan Hajnoczi
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1615 1b7bdbc1 Stefan Hajnoczi
        if (bs->drv && !bdrv_is_read_only(bs) &&
1616 1b7bdbc1 Stefan Hajnoczi
            (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1617 c6ca28d6 aliguori
            bdrv_flush(bs);
1618 1b7bdbc1 Stefan Hajnoczi
        }
1619 1b7bdbc1 Stefan Hajnoczi
    }
1620 c6ca28d6 aliguori
}
1621 c6ca28d6 aliguori
1622 f2feebbd Kevin Wolf
int bdrv_has_zero_init(BlockDriverState *bs)
1623 f2feebbd Kevin Wolf
{
1624 f2feebbd Kevin Wolf
    assert(bs->drv);
1625 f2feebbd Kevin Wolf
1626 336c1c12 Kevin Wolf
    if (bs->drv->bdrv_has_zero_init) {
1627 336c1c12 Kevin Wolf
        return bs->drv->bdrv_has_zero_init(bs);
1628 f2feebbd Kevin Wolf
    }
1629 f2feebbd Kevin Wolf
1630 f2feebbd Kevin Wolf
    return 1;
1631 f2feebbd Kevin Wolf
}
1632 f2feebbd Kevin Wolf
1633 bb8bf76f Christoph Hellwig
int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1634 bb8bf76f Christoph Hellwig
{
1635 bb8bf76f Christoph Hellwig
    if (!bs->drv) {
1636 bb8bf76f Christoph Hellwig
        return -ENOMEDIUM;
1637 bb8bf76f Christoph Hellwig
    }
1638 bb8bf76f Christoph Hellwig
    if (!bs->drv->bdrv_discard) {
1639 bb8bf76f Christoph Hellwig
        return 0;
1640 bb8bf76f Christoph Hellwig
    }
1641 bb8bf76f Christoph Hellwig
    return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1642 bb8bf76f Christoph Hellwig
}
1643 bb8bf76f Christoph Hellwig
1644 f58c7b35 ths
/*
1645 f58c7b35 ths
 * Returns true iff the specified sector is present in the disk image. Drivers
1646 f58c7b35 ths
 * not implementing the functionality are assumed to not support backing files,
1647 f58c7b35 ths
 * hence all their sectors are reported as allocated.
1648 f58c7b35 ths
 *
1649 f58c7b35 ths
 * 'pnum' is set to the number of sectors (including and immediately following
1650 f58c7b35 ths
 * the specified sector) that are known to be in the same
1651 f58c7b35 ths
 * allocated/unallocated state.
1652 f58c7b35 ths
 *
1653 f58c7b35 ths
 * 'nb_sectors' is the max value 'pnum' should be set to.
1654 f58c7b35 ths
 */
1655 f58c7b35 ths
int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1656 f58c7b35 ths
        int *pnum)
1657 f58c7b35 ths
{
1658 f58c7b35 ths
    int64_t n;
1659 f58c7b35 ths
    if (!bs->drv->bdrv_is_allocated) {
1660 f58c7b35 ths
        if (sector_num >= bs->total_sectors) {
1661 f58c7b35 ths
            *pnum = 0;
1662 f58c7b35 ths
            return 0;
1663 f58c7b35 ths
        }
1664 f58c7b35 ths
        n = bs->total_sectors - sector_num;
1665 f58c7b35 ths
        *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1666 f58c7b35 ths
        return 1;
1667 f58c7b35 ths
    }
1668 f58c7b35 ths
    return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1669 f58c7b35 ths
}
1670 f58c7b35 ths
1671 2582bfed Luiz Capitulino
void bdrv_mon_event(const BlockDriverState *bdrv,
1672 2582bfed Luiz Capitulino
                    BlockMonEventAction action, int is_read)
1673 2582bfed Luiz Capitulino
{
1674 2582bfed Luiz Capitulino
    QObject *data;
1675 2582bfed Luiz Capitulino
    const char *action_str;
1676 2582bfed Luiz Capitulino
1677 2582bfed Luiz Capitulino
    switch (action) {
1678 2582bfed Luiz Capitulino
    case BDRV_ACTION_REPORT:
1679 2582bfed Luiz Capitulino
        action_str = "report";
1680 2582bfed Luiz Capitulino
        break;
1681 2582bfed Luiz Capitulino
    case BDRV_ACTION_IGNORE:
1682 2582bfed Luiz Capitulino
        action_str = "ignore";
1683 2582bfed Luiz Capitulino
        break;
1684 2582bfed Luiz Capitulino
    case BDRV_ACTION_STOP:
1685 2582bfed Luiz Capitulino
        action_str = "stop";
1686 2582bfed Luiz Capitulino
        break;
1687 2582bfed Luiz Capitulino
    default:
1688 2582bfed Luiz Capitulino
        abort();
1689 2582bfed Luiz Capitulino
    }
1690 2582bfed Luiz Capitulino
1691 2582bfed Luiz Capitulino
    data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1692 2582bfed Luiz Capitulino
                              bdrv->device_name,
1693 2582bfed Luiz Capitulino
                              action_str,
1694 2582bfed Luiz Capitulino
                              is_read ? "read" : "write");
1695 2582bfed Luiz Capitulino
    monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1696 2582bfed Luiz Capitulino
1697 2582bfed Luiz Capitulino
    qobject_decref(data);
1698 2582bfed Luiz Capitulino
}
1699 2582bfed Luiz Capitulino
1700 d15e5465 Luiz Capitulino
static void bdrv_print_dict(QObject *obj, void *opaque)
1701 b338082b bellard
{
1702 d15e5465 Luiz Capitulino
    QDict *bs_dict;
1703 d15e5465 Luiz Capitulino
    Monitor *mon = opaque;
1704 d15e5465 Luiz Capitulino
1705 d15e5465 Luiz Capitulino
    bs_dict = qobject_to_qdict(obj);
1706 d15e5465 Luiz Capitulino
1707 d15e5465 Luiz Capitulino
    monitor_printf(mon, "%s: type=%s removable=%d",
1708 d15e5465 Luiz Capitulino
                        qdict_get_str(bs_dict, "device"),
1709 d15e5465 Luiz Capitulino
                        qdict_get_str(bs_dict, "type"),
1710 d15e5465 Luiz Capitulino
                        qdict_get_bool(bs_dict, "removable"));
1711 d15e5465 Luiz Capitulino
1712 d15e5465 Luiz Capitulino
    if (qdict_get_bool(bs_dict, "removable")) {
1713 d15e5465 Luiz Capitulino
        monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1714 d15e5465 Luiz Capitulino
    }
1715 d15e5465 Luiz Capitulino
1716 d15e5465 Luiz Capitulino
    if (qdict_haskey(bs_dict, "inserted")) {
1717 d15e5465 Luiz Capitulino
        QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1718 d15e5465 Luiz Capitulino
1719 d15e5465 Luiz Capitulino
        monitor_printf(mon, " file=");
1720 d15e5465 Luiz Capitulino
        monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1721 d15e5465 Luiz Capitulino
        if (qdict_haskey(qdict, "backing_file")) {
1722 d15e5465 Luiz Capitulino
            monitor_printf(mon, " backing_file=");
1723 d15e5465 Luiz Capitulino
            monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1724 d15e5465 Luiz Capitulino
        }
1725 d15e5465 Luiz Capitulino
        monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1726 d15e5465 Luiz Capitulino
                            qdict_get_bool(qdict, "ro"),
1727 d15e5465 Luiz Capitulino
                            qdict_get_str(qdict, "drv"),
1728 d15e5465 Luiz Capitulino
                            qdict_get_bool(qdict, "encrypted"));
1729 d15e5465 Luiz Capitulino
    } else {
1730 d15e5465 Luiz Capitulino
        monitor_printf(mon, " [not inserted]");
1731 d15e5465 Luiz Capitulino
    }
1732 d15e5465 Luiz Capitulino
1733 d15e5465 Luiz Capitulino
    monitor_printf(mon, "\n");
1734 d15e5465 Luiz Capitulino
}
1735 d15e5465 Luiz Capitulino
1736 d15e5465 Luiz Capitulino
void bdrv_info_print(Monitor *mon, const QObject *data)
1737 d15e5465 Luiz Capitulino
{
1738 d15e5465 Luiz Capitulino
    qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1739 d15e5465 Luiz Capitulino
}
1740 d15e5465 Luiz Capitulino
1741 d15e5465 Luiz Capitulino
void bdrv_info(Monitor *mon, QObject **ret_data)
1742 d15e5465 Luiz Capitulino
{
1743 d15e5465 Luiz Capitulino
    QList *bs_list;
1744 b338082b bellard
    BlockDriverState *bs;
1745 b338082b bellard
1746 d15e5465 Luiz Capitulino
    bs_list = qlist_new();
1747 d15e5465 Luiz Capitulino
1748 1b7bdbc1 Stefan Hajnoczi
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1749 d15e5465 Luiz Capitulino
        QObject *bs_obj;
1750 d15e5465 Luiz Capitulino
        const char *type = "unknown";
1751 d15e5465 Luiz Capitulino
1752 b338082b bellard
        switch(bs->type) {
1753 b338082b bellard
        case BDRV_TYPE_HD:
1754 d15e5465 Luiz Capitulino
            type = "hd";
1755 b338082b bellard
            break;
1756 b338082b bellard
        case BDRV_TYPE_CDROM:
1757 d15e5465 Luiz Capitulino
            type = "cdrom";
1758 b338082b bellard
            break;
1759 b338082b bellard
        case BDRV_TYPE_FLOPPY:
1760 d15e5465 Luiz Capitulino
            type = "floppy";
1761 b338082b bellard
            break;
1762 b338082b bellard
        }
1763 d15e5465 Luiz Capitulino
1764 d15e5465 Luiz Capitulino
        bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1765 d15e5465 Luiz Capitulino
                                    "'removable': %i, 'locked': %i }",
1766 d15e5465 Luiz Capitulino
                                    bs->device_name, type, bs->removable,
1767 d15e5465 Luiz Capitulino
                                    bs->locked);
1768 d15e5465 Luiz Capitulino
1769 19cb3738 bellard
        if (bs->drv) {
1770 d15e5465 Luiz Capitulino
            QObject *obj;
1771 d15e5465 Luiz Capitulino
            QDict *bs_dict = qobject_to_qdict(bs_obj);
1772 d15e5465 Luiz Capitulino
1773 d15e5465 Luiz Capitulino
            obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1774 d15e5465 Luiz Capitulino
                                     "'encrypted': %i }",
1775 d15e5465 Luiz Capitulino
                                     bs->filename, bs->read_only,
1776 d15e5465 Luiz Capitulino
                                     bs->drv->format_name,
1777 d15e5465 Luiz Capitulino
                                     bdrv_is_encrypted(bs));
1778 fef30743 ths
            if (bs->backing_file[0] != '\0') {
1779 d15e5465 Luiz Capitulino
                QDict *qdict = qobject_to_qdict(obj);
1780 d15e5465 Luiz Capitulino
                qdict_put(qdict, "backing_file",
1781 d15e5465 Luiz Capitulino
                          qstring_from_str(bs->backing_file));
1782 376253ec aliguori
            }
1783 d15e5465 Luiz Capitulino
1784 d15e5465 Luiz Capitulino
            qdict_put_obj(bs_dict, "inserted", obj);
1785 b338082b bellard
        }
1786 d15e5465 Luiz Capitulino
        qlist_append_obj(bs_list, bs_obj);
1787 b338082b bellard
    }
1788 d15e5465 Luiz Capitulino
1789 d15e5465 Luiz Capitulino
    *ret_data = QOBJECT(bs_list);
1790 b338082b bellard
}
1791 a36e69dd ths
1792 218a536a Luiz Capitulino
static void bdrv_stats_iter(QObject *data, void *opaque)
1793 a36e69dd ths
{
1794 218a536a Luiz Capitulino
    QDict *qdict;
1795 218a536a Luiz Capitulino
    Monitor *mon = opaque;
1796 218a536a Luiz Capitulino
1797 218a536a Luiz Capitulino
    qdict = qobject_to_qdict(data);
1798 218a536a Luiz Capitulino
    monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1799 218a536a Luiz Capitulino
1800 218a536a Luiz Capitulino
    qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1801 218a536a Luiz Capitulino
    monitor_printf(mon, " rd_bytes=%" PRId64
1802 218a536a Luiz Capitulino
                        " wr_bytes=%" PRId64
1803 218a536a Luiz Capitulino
                        " rd_operations=%" PRId64
1804 218a536a Luiz Capitulino
                        " wr_operations=%" PRId64
1805 218a536a Luiz Capitulino
                        "\n",
1806 218a536a Luiz Capitulino
                        qdict_get_int(qdict, "rd_bytes"),
1807 218a536a Luiz Capitulino
                        qdict_get_int(qdict, "wr_bytes"),
1808 218a536a Luiz Capitulino
                        qdict_get_int(qdict, "rd_operations"),
1809 218a536a Luiz Capitulino
                        qdict_get_int(qdict, "wr_operations"));
1810 218a536a Luiz Capitulino
}
1811 218a536a Luiz Capitulino
1812 218a536a Luiz Capitulino
void bdrv_stats_print(Monitor *mon, const QObject *data)
1813 218a536a Luiz Capitulino
{
1814 218a536a Luiz Capitulino
    qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1815 218a536a Luiz Capitulino
}
1816 218a536a Luiz Capitulino
1817 294cc35f Kevin Wolf
static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1818 294cc35f Kevin Wolf
{
1819 294cc35f Kevin Wolf
    QObject *res;
1820 294cc35f Kevin Wolf
    QDict *dict;
1821 294cc35f Kevin Wolf
1822 294cc35f Kevin Wolf
    res = qobject_from_jsonf("{ 'stats': {"
1823 294cc35f Kevin Wolf
                             "'rd_bytes': %" PRId64 ","
1824 294cc35f Kevin Wolf
                             "'wr_bytes': %" PRId64 ","
1825 294cc35f Kevin Wolf
                             "'rd_operations': %" PRId64 ","
1826 294cc35f Kevin Wolf
                             "'wr_operations': %" PRId64 ","
1827 294cc35f Kevin Wolf
                             "'wr_highest_offset': %" PRId64
1828 294cc35f Kevin Wolf
                             "} }",
1829 294cc35f Kevin Wolf
                             bs->rd_bytes, bs->wr_bytes,
1830 294cc35f Kevin Wolf
                             bs->rd_ops, bs->wr_ops,
1831 5ffbbc67 Blue Swirl
                             bs->wr_highest_sector *
1832 5ffbbc67 Blue Swirl
                             (uint64_t)BDRV_SECTOR_SIZE);
1833 294cc35f Kevin Wolf
    dict  = qobject_to_qdict(res);
1834 294cc35f Kevin Wolf
1835 294cc35f Kevin Wolf
    if (*bs->device_name) {
1836 294cc35f Kevin Wolf
        qdict_put(dict, "device", qstring_from_str(bs->device_name));
1837 294cc35f Kevin Wolf
    }
1838 294cc35f Kevin Wolf
1839 294cc35f Kevin Wolf
    if (bs->file) {
1840 294cc35f Kevin Wolf
        QObject *parent = bdrv_info_stats_bs(bs->file);
1841 294cc35f Kevin Wolf
        qdict_put_obj(dict, "parent", parent);
1842 294cc35f Kevin Wolf
    }
1843 294cc35f Kevin Wolf
1844 294cc35f Kevin Wolf
    return res;
1845 294cc35f Kevin Wolf
}
1846 294cc35f Kevin Wolf
1847 218a536a Luiz Capitulino
void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1848 218a536a Luiz Capitulino
{
1849 218a536a Luiz Capitulino
    QObject *obj;
1850 218a536a Luiz Capitulino
    QList *devices;
1851 a36e69dd ths
    BlockDriverState *bs;
1852 a36e69dd ths
1853 218a536a Luiz Capitulino
    devices = qlist_new();
1854 218a536a Luiz Capitulino
1855 1b7bdbc1 Stefan Hajnoczi
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1856 294cc35f Kevin Wolf
        obj = bdrv_info_stats_bs(bs);
1857 218a536a Luiz Capitulino
        qlist_append_obj(devices, obj);
1858 a36e69dd ths
    }
1859 218a536a Luiz Capitulino
1860 218a536a Luiz Capitulino
    *ret_data = QOBJECT(devices);
1861 a36e69dd ths
}
1862 ea2384d3 bellard
1863 045df330 aliguori
const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1864 045df330 aliguori
{
1865 045df330 aliguori
    if (bs->backing_hd && bs->backing_hd->encrypted)
1866 045df330 aliguori
        return bs->backing_file;
1867 045df330 aliguori
    else if (bs->encrypted)
1868 045df330 aliguori
        return bs->filename;
1869 045df330 aliguori
    else
1870 045df330 aliguori
        return NULL;
1871 045df330 aliguori
}
1872 045df330 aliguori
1873 5fafdf24 ths
void bdrv_get_backing_filename(BlockDriverState *bs,
1874 83f64091 bellard
                               char *filename, int filename_size)
1875 83f64091 bellard
{
1876 b783e409 Kevin Wolf
    if (!bs->backing_file) {
1877 83f64091 bellard
        pstrcpy(filename, filename_size, "");
1878 83f64091 bellard
    } else {
1879 83f64091 bellard
        pstrcpy(filename, filename_size, bs->backing_file);
1880 83f64091 bellard
    }
1881 83f64091 bellard
}
1882 83f64091 bellard
1883 5fafdf24 ths
int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1884 faea38e7 bellard
                          const uint8_t *buf, int nb_sectors)
1885 faea38e7 bellard
{
1886 faea38e7 bellard
    BlockDriver *drv = bs->drv;
1887 faea38e7 bellard
    if (!drv)
1888 19cb3738 bellard
        return -ENOMEDIUM;
1889 faea38e7 bellard
    if (!drv->bdrv_write_compressed)
1890 faea38e7 bellard
        return -ENOTSUP;
1891 fbb7b4e0 Kevin Wolf
    if (bdrv_check_request(bs, sector_num, nb_sectors))
1892 fbb7b4e0 Kevin Wolf
        return -EIO;
1893 a55eb92c Jan Kiszka
1894 c6d22830 Jan Kiszka
    if (bs->dirty_bitmap) {
1895 7cd1e32a lirans@il.ibm.com
        set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1896 7cd1e32a lirans@il.ibm.com
    }
1897 a55eb92c Jan Kiszka
1898 faea38e7 bellard
    return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1899 faea38e7 bellard
}
1900 3b46e624 ths
1901 faea38e7 bellard
int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1902 faea38e7 bellard
{
1903 faea38e7 bellard
    BlockDriver *drv = bs->drv;
1904 faea38e7 bellard
    if (!drv)
1905 19cb3738 bellard
        return -ENOMEDIUM;
1906 faea38e7 bellard
    if (!drv->bdrv_get_info)
1907 faea38e7 bellard
        return -ENOTSUP;
1908 faea38e7 bellard
    memset(bdi, 0, sizeof(*bdi));
1909 faea38e7 bellard
    return drv->bdrv_get_info(bs, bdi);
1910 faea38e7 bellard
}
1911 faea38e7 bellard
1912 45566e9c Christoph Hellwig
int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1913 45566e9c Christoph Hellwig
                      int64_t pos, int size)
1914 178e08a5 aliguori
{
1915 178e08a5 aliguori
    BlockDriver *drv = bs->drv;
1916 178e08a5 aliguori
    if (!drv)
1917 178e08a5 aliguori
        return -ENOMEDIUM;
1918 7cdb1f6d MORITA Kazutaka
    if (drv->bdrv_save_vmstate)
1919 7cdb1f6d MORITA Kazutaka
        return drv->bdrv_save_vmstate(bs, buf, pos, size);
1920 7cdb1f6d MORITA Kazutaka
    if (bs->file)
1921 7cdb1f6d MORITA Kazutaka
        return bdrv_save_vmstate(bs->file, buf, pos, size);
1922 7cdb1f6d MORITA Kazutaka
    return -ENOTSUP;
1923 178e08a5 aliguori
}
1924 178e08a5 aliguori
1925 45566e9c Christoph Hellwig
int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1926 45566e9c Christoph Hellwig
                      int64_t pos, int size)
1927 178e08a5 aliguori
{
1928 178e08a5 aliguori
    BlockDriver *drv = bs->drv;
1929 178e08a5 aliguori
    if (!drv)
1930 178e08a5 aliguori
        return -ENOMEDIUM;
1931 7cdb1f6d MORITA Kazutaka
    if (drv->bdrv_load_vmstate)
1932 7cdb1f6d MORITA Kazutaka
        return drv->bdrv_load_vmstate(bs, buf, pos, size);
1933 7cdb1f6d MORITA Kazutaka
    if (bs->file)
1934 7cdb1f6d MORITA Kazutaka
        return bdrv_load_vmstate(bs->file, buf, pos, size);
1935 7cdb1f6d MORITA Kazutaka
    return -ENOTSUP;
1936 178e08a5 aliguori
}
1937 178e08a5 aliguori
1938 8b9b0cc2 Kevin Wolf
void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1939 8b9b0cc2 Kevin Wolf
{
1940 8b9b0cc2 Kevin Wolf
    BlockDriver *drv = bs->drv;
1941 8b9b0cc2 Kevin Wolf
1942 8b9b0cc2 Kevin Wolf
    if (!drv || !drv->bdrv_debug_event) {
1943 8b9b0cc2 Kevin Wolf
        return;
1944 8b9b0cc2 Kevin Wolf
    }
1945 8b9b0cc2 Kevin Wolf
1946 8b9b0cc2 Kevin Wolf
    return drv->bdrv_debug_event(bs, event);
1947 8b9b0cc2 Kevin Wolf
1948 8b9b0cc2 Kevin Wolf
}
1949 8b9b0cc2 Kevin Wolf
1950 faea38e7 bellard
/**************************************************************/
1951 faea38e7 bellard
/* handling of snapshots */
1952 faea38e7 bellard
1953 feeee5ac Miguel Di Ciurcio Filho
int bdrv_can_snapshot(BlockDriverState *bs)
1954 feeee5ac Miguel Di Ciurcio Filho
{
1955 feeee5ac Miguel Di Ciurcio Filho
    BlockDriver *drv = bs->drv;
1956 feeee5ac Miguel Di Ciurcio Filho
    if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1957 feeee5ac Miguel Di Ciurcio Filho
        return 0;
1958 feeee5ac Miguel Di Ciurcio Filho
    }
1959 feeee5ac Miguel Di Ciurcio Filho
1960 feeee5ac Miguel Di Ciurcio Filho
    if (!drv->bdrv_snapshot_create) {
1961 feeee5ac Miguel Di Ciurcio Filho
        if (bs->file != NULL) {
1962 feeee5ac Miguel Di Ciurcio Filho
            return bdrv_can_snapshot(bs->file);
1963 feeee5ac Miguel Di Ciurcio Filho
        }
1964 feeee5ac Miguel Di Ciurcio Filho
        return 0;
1965 feeee5ac Miguel Di Ciurcio Filho
    }
1966 feeee5ac Miguel Di Ciurcio Filho
1967 feeee5ac Miguel Di Ciurcio Filho
    return 1;
1968 feeee5ac Miguel Di Ciurcio Filho
}
1969 feeee5ac Miguel Di Ciurcio Filho
1970 199630b6 Blue Swirl
int bdrv_is_snapshot(BlockDriverState *bs)
1971 199630b6 Blue Swirl
{
1972 199630b6 Blue Swirl
    return !!(bs->open_flags & BDRV_O_SNAPSHOT);
1973 199630b6 Blue Swirl
}
1974 199630b6 Blue Swirl
1975 f9092b10 Markus Armbruster
BlockDriverState *bdrv_snapshots(void)
1976 f9092b10 Markus Armbruster
{
1977 f9092b10 Markus Armbruster
    BlockDriverState *bs;
1978 f9092b10 Markus Armbruster
1979 3ac906f7 Markus Armbruster
    if (bs_snapshots) {
1980 f9092b10 Markus Armbruster
        return bs_snapshots;
1981 3ac906f7 Markus Armbruster
    }
1982 f9092b10 Markus Armbruster
1983 f9092b10 Markus Armbruster
    bs = NULL;
1984 f9092b10 Markus Armbruster
    while ((bs = bdrv_next(bs))) {
1985 f9092b10 Markus Armbruster
        if (bdrv_can_snapshot(bs)) {
1986 3ac906f7 Markus Armbruster
            bs_snapshots = bs;
1987 3ac906f7 Markus Armbruster
            return bs;
1988 f9092b10 Markus Armbruster
        }
1989 f9092b10 Markus Armbruster
    }
1990 f9092b10 Markus Armbruster
    return NULL;
1991 f9092b10 Markus Armbruster
}
1992 f9092b10 Markus Armbruster
1993 5fafdf24 ths
int bdrv_snapshot_create(BlockDriverState *bs,
1994 faea38e7 bellard
                         QEMUSnapshotInfo *sn_info)
1995 faea38e7 bellard
{
1996 faea38e7 bellard
    BlockDriver *drv = bs->drv;
1997 faea38e7 bellard
    if (!drv)
1998 19cb3738 bellard
        return -ENOMEDIUM;
1999 7cdb1f6d MORITA Kazutaka
    if (drv->bdrv_snapshot_create)
2000 7cdb1f6d MORITA Kazutaka
        return drv->bdrv_snapshot_create(bs, sn_info);
2001 7cdb1f6d MORITA Kazutaka
    if (bs->file)
2002 7cdb1f6d MORITA Kazutaka
        return bdrv_snapshot_create(bs->file, sn_info);
2003 7cdb1f6d MORITA Kazutaka
    return -ENOTSUP;
2004 faea38e7 bellard
}
2005 faea38e7 bellard
2006 5fafdf24 ths
int bdrv_snapshot_goto(BlockDriverState *bs,
2007 faea38e7 bellard
                       const char *snapshot_id)
2008 faea38e7 bellard
{
2009 faea38e7 bellard
    BlockDriver *drv = bs->drv;
2010 7cdb1f6d MORITA Kazutaka
    int ret, open_ret;
2011 7cdb1f6d MORITA Kazutaka
2012 faea38e7 bellard
    if (!drv)
2013 19cb3738 bellard
        return -ENOMEDIUM;
2014 7cdb1f6d MORITA Kazutaka
    if (drv->bdrv_snapshot_goto)
2015 7cdb1f6d MORITA Kazutaka
        return drv->bdrv_snapshot_goto(bs, snapshot_id);
2016 7cdb1f6d MORITA Kazutaka
2017 7cdb1f6d MORITA Kazutaka
    if (bs->file) {
2018 7cdb1f6d MORITA Kazutaka
        drv->bdrv_close(bs);
2019 7cdb1f6d MORITA Kazutaka
        ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2020 7cdb1f6d MORITA Kazutaka
        open_ret = drv->bdrv_open(bs, bs->open_flags);
2021 7cdb1f6d MORITA Kazutaka
        if (open_ret < 0) {
2022 7cdb1f6d MORITA Kazutaka
            bdrv_delete(bs->file);
2023 7cdb1f6d MORITA Kazutaka
            bs->drv = NULL;
2024 7cdb1f6d MORITA Kazutaka
            return open_ret;
2025 7cdb1f6d MORITA Kazutaka
        }
2026 7cdb1f6d MORITA Kazutaka
        return ret;
2027 7cdb1f6d MORITA Kazutaka
    }
2028 7cdb1f6d MORITA Kazutaka
2029 7cdb1f6d MORITA Kazutaka
    return -ENOTSUP;
2030 faea38e7 bellard
}
2031 faea38e7 bellard
2032 faea38e7 bellard
int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2033 faea38e7 bellard
{
2034 faea38e7 bellard
    BlockDriver *drv = bs->drv;
2035 faea38e7 bellard
    if (!drv)
2036 19cb3738 bellard
        return -ENOMEDIUM;
2037 7cdb1f6d MORITA Kazutaka
    if (drv->bdrv_snapshot_delete)
2038 7cdb1f6d MORITA Kazutaka
        return drv->bdrv_snapshot_delete(bs, snapshot_id);
2039 7cdb1f6d MORITA Kazutaka
    if (bs->file)
2040 7cdb1f6d MORITA Kazutaka
        return bdrv_snapshot_delete(bs->file, snapshot_id);
2041 7cdb1f6d MORITA Kazutaka
    return -ENOTSUP;
2042 faea38e7 bellard
}
2043 faea38e7 bellard
2044 5fafdf24 ths
int bdrv_snapshot_list(BlockDriverState *bs,
2045 faea38e7 bellard
                       QEMUSnapshotInfo **psn_info)
2046 faea38e7 bellard
{
2047 faea38e7 bellard
    BlockDriver *drv = bs->drv;
2048 faea38e7 bellard
    if (!drv)
2049 19cb3738 bellard
        return -ENOMEDIUM;
2050 7cdb1f6d MORITA Kazutaka
    if (drv->bdrv_snapshot_list)
2051 7cdb1f6d MORITA Kazutaka
        return drv->bdrv_snapshot_list(bs, psn_info);
2052 7cdb1f6d MORITA Kazutaka
    if (bs->file)
2053 7cdb1f6d MORITA Kazutaka
        return bdrv_snapshot_list(bs->file, psn_info);
2054 7cdb1f6d MORITA Kazutaka
    return -ENOTSUP;
2055 faea38e7 bellard
}
2056 faea38e7 bellard
2057 51ef6727 edison
int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2058 51ef6727 edison
        const char *snapshot_name)
2059 51ef6727 edison
{
2060 51ef6727 edison
    BlockDriver *drv = bs->drv;
2061 51ef6727 edison
    if (!drv) {
2062 51ef6727 edison
        return -ENOMEDIUM;
2063 51ef6727 edison
    }
2064 51ef6727 edison
    if (!bs->read_only) {
2065 51ef6727 edison
        return -EINVAL;
2066 51ef6727 edison
    }
2067 51ef6727 edison
    if (drv->bdrv_snapshot_load_tmp) {
2068 51ef6727 edison
        return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2069 51ef6727 edison
    }
2070 51ef6727 edison
    return -ENOTSUP;
2071 51ef6727 edison
}
2072 51ef6727 edison
2073 faea38e7 bellard
#define NB_SUFFIXES 4
2074 faea38e7 bellard
2075 faea38e7 bellard
char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2076 faea38e7 bellard
{
2077 faea38e7 bellard
    static const char suffixes[NB_SUFFIXES] = "KMGT";
2078 faea38e7 bellard
    int64_t base;
2079 faea38e7 bellard
    int i;
2080 faea38e7 bellard
2081 faea38e7 bellard
    if (size <= 999) {
2082 faea38e7 bellard
        snprintf(buf, buf_size, "%" PRId64, size);
2083 faea38e7 bellard
    } else {
2084 faea38e7 bellard
        base = 1024;
2085 faea38e7 bellard
        for(i = 0; i < NB_SUFFIXES; i++) {
2086 faea38e7 bellard
            if (size < (10 * base)) {
2087 5fafdf24 ths
                snprintf(buf, buf_size, "%0.1f%c",
2088 faea38e7 bellard
                         (double)size / base,
2089 faea38e7 bellard
                         suffixes[i]);
2090 faea38e7 bellard
                break;
2091 faea38e7 bellard
            } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2092 5fafdf24 ths
                snprintf(buf, buf_size, "%" PRId64 "%c",
2093 faea38e7 bellard
                         ((size + (base >> 1)) / base),
2094 faea38e7 bellard
                         suffixes[i]);
2095 faea38e7 bellard
                break;
2096 faea38e7 bellard
            }
2097 faea38e7 bellard
            base = base * 1024;
2098 faea38e7 bellard
        }
2099 faea38e7 bellard
    }
2100 faea38e7 bellard
    return buf;
2101 faea38e7 bellard
}
2102 faea38e7 bellard
2103 faea38e7 bellard
char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2104 faea38e7 bellard
{
2105 faea38e7 bellard
    char buf1[128], date_buf[128], clock_buf[128];
2106 3b9f94e1 bellard
#ifdef _WIN32
2107 3b9f94e1 bellard
    struct tm *ptm;
2108 3b9f94e1 bellard
#else
2109 faea38e7 bellard
    struct tm tm;
2110 3b9f94e1 bellard
#endif
2111 faea38e7 bellard
    time_t ti;
2112 faea38e7 bellard
    int64_t secs;
2113 faea38e7 bellard
2114 faea38e7 bellard
    if (!sn) {
2115 5fafdf24 ths
        snprintf(buf, buf_size,
2116 5fafdf24 ths
                 "%-10s%-20s%7s%20s%15s",
2117 faea38e7 bellard
                 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2118 faea38e7 bellard
    } else {
2119 faea38e7 bellard
        ti = sn->date_sec;
2120 3b9f94e1 bellard
#ifdef _WIN32
2121 3b9f94e1 bellard
        ptm = localtime(&ti);
2122 3b9f94e1 bellard
        strftime(date_buf, sizeof(date_buf),
2123 3b9f94e1 bellard
                 "%Y-%m-%d %H:%M:%S", ptm);
2124 3b9f94e1 bellard
#else
2125 faea38e7 bellard
        localtime_r(&ti, &tm);
2126 faea38e7 bellard
        strftime(date_buf, sizeof(date_buf),
2127 faea38e7 bellard
                 "%Y-%m-%d %H:%M:%S", &tm);
2128 3b9f94e1 bellard
#endif
2129 faea38e7 bellard
        secs = sn->vm_clock_nsec / 1000000000;
2130 faea38e7 bellard
        snprintf(clock_buf, sizeof(clock_buf),
2131 faea38e7 bellard
                 "%02d:%02d:%02d.%03d",
2132 faea38e7 bellard
                 (int)(secs / 3600),
2133 faea38e7 bellard
                 (int)((secs / 60) % 60),
2134 5fafdf24 ths
                 (int)(secs % 60),
2135 faea38e7 bellard
                 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2136 faea38e7 bellard
        snprintf(buf, buf_size,
2137 5fafdf24 ths
                 "%-10s%-20s%7s%20s%15s",
2138 faea38e7 bellard
                 sn->id_str, sn->name,
2139 faea38e7 bellard
                 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2140 faea38e7 bellard
                 date_buf,
2141 faea38e7 bellard
                 clock_buf);
2142 faea38e7 bellard
    }
2143 faea38e7 bellard
    return buf;
2144 faea38e7 bellard
}
2145 faea38e7 bellard
2146 83f64091 bellard
2147 ea2384d3 bellard
/**************************************************************/
2148 83f64091 bellard
/* async I/Os */
2149 ea2384d3 bellard
2150 3b69e4b9 aliguori
BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2151 f141eafe aliguori
                                 QEMUIOVector *qiov, int nb_sectors,
2152 3b69e4b9 aliguori
                                 BlockDriverCompletionFunc *cb, void *opaque)
2153 3b69e4b9 aliguori
{
2154 83f64091 bellard
    BlockDriver *drv = bs->drv;
2155 a36e69dd ths
    BlockDriverAIOCB *ret;
2156 83f64091 bellard
2157 bbf0a440 Stefan Hajnoczi
    trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2158 bbf0a440 Stefan Hajnoczi
2159 19cb3738 bellard
    if (!drv)
2160 ce1a14dc pbrook
        return NULL;
2161 71d0770c aliguori
    if (bdrv_check_request(bs, sector_num, nb_sectors))
2162 71d0770c aliguori
        return NULL;
2163 3b46e624 ths
2164 f141eafe aliguori
    ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2165 f141eafe aliguori
                              cb, opaque);
2166 a36e69dd ths
2167 a36e69dd ths
    if (ret) {
2168 a36e69dd ths
        /* Update stats even though technically transfer has not happened. */
2169 6ea44308 Jan Kiszka
        bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2170 a36e69dd ths
        bs->rd_ops ++;
2171 a36e69dd ths
    }
2172 a36e69dd ths
2173 a36e69dd ths
    return ret;
2174 ea2384d3 bellard
}
2175 ea2384d3 bellard
2176 4dcafbb1 Marcelo Tosatti
typedef struct BlockCompleteData {
2177 4dcafbb1 Marcelo Tosatti
    BlockDriverCompletionFunc *cb;
2178 4dcafbb1 Marcelo Tosatti
    void *opaque;
2179 4dcafbb1 Marcelo Tosatti
    BlockDriverState *bs;
2180 4dcafbb1 Marcelo Tosatti
    int64_t sector_num;
2181 4dcafbb1 Marcelo Tosatti
    int nb_sectors;
2182 4dcafbb1 Marcelo Tosatti
} BlockCompleteData;
2183 4dcafbb1 Marcelo Tosatti
2184 4dcafbb1 Marcelo Tosatti
static void block_complete_cb(void *opaque, int ret)
2185 4dcafbb1 Marcelo Tosatti
{
2186 4dcafbb1 Marcelo Tosatti
    BlockCompleteData *b = opaque;
2187 4dcafbb1 Marcelo Tosatti
2188 4dcafbb1 Marcelo Tosatti
    if (b->bs->dirty_bitmap) {
2189 4dcafbb1 Marcelo Tosatti
        set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2190 4dcafbb1 Marcelo Tosatti
    }
2191 4dcafbb1 Marcelo Tosatti
    b->cb(b->opaque, ret);
2192 4dcafbb1 Marcelo Tosatti
    qemu_free(b);
2193 4dcafbb1 Marcelo Tosatti
}
2194 4dcafbb1 Marcelo Tosatti
2195 4dcafbb1 Marcelo Tosatti
static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2196 4dcafbb1 Marcelo Tosatti
                                             int64_t sector_num,
2197 4dcafbb1 Marcelo Tosatti
                                             int nb_sectors,
2198 4dcafbb1 Marcelo Tosatti
                                             BlockDriverCompletionFunc *cb,
2199 4dcafbb1 Marcelo Tosatti
                                             void *opaque)
2200 4dcafbb1 Marcelo Tosatti
{
2201 4dcafbb1 Marcelo Tosatti
    BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
2202 4dcafbb1 Marcelo Tosatti
2203 4dcafbb1 Marcelo Tosatti
    blkdata->bs = bs;
2204 4dcafbb1 Marcelo Tosatti
    blkdata->cb = cb;
2205 4dcafbb1 Marcelo Tosatti
    blkdata->opaque = opaque;
2206 4dcafbb1 Marcelo Tosatti
    blkdata->sector_num = sector_num;
2207 4dcafbb1 Marcelo Tosatti
    blkdata->nb_sectors = nb_sectors;
2208 4dcafbb1 Marcelo Tosatti
2209 4dcafbb1 Marcelo Tosatti
    return blkdata;
2210 4dcafbb1 Marcelo Tosatti
}
2211 4dcafbb1 Marcelo Tosatti
2212 f141eafe aliguori
BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2213 f141eafe aliguori
                                  QEMUIOVector *qiov, int nb_sectors,
2214 f141eafe aliguori
                                  BlockDriverCompletionFunc *cb, void *opaque)
2215 ea2384d3 bellard
{
2216 83f64091 bellard
    BlockDriver *drv = bs->drv;
2217 a36e69dd ths
    BlockDriverAIOCB *ret;
2218 4dcafbb1 Marcelo Tosatti
    BlockCompleteData *blk_cb_data;
2219 ea2384d3 bellard
2220 bbf0a440 Stefan Hajnoczi
    trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2221 bbf0a440 Stefan Hajnoczi
2222 19cb3738 bellard
    if (!drv)
2223 ce1a14dc pbrook
        return NULL;
2224 83f64091 bellard
    if (bs->read_only)
2225 ce1a14dc pbrook
        return NULL;
2226 71d0770c aliguori
    if (bdrv_check_request(bs, sector_num, nb_sectors))
2227 71d0770c aliguori
        return NULL;
2228 83f64091 bellard
2229 c6d22830 Jan Kiszka
    if (bs->dirty_bitmap) {
2230 4dcafbb1 Marcelo Tosatti
        blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2231 4dcafbb1 Marcelo Tosatti
                                         opaque);
2232 4dcafbb1 Marcelo Tosatti
        cb = &block_complete_cb;
2233 4dcafbb1 Marcelo Tosatti
        opaque = blk_cb_data;
2234 7cd1e32a lirans@il.ibm.com
    }
2235 a55eb92c Jan Kiszka
2236 f141eafe aliguori
    ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2237 f141eafe aliguori
                               cb, opaque);
2238 a36e69dd ths
2239 a36e69dd ths
    if (ret) {
2240 294cc35f Kevin Wolf
        /* Update stats even though technically transfer has not happened. */
2241 294cc35f Kevin Wolf
        bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2242 294cc35f Kevin Wolf
        bs->wr_ops ++;
2243 294cc35f Kevin Wolf
        if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2244 294cc35f Kevin Wolf
            bs->wr_highest_sector = sector_num + nb_sectors - 1;
2245 294cc35f Kevin Wolf
        }
2246 a36e69dd ths
    }
2247 a36e69dd ths
2248 a36e69dd ths
    return ret;
2249 83f64091 bellard
}
2250 83f64091 bellard
2251 40b4f539 Kevin Wolf
2252 40b4f539 Kevin Wolf
typedef struct MultiwriteCB {
2253 40b4f539 Kevin Wolf
    int error;
2254 40b4f539 Kevin Wolf
    int num_requests;
2255 40b4f539 Kevin Wolf
    int num_callbacks;
2256 40b4f539 Kevin Wolf
    struct {
2257 40b4f539 Kevin Wolf
        BlockDriverCompletionFunc *cb;
2258 40b4f539 Kevin Wolf
        void *opaque;
2259 40b4f539 Kevin Wolf
        QEMUIOVector *free_qiov;
2260 40b4f539 Kevin Wolf
        void *free_buf;
2261 40b4f539 Kevin Wolf
    } callbacks[];
2262 40b4f539 Kevin Wolf
} MultiwriteCB;
2263 40b4f539 Kevin Wolf
2264 40b4f539 Kevin Wolf
static void multiwrite_user_cb(MultiwriteCB *mcb)
2265 40b4f539 Kevin Wolf
{
2266 40b4f539 Kevin Wolf
    int i;
2267 40b4f539 Kevin Wolf
2268 40b4f539 Kevin Wolf
    for (i = 0; i < mcb->num_callbacks; i++) {
2269 40b4f539 Kevin Wolf
        mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2270 1e1ea48d Stefan Hajnoczi
        if (mcb->callbacks[i].free_qiov) {
2271 1e1ea48d Stefan Hajnoczi
            qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2272 1e1ea48d Stefan Hajnoczi
        }
2273 40b4f539 Kevin Wolf
        qemu_free(mcb->callbacks[i].free_qiov);
2274 f8a83245 Herve Poussineau
        qemu_vfree(mcb->callbacks[i].free_buf);
2275 40b4f539 Kevin Wolf
    }
2276 40b4f539 Kevin Wolf
}
2277 40b4f539 Kevin Wolf
2278 40b4f539 Kevin Wolf
static void multiwrite_cb(void *opaque, int ret)
2279 40b4f539 Kevin Wolf
{
2280 40b4f539 Kevin Wolf
    MultiwriteCB *mcb = opaque;
2281 40b4f539 Kevin Wolf
2282 6d519a5f Stefan Hajnoczi
    trace_multiwrite_cb(mcb, ret);
2283 6d519a5f Stefan Hajnoczi
2284 cb6d3ca0 Kevin Wolf
    if (ret < 0 && !mcb->error) {
2285 40b4f539 Kevin Wolf
        mcb->error = ret;
2286 40b4f539 Kevin Wolf
    }
2287 40b4f539 Kevin Wolf
2288 40b4f539 Kevin Wolf
    mcb->num_requests--;
2289 40b4f539 Kevin Wolf
    if (mcb->num_requests == 0) {
2290 de189a1b Kevin Wolf
        multiwrite_user_cb(mcb);
2291 40b4f539 Kevin Wolf
        qemu_free(mcb);
2292 40b4f539 Kevin Wolf
    }
2293 40b4f539 Kevin Wolf
}
2294 40b4f539 Kevin Wolf
2295 40b4f539 Kevin Wolf
static int multiwrite_req_compare(const void *a, const void *b)
2296 40b4f539 Kevin Wolf
{
2297 77be4366 Christoph Hellwig
    const BlockRequest *req1 = a, *req2 = b;
2298 77be4366 Christoph Hellwig
2299 77be4366 Christoph Hellwig
    /*
2300 77be4366 Christoph Hellwig
     * Note that we can't simply subtract req2->sector from req1->sector
2301 77be4366 Christoph Hellwig
     * here as that could overflow the return value.
2302 77be4366 Christoph Hellwig
     */
2303 77be4366 Christoph Hellwig
    if (req1->sector > req2->sector) {
2304 77be4366 Christoph Hellwig
        return 1;
2305 77be4366 Christoph Hellwig
    } else if (req1->sector < req2->sector) {
2306 77be4366 Christoph Hellwig
        return -1;
2307 77be4366 Christoph Hellwig
    } else {
2308 77be4366 Christoph Hellwig
        return 0;
2309 77be4366 Christoph Hellwig
    }
2310 40b4f539 Kevin Wolf
}
2311 40b4f539 Kevin Wolf
2312 40b4f539 Kevin Wolf
/*
2313 40b4f539 Kevin Wolf
 * Takes a bunch of requests and tries to merge them. Returns the number of
2314 40b4f539 Kevin Wolf
 * requests that remain after merging.
2315 40b4f539 Kevin Wolf
 */
2316 40b4f539 Kevin Wolf
static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2317 40b4f539 Kevin Wolf
    int num_reqs, MultiwriteCB *mcb)
2318 40b4f539 Kevin Wolf
{
2319 40b4f539 Kevin Wolf
    int i, outidx;
2320 40b4f539 Kevin Wolf
2321 40b4f539 Kevin Wolf
    // Sort requests by start sector
2322 40b4f539 Kevin Wolf
    qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2323 40b4f539 Kevin Wolf
2324 40b4f539 Kevin Wolf
    // Check if adjacent requests touch the same clusters. If so, combine them,
2325 40b4f539 Kevin Wolf
    // filling up gaps with zero sectors.
2326 40b4f539 Kevin Wolf
    outidx = 0;
2327 40b4f539 Kevin Wolf
    for (i = 1; i < num_reqs; i++) {
2328 40b4f539 Kevin Wolf
        int merge = 0;
2329 40b4f539 Kevin Wolf
        int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2330 40b4f539 Kevin Wolf
2331 40b4f539 Kevin Wolf
        // This handles the cases that are valid for all block drivers, namely
2332 40b4f539 Kevin Wolf
        // exactly sequential writes and overlapping writes.
2333 40b4f539 Kevin Wolf
        if (reqs[i].sector <= oldreq_last) {
2334 40b4f539 Kevin Wolf
            merge = 1;
2335 40b4f539 Kevin Wolf
        }
2336 40b4f539 Kevin Wolf
2337 40b4f539 Kevin Wolf
        // The block driver may decide that it makes sense to combine requests
2338 40b4f539 Kevin Wolf
        // even if there is a gap of some sectors between them. In this case,
2339 40b4f539 Kevin Wolf
        // the gap is filled with zeros (therefore only applicable for yet
2340 40b4f539 Kevin Wolf
        // unused space in format like qcow2).
2341 40b4f539 Kevin Wolf
        if (!merge && bs->drv->bdrv_merge_requests) {
2342 40b4f539 Kevin Wolf
            merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2343 40b4f539 Kevin Wolf
        }
2344 40b4f539 Kevin Wolf
2345 e2a305fb Christoph Hellwig
        if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2346 e2a305fb Christoph Hellwig
            merge = 0;
2347 e2a305fb Christoph Hellwig
        }
2348 e2a305fb Christoph Hellwig
2349 40b4f539 Kevin Wolf
        if (merge) {
2350 40b4f539 Kevin Wolf
            size_t size;
2351 40b4f539 Kevin Wolf
            QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2352 40b4f539 Kevin Wolf
            qemu_iovec_init(qiov,
2353 40b4f539 Kevin Wolf
                reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2354 40b4f539 Kevin Wolf
2355 40b4f539 Kevin Wolf
            // Add the first request to the merged one. If the requests are
2356 40b4f539 Kevin Wolf
            // overlapping, drop the last sectors of the first request.
2357 40b4f539 Kevin Wolf
            size = (reqs[i].sector - reqs[outidx].sector) << 9;
2358 40b4f539 Kevin Wolf
            qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2359 40b4f539 Kevin Wolf
2360 40b4f539 Kevin Wolf
            // We might need to add some zeros between the two requests
2361 40b4f539 Kevin Wolf
            if (reqs[i].sector > oldreq_last) {
2362 40b4f539 Kevin Wolf
                size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2363 40b4f539 Kevin Wolf
                uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2364 40b4f539 Kevin Wolf
                memset(buf, 0, zero_bytes);
2365 40b4f539 Kevin Wolf
                qemu_iovec_add(qiov, buf, zero_bytes);
2366 40b4f539 Kevin Wolf
                mcb->callbacks[i].free_buf = buf;
2367 40b4f539 Kevin Wolf
            }
2368 40b4f539 Kevin Wolf
2369 40b4f539 Kevin Wolf
            // Add the second request
2370 40b4f539 Kevin Wolf
            qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2371 40b4f539 Kevin Wolf
2372 cbf1dff2 Kevin Wolf
            reqs[outidx].nb_sectors = qiov->size >> 9;
2373 40b4f539 Kevin Wolf
            reqs[outidx].qiov = qiov;
2374 40b4f539 Kevin Wolf
2375 40b4f539 Kevin Wolf
            mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2376 40b4f539 Kevin Wolf
        } else {
2377 40b4f539 Kevin Wolf
            outidx++;
2378 40b4f539 Kevin Wolf
            reqs[outidx].sector     = reqs[i].sector;
2379 40b4f539 Kevin Wolf
            reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2380 40b4f539 Kevin Wolf
            reqs[outidx].qiov       = reqs[i].qiov;
2381 40b4f539 Kevin Wolf
        }
2382 40b4f539 Kevin Wolf
    }
2383 40b4f539 Kevin Wolf
2384 40b4f539 Kevin Wolf
    return outidx + 1;
2385 40b4f539 Kevin Wolf
}
2386 40b4f539 Kevin Wolf
2387 40b4f539 Kevin Wolf
/*
2388 40b4f539 Kevin Wolf
 * Submit multiple AIO write requests at once.
2389 40b4f539 Kevin Wolf
 *
2390 40b4f539 Kevin Wolf
 * On success, the function returns 0 and all requests in the reqs array have
2391 40b4f539 Kevin Wolf
 * been submitted. In error case this function returns -1, and any of the
2392 40b4f539 Kevin Wolf
 * requests may or may not be submitted yet. In particular, this means that the
2393 40b4f539 Kevin Wolf
 * callback will be called for some of the requests, for others it won't. The
2394 40b4f539 Kevin Wolf
 * caller must check the error field of the BlockRequest to wait for the right
2395 40b4f539 Kevin Wolf
 * callbacks (if error != 0, no callback will be called).
2396 40b4f539 Kevin Wolf
 *
2397 40b4f539 Kevin Wolf
 * The implementation may modify the contents of the reqs array, e.g. to merge
2398 40b4f539 Kevin Wolf
 * requests. However, the fields opaque and error are left unmodified as they
2399 40b4f539 Kevin Wolf
 * are used to signal failure for a single request to the caller.
2400 40b4f539 Kevin Wolf
 */
2401 40b4f539 Kevin Wolf
int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2402 40b4f539 Kevin Wolf
{
2403 40b4f539 Kevin Wolf
    BlockDriverAIOCB *acb;
2404 40b4f539 Kevin Wolf
    MultiwriteCB *mcb;
2405 40b4f539 Kevin Wolf
    int i;
2406 40b4f539 Kevin Wolf
2407 301db7c2 Ryan Harper
    /* don't submit writes if we don't have a medium */
2408 301db7c2 Ryan Harper
    if (bs->drv == NULL) {
2409 301db7c2 Ryan Harper
        for (i = 0; i < num_reqs; i++) {
2410 301db7c2 Ryan Harper
            reqs[i].error = -ENOMEDIUM;
2411 301db7c2 Ryan Harper
        }
2412 301db7c2 Ryan Harper
        return -1;
2413 301db7c2 Ryan Harper
    }
2414 301db7c2 Ryan Harper
2415 40b4f539 Kevin Wolf
    if (num_reqs == 0) {
2416 40b4f539 Kevin Wolf
        return 0;
2417 40b4f539 Kevin Wolf
    }
2418 40b4f539 Kevin Wolf
2419 40b4f539 Kevin Wolf
    // Create MultiwriteCB structure
2420 40b4f539 Kevin Wolf
    mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2421 40b4f539 Kevin Wolf
    mcb->num_requests = 0;
2422 40b4f539 Kevin Wolf
    mcb->num_callbacks = num_reqs;
2423 40b4f539 Kevin Wolf
2424 40b4f539 Kevin Wolf
    for (i = 0; i < num_reqs; i++) {
2425 40b4f539 Kevin Wolf
        mcb->callbacks[i].cb = reqs[i].cb;
2426 40b4f539 Kevin Wolf
        mcb->callbacks[i].opaque = reqs[i].opaque;
2427 40b4f539 Kevin Wolf
    }
2428 40b4f539 Kevin Wolf
2429 40b4f539 Kevin Wolf
    // Check for mergable requests
2430 40b4f539 Kevin Wolf
    num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2431 40b4f539 Kevin Wolf
2432 6d519a5f Stefan Hajnoczi
    trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2433 6d519a5f Stefan Hajnoczi
2434 453f9a16 Kevin Wolf
    /*
2435 453f9a16 Kevin Wolf
     * Run the aio requests. As soon as one request can't be submitted
2436 453f9a16 Kevin Wolf
     * successfully, fail all requests that are not yet submitted (we must
2437 453f9a16 Kevin Wolf
     * return failure for all requests anyway)
2438 453f9a16 Kevin Wolf
     *
2439 453f9a16 Kevin Wolf
     * num_requests cannot be set to the right value immediately: If
2440 453f9a16 Kevin Wolf
     * bdrv_aio_writev fails for some request, num_requests would be too high
2441 453f9a16 Kevin Wolf
     * and therefore multiwrite_cb() would never recognize the multiwrite
2442 453f9a16 Kevin Wolf
     * request as completed. We also cannot use the loop variable i to set it
2443 453f9a16 Kevin Wolf
     * when the first request fails because the callback may already have been
2444 453f9a16 Kevin Wolf
     * called for previously submitted requests. Thus, num_requests must be
2445 453f9a16 Kevin Wolf
     * incremented for each request that is submitted.
2446 453f9a16 Kevin Wolf
     *
2447 453f9a16 Kevin Wolf
     * The problem that callbacks may be called early also means that we need
2448 453f9a16 Kevin Wolf
     * to take care that num_requests doesn't become 0 before all requests are
2449 453f9a16 Kevin Wolf
     * submitted - multiwrite_cb() would consider the multiwrite request
2450 453f9a16 Kevin Wolf
     * completed. A dummy request that is "completed" by a manual call to
2451 453f9a16 Kevin Wolf
     * multiwrite_cb() takes care of this.
2452 453f9a16 Kevin Wolf
     */
2453 453f9a16 Kevin Wolf
    mcb->num_requests = 1;
2454 453f9a16 Kevin Wolf
2455 6d519a5f Stefan Hajnoczi
    // Run the aio requests
2456 40b4f539 Kevin Wolf
    for (i = 0; i < num_reqs; i++) {
2457 453f9a16 Kevin Wolf
        mcb->num_requests++;
2458 40b4f539 Kevin Wolf
        acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2459 40b4f539 Kevin Wolf
            reqs[i].nb_sectors, multiwrite_cb, mcb);
2460 40b4f539 Kevin Wolf
2461 40b4f539 Kevin Wolf
        if (acb == NULL) {
2462 40b4f539 Kevin Wolf
            // We can only fail the whole thing if no request has been
2463 40b4f539 Kevin Wolf
            // submitted yet. Otherwise we'll wait for the submitted AIOs to
2464 40b4f539 Kevin Wolf
            // complete and report the error in the callback.
2465 453f9a16 Kevin Wolf
            if (i == 0) {
2466 6d519a5f Stefan Hajnoczi
                trace_bdrv_aio_multiwrite_earlyfail(mcb);
2467 40b4f539 Kevin Wolf
                goto fail;
2468 40b4f539 Kevin Wolf
            } else {
2469 6d519a5f Stefan Hajnoczi
                trace_bdrv_aio_multiwrite_latefail(mcb, i);
2470 7eb58a6c Kevin Wolf
                multiwrite_cb(mcb, -EIO);
2471 40b4f539 Kevin Wolf
                break;
2472 40b4f539 Kevin Wolf
            }
2473 40b4f539 Kevin Wolf
        }
2474 40b4f539 Kevin Wolf
    }
2475 40b4f539 Kevin Wolf
2476 453f9a16 Kevin Wolf
    /* Complete the dummy request */
2477 453f9a16 Kevin Wolf
    multiwrite_cb(mcb, 0);
2478 453f9a16 Kevin Wolf
2479 40b4f539 Kevin Wolf
    return 0;
2480 40b4f539 Kevin Wolf
2481 40b4f539 Kevin Wolf
fail:
2482 453f9a16 Kevin Wolf
    for (i = 0; i < mcb->num_callbacks; i++) {
2483 453f9a16 Kevin Wolf
        reqs[i].error = -EIO;
2484 453f9a16 Kevin Wolf
    }
2485 af474591 Bruce Rogers
    qemu_free(mcb);
2486 40b4f539 Kevin Wolf
    return -1;
2487 40b4f539 Kevin Wolf
}
2488 40b4f539 Kevin Wolf
2489 b2e12bc6 Christoph Hellwig
BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2490 b2e12bc6 Christoph Hellwig
        BlockDriverCompletionFunc *cb, void *opaque)
2491 b2e12bc6 Christoph Hellwig
{
2492 b2e12bc6 Christoph Hellwig
    BlockDriver *drv = bs->drv;
2493 b2e12bc6 Christoph Hellwig
2494 a13aac04 Stefan Hajnoczi
    trace_bdrv_aio_flush(bs, opaque);
2495 a13aac04 Stefan Hajnoczi
2496 016f5cf6 Alexander Graf
    if (bs->open_flags & BDRV_O_NO_FLUSH) {
2497 016f5cf6 Alexander Graf
        return bdrv_aio_noop_em(bs, cb, opaque);
2498 016f5cf6 Alexander Graf
    }
2499 016f5cf6 Alexander Graf
2500 b2e12bc6 Christoph Hellwig
    if (!drv)
2501 b2e12bc6 Christoph Hellwig
        return NULL;
2502 b2e12bc6 Christoph Hellwig
    return drv->bdrv_aio_flush(bs, cb, opaque);
2503 b2e12bc6 Christoph Hellwig
}
2504 b2e12bc6 Christoph Hellwig
2505 83f64091 bellard
void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2506 83f64091 bellard
{
2507 6bbff9a0 aliguori
    acb->pool->cancel(acb);
2508 83f64091 bellard
}
2509 83f64091 bellard
2510 ce1a14dc pbrook
2511 83f64091 bellard
/**************************************************************/
2512 83f64091 bellard
/* async block device emulation */
2513 83f64091 bellard
2514 c16b5a2c Christoph Hellwig
typedef struct BlockDriverAIOCBSync {
2515 c16b5a2c Christoph Hellwig
    BlockDriverAIOCB common;
2516 c16b5a2c Christoph Hellwig
    QEMUBH *bh;
2517 c16b5a2c Christoph Hellwig
    int ret;
2518 c16b5a2c Christoph Hellwig
    /* vector translation state */
2519 c16b5a2c Christoph Hellwig
    QEMUIOVector *qiov;
2520 c16b5a2c Christoph Hellwig
    uint8_t *bounce;
2521 c16b5a2c Christoph Hellwig
    int is_write;
2522 c16b5a2c Christoph Hellwig
} BlockDriverAIOCBSync;
2523 c16b5a2c Christoph Hellwig
2524 c16b5a2c Christoph Hellwig
static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2525 c16b5a2c Christoph Hellwig
{
2526 b666d239 Kevin Wolf
    BlockDriverAIOCBSync *acb =
2527 b666d239 Kevin Wolf
        container_of(blockacb, BlockDriverAIOCBSync, common);
2528 6a7ad299 Dor Laor
    qemu_bh_delete(acb->bh);
2529 36afc451 Avi Kivity
    acb->bh = NULL;
2530 c16b5a2c Christoph Hellwig
    qemu_aio_release(acb);
2531 c16b5a2c Christoph Hellwig
}
2532 c16b5a2c Christoph Hellwig
2533 c16b5a2c Christoph Hellwig
static AIOPool bdrv_em_aio_pool = {
2534 c16b5a2c Christoph Hellwig
    .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2535 c16b5a2c Christoph Hellwig
    .cancel             = bdrv_aio_cancel_em,
2536 c16b5a2c Christoph Hellwig
};
2537 c16b5a2c Christoph Hellwig
2538 ce1a14dc pbrook
static void bdrv_aio_bh_cb(void *opaque)
2539 83f64091 bellard
{
2540 ce1a14dc pbrook
    BlockDriverAIOCBSync *acb = opaque;
2541 f141eafe aliguori
2542 f141eafe aliguori
    if (!acb->is_write)
2543 f141eafe aliguori
        qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2544 ceb42de8 aliguori
    qemu_vfree(acb->bounce);
2545 ce1a14dc pbrook
    acb->common.cb(acb->common.opaque, acb->ret);
2546 6a7ad299 Dor Laor
    qemu_bh_delete(acb->bh);
2547 36afc451 Avi Kivity
    acb->bh = NULL;
2548 ce1a14dc pbrook
    qemu_aio_release(acb);
2549 83f64091 bellard
}
2550 beac80cd bellard
2551 f141eafe aliguori
static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2552 f141eafe aliguori
                                            int64_t sector_num,
2553 f141eafe aliguori
                                            QEMUIOVector *qiov,
2554 f141eafe aliguori
                                            int nb_sectors,
2555 f141eafe aliguori
                                            BlockDriverCompletionFunc *cb,
2556 f141eafe aliguori
                                            void *opaque,
2557 f141eafe aliguori
                                            int is_write)
2558 f141eafe aliguori
2559 83f64091 bellard
{
2560 ce1a14dc pbrook
    BlockDriverAIOCBSync *acb;
2561 ce1a14dc pbrook
2562 c16b5a2c Christoph Hellwig
    acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2563 f141eafe aliguori
    acb->is_write = is_write;
2564 f141eafe aliguori
    acb->qiov = qiov;
2565 e268ca52 aliguori
    acb->bounce = qemu_blockalign(bs, qiov->size);
2566 f141eafe aliguori
2567 ce1a14dc pbrook
    if (!acb->bh)
2568 ce1a14dc pbrook
        acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2569 f141eafe aliguori
2570 f141eafe aliguori
    if (is_write) {
2571 f141eafe aliguori
        qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2572 f141eafe aliguori
        acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2573 f141eafe aliguori
    } else {
2574 f141eafe aliguori
        acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2575 f141eafe aliguori
    }
2576 f141eafe aliguori
2577 ce1a14dc pbrook
    qemu_bh_schedule(acb->bh);
2578 f141eafe aliguori
2579 ce1a14dc pbrook
    return &acb->common;
2580 beac80cd bellard
}
2581 beac80cd bellard
2582 f141eafe aliguori
static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2583 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2584 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque)
2585 beac80cd bellard
{
2586 f141eafe aliguori
    return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2587 f141eafe aliguori
}
2588 83f64091 bellard
2589 f141eafe aliguori
static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2590 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2591 f141eafe aliguori
        BlockDriverCompletionFunc *cb, void *opaque)
2592 f141eafe aliguori
{
2593 f141eafe aliguori
    return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2594 beac80cd bellard
}
2595 beac80cd bellard
2596 b2e12bc6 Christoph Hellwig
static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2597 b2e12bc6 Christoph Hellwig
        BlockDriverCompletionFunc *cb, void *opaque)
2598 b2e12bc6 Christoph Hellwig
{
2599 b2e12bc6 Christoph Hellwig
    BlockDriverAIOCBSync *acb;
2600 b2e12bc6 Christoph Hellwig
2601 b2e12bc6 Christoph Hellwig
    acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2602 b2e12bc6 Christoph Hellwig
    acb->is_write = 1; /* don't bounce in the completion hadler */
2603 b2e12bc6 Christoph Hellwig
    acb->qiov = NULL;
2604 b2e12bc6 Christoph Hellwig
    acb->bounce = NULL;
2605 b2e12bc6 Christoph Hellwig
    acb->ret = 0;
2606 b2e12bc6 Christoph Hellwig
2607 b2e12bc6 Christoph Hellwig
    if (!acb->bh)
2608 b2e12bc6 Christoph Hellwig
        acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2609 b2e12bc6 Christoph Hellwig
2610 b2e12bc6 Christoph Hellwig
    bdrv_flush(bs);
2611 b2e12bc6 Christoph Hellwig
    qemu_bh_schedule(acb->bh);
2612 b2e12bc6 Christoph Hellwig
    return &acb->common;
2613 b2e12bc6 Christoph Hellwig
}
2614 b2e12bc6 Christoph Hellwig
2615 016f5cf6 Alexander Graf
static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2616 016f5cf6 Alexander Graf
        BlockDriverCompletionFunc *cb, void *opaque)
2617 016f5cf6 Alexander Graf
{
2618 016f5cf6 Alexander Graf
    BlockDriverAIOCBSync *acb;
2619 016f5cf6 Alexander Graf
2620 016f5cf6 Alexander Graf
    acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2621 016f5cf6 Alexander Graf
    acb->is_write = 1; /* don't bounce in the completion handler */
2622 016f5cf6 Alexander Graf
    acb->qiov = NULL;
2623 016f5cf6 Alexander Graf
    acb->bounce = NULL;
2624 016f5cf6 Alexander Graf
    acb->ret = 0;
2625 016f5cf6 Alexander Graf
2626 016f5cf6 Alexander Graf
    if (!acb->bh) {
2627 016f5cf6 Alexander Graf
        acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2628 016f5cf6 Alexander Graf
    }
2629 016f5cf6 Alexander Graf
2630 016f5cf6 Alexander Graf
    qemu_bh_schedule(acb->bh);
2631 016f5cf6 Alexander Graf
    return &acb->common;
2632 016f5cf6 Alexander Graf
}
2633 016f5cf6 Alexander Graf
2634 83f64091 bellard
/**************************************************************/
2635 83f64091 bellard
/* sync block device emulation */
2636 ea2384d3 bellard
2637 83f64091 bellard
static void bdrv_rw_em_cb(void *opaque, int ret)
2638 83f64091 bellard
{
2639 83f64091 bellard
    *(int *)opaque = ret;
2640 ea2384d3 bellard
}
2641 ea2384d3 bellard
2642 83f64091 bellard
#define NOT_DONE 0x7fffffff
2643 83f64091 bellard
2644 5fafdf24 ths
static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2645 83f64091 bellard
                        uint8_t *buf, int nb_sectors)
2646 7a6cba61 pbrook
{
2647 ce1a14dc pbrook
    int async_ret;
2648 ce1a14dc pbrook
    BlockDriverAIOCB *acb;
2649 f141eafe aliguori
    struct iovec iov;
2650 f141eafe aliguori
    QEMUIOVector qiov;
2651 83f64091 bellard
2652 65d6b3d8 Kevin Wolf
    async_context_push();
2653 65d6b3d8 Kevin Wolf
2654 83f64091 bellard
    async_ret = NOT_DONE;
2655 3f4cb3d3 blueswir1
    iov.iov_base = (void *)buf;
2656 eb5a3165 Jes Sorensen
    iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2657 f141eafe aliguori
    qemu_iovec_init_external(&qiov, &iov, 1);
2658 f141eafe aliguori
    acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2659 f141eafe aliguori
        bdrv_rw_em_cb, &async_ret);
2660 65d6b3d8 Kevin Wolf
    if (acb == NULL) {
2661 65d6b3d8 Kevin Wolf
        async_ret = -1;
2662 65d6b3d8 Kevin Wolf
        goto fail;
2663 65d6b3d8 Kevin Wolf
    }
2664 baf35cb9 aliguori
2665 83f64091 bellard
    while (async_ret == NOT_DONE) {
2666 83f64091 bellard
        qemu_aio_wait();
2667 83f64091 bellard
    }
2668 baf35cb9 aliguori
2669 65d6b3d8 Kevin Wolf
2670 65d6b3d8 Kevin Wolf
fail:
2671 65d6b3d8 Kevin Wolf
    async_context_pop();
2672 83f64091 bellard
    return async_ret;
2673 7a6cba61 pbrook
}
2674 7a6cba61 pbrook
2675 83f64091 bellard
static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2676 83f64091 bellard
                         const uint8_t *buf, int nb_sectors)
2677 83f64091 bellard
{
2678 ce1a14dc pbrook
    int async_ret;
2679 ce1a14dc pbrook
    BlockDriverAIOCB *acb;
2680 f141eafe aliguori
    struct iovec iov;
2681 f141eafe aliguori
    QEMUIOVector qiov;
2682 83f64091 bellard
2683 65d6b3d8 Kevin Wolf
    async_context_push();
2684 65d6b3d8 Kevin Wolf
2685 83f64091 bellard
    async_ret = NOT_DONE;
2686 f141eafe aliguori
    iov.iov_base = (void *)buf;
2687 eb5a3165 Jes Sorensen
    iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2688 f141eafe aliguori
    qemu_iovec_init_external(&qiov, &iov, 1);
2689 f141eafe aliguori
    acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2690 f141eafe aliguori
        bdrv_rw_em_cb, &async_ret);
2691 65d6b3d8 Kevin Wolf
    if (acb == NULL) {
2692 65d6b3d8 Kevin Wolf
        async_ret = -1;
2693 65d6b3d8 Kevin Wolf
        goto fail;
2694 65d6b3d8 Kevin Wolf
    }
2695 83f64091 bellard
    while (async_ret == NOT_DONE) {
2696 83f64091 bellard
        qemu_aio_wait();
2697 83f64091 bellard
    }
2698 65d6b3d8 Kevin Wolf
2699 65d6b3d8 Kevin Wolf
fail:
2700 65d6b3d8 Kevin Wolf
    async_context_pop();
2701 83f64091 bellard
    return async_ret;
2702 83f64091 bellard
}
2703 ea2384d3 bellard
2704 ea2384d3 bellard
void bdrv_init(void)
2705 ea2384d3 bellard
{
2706 5efa9d5a Anthony Liguori
    module_call_init(MODULE_INIT_BLOCK);
2707 ea2384d3 bellard
}
2708 ce1a14dc pbrook
2709 eb852011 Markus Armbruster
void bdrv_init_with_whitelist(void)
2710 eb852011 Markus Armbruster
{
2711 eb852011 Markus Armbruster
    use_bdrv_whitelist = 1;
2712 eb852011 Markus Armbruster
    bdrv_init();
2713 eb852011 Markus Armbruster
}
2714 eb852011 Markus Armbruster
2715 c16b5a2c Christoph Hellwig
void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2716 c16b5a2c Christoph Hellwig
                   BlockDriverCompletionFunc *cb, void *opaque)
2717 ce1a14dc pbrook
{
2718 ce1a14dc pbrook
    BlockDriverAIOCB *acb;
2719 ce1a14dc pbrook
2720 6bbff9a0 aliguori
    if (pool->free_aiocb) {
2721 6bbff9a0 aliguori
        acb = pool->free_aiocb;
2722 6bbff9a0 aliguori
        pool->free_aiocb = acb->next;
2723 ce1a14dc pbrook
    } else {
2724 6bbff9a0 aliguori
        acb = qemu_mallocz(pool->aiocb_size);
2725 6bbff9a0 aliguori
        acb->pool = pool;
2726 ce1a14dc pbrook
    }
2727 ce1a14dc pbrook
    acb->bs = bs;
2728 ce1a14dc pbrook
    acb->cb = cb;
2729 ce1a14dc pbrook
    acb->opaque = opaque;
2730 ce1a14dc pbrook
    return acb;
2731 ce1a14dc pbrook
}
2732 ce1a14dc pbrook
2733 ce1a14dc pbrook
void qemu_aio_release(void *p)
2734 ce1a14dc pbrook
{
2735 6bbff9a0 aliguori
    BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2736 6bbff9a0 aliguori
    AIOPool *pool = acb->pool;
2737 6bbff9a0 aliguori
    acb->next = pool->free_aiocb;
2738 6bbff9a0 aliguori
    pool->free_aiocb = acb;
2739 ce1a14dc pbrook
}
2740 19cb3738 bellard
2741 19cb3738 bellard
/**************************************************************/
2742 19cb3738 bellard
/* removable device support */
2743 19cb3738 bellard
2744 19cb3738 bellard
/**
2745 19cb3738 bellard
 * Return TRUE if the media is present
2746 19cb3738 bellard
 */
2747 19cb3738 bellard
int bdrv_is_inserted(BlockDriverState *bs)
2748 19cb3738 bellard
{
2749 19cb3738 bellard
    BlockDriver *drv = bs->drv;
2750 19cb3738 bellard
    int ret;
2751 19cb3738 bellard
    if (!drv)
2752 19cb3738 bellard
        return 0;
2753 19cb3738 bellard
    if (!drv->bdrv_is_inserted)
2754 4be9762a Markus Armbruster
        return !bs->tray_open;
2755 19cb3738 bellard
    ret = drv->bdrv_is_inserted(bs);
2756 19cb3738 bellard
    return ret;
2757 19cb3738 bellard
}
2758 19cb3738 bellard
2759 19cb3738 bellard
/**
2760 19cb3738 bellard
 * Return TRUE if the media changed since the last call to this
2761 5fafdf24 ths
 * function. It is currently only used for floppy disks
2762 19cb3738 bellard
 */
2763 19cb3738 bellard
int bdrv_media_changed(BlockDriverState *bs)
2764 19cb3738 bellard
{
2765 19cb3738 bellard
    BlockDriver *drv = bs->drv;
2766 19cb3738 bellard
    int ret;
2767 19cb3738 bellard
2768 19cb3738 bellard
    if (!drv || !drv->bdrv_media_changed)
2769 19cb3738 bellard
        ret = -ENOTSUP;
2770 19cb3738 bellard
    else
2771 19cb3738 bellard
        ret = drv->bdrv_media_changed(bs);
2772 19cb3738 bellard
    if (ret == -ENOTSUP)
2773 19cb3738 bellard
        ret = bs->media_changed;
2774 19cb3738 bellard
    bs->media_changed = 0;
2775 19cb3738 bellard
    return ret;
2776 19cb3738 bellard
}
2777 19cb3738 bellard
2778 19cb3738 bellard
/**
2779 19cb3738 bellard
 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2780 19cb3738 bellard
 */
2781 aea2a33c Mark McLoughlin
int bdrv_eject(BlockDriverState *bs, int eject_flag)
2782 19cb3738 bellard
{
2783 19cb3738 bellard
    BlockDriver *drv = bs->drv;
2784 19cb3738 bellard
    int ret;
2785 19cb3738 bellard
2786 aea2a33c Mark McLoughlin
    if (bs->locked) {
2787 aea2a33c Mark McLoughlin
        return -EBUSY;
2788 aea2a33c Mark McLoughlin
    }
2789 aea2a33c Mark McLoughlin
2790 19cb3738 bellard
    if (!drv || !drv->bdrv_eject) {
2791 19cb3738 bellard
        ret = -ENOTSUP;
2792 19cb3738 bellard
    } else {
2793 19cb3738 bellard
        ret = drv->bdrv_eject(bs, eject_flag);
2794 19cb3738 bellard
    }
2795 19cb3738 bellard
    if (ret == -ENOTSUP) {
2796 aea2a33c Mark McLoughlin
        ret = 0;
2797 19cb3738 bellard
    }
2798 4be9762a Markus Armbruster
    if (ret >= 0) {
2799 4be9762a Markus Armbruster
        bs->tray_open = eject_flag;
2800 4be9762a Markus Armbruster
    }
2801 aea2a33c Mark McLoughlin
2802 aea2a33c Mark McLoughlin
    return ret;
2803 19cb3738 bellard
}
2804 19cb3738 bellard
2805 19cb3738 bellard
int bdrv_is_locked(BlockDriverState *bs)
2806 19cb3738 bellard
{
2807 19cb3738 bellard
    return bs->locked;
2808 19cb3738 bellard
}
2809 19cb3738 bellard
2810 19cb3738 bellard
/**
2811 19cb3738 bellard
 * Lock or unlock the media (if it is locked, the user won't be able
2812 19cb3738 bellard
 * to eject it manually).
2813 19cb3738 bellard
 */
2814 19cb3738 bellard
void bdrv_set_locked(BlockDriverState *bs, int locked)
2815 19cb3738 bellard
{
2816 19cb3738 bellard
    BlockDriver *drv = bs->drv;
2817 19cb3738 bellard
2818 b8c6d095 Stefan Hajnoczi
    trace_bdrv_set_locked(bs, locked);
2819 b8c6d095 Stefan Hajnoczi
2820 19cb3738 bellard
    bs->locked = locked;
2821 19cb3738 bellard
    if (drv && drv->bdrv_set_locked) {
2822 19cb3738 bellard
        drv->bdrv_set_locked(bs, locked);
2823 19cb3738 bellard
    }
2824 19cb3738 bellard
}
2825 985a03b0 ths
2826 985a03b0 ths
/* needed for generic scsi interface */
2827 985a03b0 ths
2828 985a03b0 ths
int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2829 985a03b0 ths
{
2830 985a03b0 ths
    BlockDriver *drv = bs->drv;
2831 985a03b0 ths
2832 985a03b0 ths
    if (drv && drv->bdrv_ioctl)
2833 985a03b0 ths
        return drv->bdrv_ioctl(bs, req, buf);
2834 985a03b0 ths
    return -ENOTSUP;
2835 985a03b0 ths
}
2836 7d780669 aliguori
2837 221f715d aliguori
BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2838 221f715d aliguori
        unsigned long int req, void *buf,
2839 221f715d aliguori
        BlockDriverCompletionFunc *cb, void *opaque)
2840 7d780669 aliguori
{
2841 221f715d aliguori
    BlockDriver *drv = bs->drv;
2842 7d780669 aliguori
2843 221f715d aliguori
    if (drv && drv->bdrv_aio_ioctl)
2844 221f715d aliguori
        return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2845 221f715d aliguori
    return NULL;
2846 7d780669 aliguori
}
2847 e268ca52 aliguori
2848 7cd1e32a lirans@il.ibm.com
2849 7cd1e32a lirans@il.ibm.com
2850 e268ca52 aliguori
void *qemu_blockalign(BlockDriverState *bs, size_t size)
2851 e268ca52 aliguori
{
2852 e268ca52 aliguori
    return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2853 e268ca52 aliguori
}
2854 7cd1e32a lirans@il.ibm.com
2855 7cd1e32a lirans@il.ibm.com
void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2856 7cd1e32a lirans@il.ibm.com
{
2857 7cd1e32a lirans@il.ibm.com
    int64_t bitmap_size;
2858 a55eb92c Jan Kiszka
2859 aaa0eb75 Liran Schour
    bs->dirty_count = 0;
2860 a55eb92c Jan Kiszka
    if (enable) {
2861 c6d22830 Jan Kiszka
        if (!bs->dirty_bitmap) {
2862 c6d22830 Jan Kiszka
            bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2863 c6d22830 Jan Kiszka
                    BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2864 c6d22830 Jan Kiszka
            bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2865 a55eb92c Jan Kiszka
2866 7cd1e32a lirans@il.ibm.com
            bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2867 a55eb92c Jan Kiszka
        }
2868 7cd1e32a lirans@il.ibm.com
    } else {
2869 c6d22830 Jan Kiszka
        if (bs->dirty_bitmap) {
2870 7cd1e32a lirans@il.ibm.com
            qemu_free(bs->dirty_bitmap);
2871 c6d22830 Jan Kiszka
            bs->dirty_bitmap = NULL;
2872 a55eb92c Jan Kiszka
        }
2873 7cd1e32a lirans@il.ibm.com
    }
2874 7cd1e32a lirans@il.ibm.com
}
2875 7cd1e32a lirans@il.ibm.com
2876 7cd1e32a lirans@il.ibm.com
int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2877 7cd1e32a lirans@il.ibm.com
{
2878 6ea44308 Jan Kiszka
    int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2879 a55eb92c Jan Kiszka
2880 c6d22830 Jan Kiszka
    if (bs->dirty_bitmap &&
2881 c6d22830 Jan Kiszka
        (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2882 6d59fec1 Marcelo Tosatti
        return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2883 6d59fec1 Marcelo Tosatti
            (1UL << (chunk % (sizeof(unsigned long) * 8))));
2884 7cd1e32a lirans@il.ibm.com
    } else {
2885 7cd1e32a lirans@il.ibm.com
        return 0;
2886 7cd1e32a lirans@il.ibm.com
    }
2887 7cd1e32a lirans@il.ibm.com
}
2888 7cd1e32a lirans@il.ibm.com
2889 a55eb92c Jan Kiszka
void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2890 a55eb92c Jan Kiszka
                      int nr_sectors)
2891 7cd1e32a lirans@il.ibm.com
{
2892 7cd1e32a lirans@il.ibm.com
    set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2893 7cd1e32a lirans@il.ibm.com
}
2894 aaa0eb75 Liran Schour
2895 aaa0eb75 Liran Schour
int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2896 aaa0eb75 Liran Schour
{
2897 aaa0eb75 Liran Schour
    return bs->dirty_count;
2898 aaa0eb75 Liran Schour
}
2899 f88e1a42 Jes Sorensen
2900 db593f25 Marcelo Tosatti
void bdrv_set_in_use(BlockDriverState *bs, int in_use)
2901 db593f25 Marcelo Tosatti
{
2902 db593f25 Marcelo Tosatti
    assert(bs->in_use != in_use);
2903 db593f25 Marcelo Tosatti
    bs->in_use = in_use;
2904 db593f25 Marcelo Tosatti
}
2905 db593f25 Marcelo Tosatti
2906 db593f25 Marcelo Tosatti
int bdrv_in_use(BlockDriverState *bs)
2907 db593f25 Marcelo Tosatti
{
2908 db593f25 Marcelo Tosatti
    return bs->in_use;
2909 db593f25 Marcelo Tosatti
}
2910 db593f25 Marcelo Tosatti
2911 f88e1a42 Jes Sorensen
int bdrv_img_create(const char *filename, const char *fmt,
2912 f88e1a42 Jes Sorensen
                    const char *base_filename, const char *base_fmt,
2913 f88e1a42 Jes Sorensen
                    char *options, uint64_t img_size, int flags)
2914 f88e1a42 Jes Sorensen
{
2915 f88e1a42 Jes Sorensen
    QEMUOptionParameter *param = NULL, *create_options = NULL;
2916 792da93a Jes Sorensen
    QEMUOptionParameter *backing_fmt, *backing_file;
2917 f88e1a42 Jes Sorensen
    BlockDriverState *bs = NULL;
2918 f88e1a42 Jes Sorensen
    BlockDriver *drv, *proto_drv;
2919 96df67d1 Stefan Hajnoczi
    BlockDriver *backing_drv = NULL;
2920 f88e1a42 Jes Sorensen
    int ret = 0;
2921 f88e1a42 Jes Sorensen
2922 f88e1a42 Jes Sorensen
    /* Find driver and parse its options */
2923 f88e1a42 Jes Sorensen
    drv = bdrv_find_format(fmt);
2924 f88e1a42 Jes Sorensen
    if (!drv) {
2925 f88e1a42 Jes Sorensen
        error_report("Unknown file format '%s'", fmt);
2926 4f70f249 Jes Sorensen
        ret = -EINVAL;
2927 f88e1a42 Jes Sorensen
        goto out;
2928 f88e1a42 Jes Sorensen
    }
2929 f88e1a42 Jes Sorensen
2930 f88e1a42 Jes Sorensen
    proto_drv = bdrv_find_protocol(filename);
2931 f88e1a42 Jes Sorensen
    if (!proto_drv) {
2932 f88e1a42 Jes Sorensen
        error_report("Unknown protocol '%s'", filename);
2933 4f70f249 Jes Sorensen
        ret = -EINVAL;
2934 f88e1a42 Jes Sorensen
        goto out;
2935 f88e1a42 Jes Sorensen
    }
2936 f88e1a42 Jes Sorensen
2937 f88e1a42 Jes Sorensen
    create_options = append_option_parameters(create_options,
2938 f88e1a42 Jes Sorensen
                                              drv->create_options);
2939 f88e1a42 Jes Sorensen
    create_options = append_option_parameters(create_options,
2940 f88e1a42 Jes Sorensen
                                              proto_drv->create_options);
2941 f88e1a42 Jes Sorensen
2942 f88e1a42 Jes Sorensen
    /* Create parameter list with default values */
2943 f88e1a42 Jes Sorensen
    param = parse_option_parameters("", create_options, param);
2944 f88e1a42 Jes Sorensen
2945 f88e1a42 Jes Sorensen
    set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
2946 f88e1a42 Jes Sorensen
2947 f88e1a42 Jes Sorensen
    /* Parse -o options */
2948 f88e1a42 Jes Sorensen
    if (options) {
2949 f88e1a42 Jes Sorensen
        param = parse_option_parameters(options, create_options, param);
2950 f88e1a42 Jes Sorensen
        if (param == NULL) {
2951 f88e1a42 Jes Sorensen
            error_report("Invalid options for file format '%s'.", fmt);
2952 4f70f249 Jes Sorensen
            ret = -EINVAL;
2953 f88e1a42 Jes Sorensen
            goto out;
2954 f88e1a42 Jes Sorensen
        }
2955 f88e1a42 Jes Sorensen
    }
2956 f88e1a42 Jes Sorensen
2957 f88e1a42 Jes Sorensen
    if (base_filename) {
2958 f88e1a42 Jes Sorensen
        if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
2959 f88e1a42 Jes Sorensen
                                 base_filename)) {
2960 f88e1a42 Jes Sorensen
            error_report("Backing file not supported for file format '%s'",
2961 f88e1a42 Jes Sorensen
                         fmt);
2962 4f70f249 Jes Sorensen
            ret = -EINVAL;
2963 f88e1a42 Jes Sorensen
            goto out;
2964 f88e1a42 Jes Sorensen
        }
2965 f88e1a42 Jes Sorensen
    }
2966 f88e1a42 Jes Sorensen
2967 f88e1a42 Jes Sorensen
    if (base_fmt) {
2968 f88e1a42 Jes Sorensen
        if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
2969 f88e1a42 Jes Sorensen
            error_report("Backing file format not supported for file "
2970 f88e1a42 Jes Sorensen
                         "format '%s'", fmt);
2971 4f70f249 Jes Sorensen
            ret = -EINVAL;
2972 f88e1a42 Jes Sorensen
            goto out;
2973 f88e1a42 Jes Sorensen
        }
2974 f88e1a42 Jes Sorensen
    }
2975 f88e1a42 Jes Sorensen
2976 792da93a Jes Sorensen
    backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
2977 792da93a Jes Sorensen
    if (backing_file && backing_file->value.s) {
2978 792da93a Jes Sorensen
        if (!strcmp(filename, backing_file->value.s)) {
2979 792da93a Jes Sorensen
            error_report("Error: Trying to create an image with the "
2980 792da93a Jes Sorensen
                         "same filename as the backing file");
2981 4f70f249 Jes Sorensen
            ret = -EINVAL;
2982 792da93a Jes Sorensen
            goto out;
2983 792da93a Jes Sorensen
        }
2984 792da93a Jes Sorensen
    }
2985 792da93a Jes Sorensen
2986 f88e1a42 Jes Sorensen
    backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
2987 f88e1a42 Jes Sorensen
    if (backing_fmt && backing_fmt->value.s) {
2988 96df67d1 Stefan Hajnoczi
        backing_drv = bdrv_find_format(backing_fmt->value.s);
2989 96df67d1 Stefan Hajnoczi
        if (!backing_drv) {
2990 f88e1a42 Jes Sorensen
            error_report("Unknown backing file format '%s'",
2991 f88e1a42 Jes Sorensen
                         backing_fmt->value.s);
2992 4f70f249 Jes Sorensen
            ret = -EINVAL;
2993 f88e1a42 Jes Sorensen
            goto out;
2994 f88e1a42 Jes Sorensen
        }
2995 f88e1a42 Jes Sorensen
    }
2996 f88e1a42 Jes Sorensen
2997 f88e1a42 Jes Sorensen
    // The size for the image must always be specified, with one exception:
2998 f88e1a42 Jes Sorensen
    // If we are using a backing file, we can obtain the size from there
2999 f88e1a42 Jes Sorensen
    if (get_option_parameter(param, BLOCK_OPT_SIZE)->value.n == -1) {
3000 f88e1a42 Jes Sorensen
        if (backing_file && backing_file->value.s) {
3001 f88e1a42 Jes Sorensen
            uint64_t size;
3002 f88e1a42 Jes Sorensen
            char buf[32];
3003 f88e1a42 Jes Sorensen
3004 f88e1a42 Jes Sorensen
            bs = bdrv_new("");
3005 f88e1a42 Jes Sorensen
3006 96df67d1 Stefan Hajnoczi
            ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
3007 f88e1a42 Jes Sorensen
            if (ret < 0) {
3008 96df67d1 Stefan Hajnoczi
                error_report("Could not open '%s'", backing_file->value.s);
3009 f88e1a42 Jes Sorensen
                goto out;
3010 f88e1a42 Jes Sorensen
            }
3011 f88e1a42 Jes Sorensen
            bdrv_get_geometry(bs, &size);
3012 f88e1a42 Jes Sorensen
            size *= 512;
3013 f88e1a42 Jes Sorensen
3014 f88e1a42 Jes Sorensen
            snprintf(buf, sizeof(buf), "%" PRId64, size);
3015 f88e1a42 Jes Sorensen
            set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3016 f88e1a42 Jes Sorensen
        } else {
3017 f88e1a42 Jes Sorensen
            error_report("Image creation needs a size parameter");
3018 4f70f249 Jes Sorensen
            ret = -EINVAL;
3019 f88e1a42 Jes Sorensen
            goto out;
3020 f88e1a42 Jes Sorensen
        }
3021 f88e1a42 Jes Sorensen
    }
3022 f88e1a42 Jes Sorensen
3023 f88e1a42 Jes Sorensen
    printf("Formatting '%s', fmt=%s ", filename, fmt);
3024 f88e1a42 Jes Sorensen
    print_option_parameters(param);
3025 f88e1a42 Jes Sorensen
    puts("");
3026 f88e1a42 Jes Sorensen
3027 f88e1a42 Jes Sorensen
    ret = bdrv_create(drv, filename, param);
3028 f88e1a42 Jes Sorensen
3029 f88e1a42 Jes Sorensen
    if (ret < 0) {
3030 f88e1a42 Jes Sorensen
        if (ret == -ENOTSUP) {
3031 f88e1a42 Jes Sorensen
            error_report("Formatting or formatting option not supported for "
3032 f88e1a42 Jes Sorensen
                         "file format '%s'", fmt);
3033 f88e1a42 Jes Sorensen
        } else if (ret == -EFBIG) {
3034 f88e1a42 Jes Sorensen
            error_report("The image size is too large for file format '%s'",
3035 f88e1a42 Jes Sorensen
                         fmt);
3036 f88e1a42 Jes Sorensen
        } else {
3037 f88e1a42 Jes Sorensen
            error_report("%s: error while creating %s: %s", filename, fmt,
3038 f88e1a42 Jes Sorensen
                         strerror(-ret));
3039 f88e1a42 Jes Sorensen
        }
3040 f88e1a42 Jes Sorensen
    }
3041 f88e1a42 Jes Sorensen
3042 f88e1a42 Jes Sorensen
out:
3043 f88e1a42 Jes Sorensen
    free_option_parameters(create_options);
3044 f88e1a42 Jes Sorensen
    free_option_parameters(param);
3045 f88e1a42 Jes Sorensen
3046 f88e1a42 Jes Sorensen
    if (bs) {
3047 f88e1a42 Jes Sorensen
        bdrv_delete(bs);
3048 f88e1a42 Jes Sorensen
    }
3049 4f70f249 Jes Sorensen
3050 4f70f249 Jes Sorensen
    return ret;
3051 f88e1a42 Jes Sorensen
}