blob: d8193a37d030ee3dd918b2e5f061797eb0c8f05a [file] [log] [blame]
bellardfc01f7e2003-06-30 10:03:06 +00001/*
2 * QEMU System Emulator block driver
ths5fafdf22007-09-16 21:08:06 +00003 *
bellardfc01f7e2003-06-30 10:03:06 +00004 * Copyright (c) 2003 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardfc01f7e2003-06-30 10:03:06 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
blueswir13990d092008-12-05 17:53:21 +000024#include "config-host.h"
pbrookfaf07962007-11-11 02:51:17 +000025#include "qemu-common.h"
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +010026#include "trace.h"
aliguori376253e2009-03-05 23:01:23 +000027#include "monitor.h"
bellardea2384d2004-08-01 21:59:26 +000028#include "block_int.h"
Anthony Liguori5efa9d52009-05-09 17:03:42 -050029#include "module.h"
Luiz Capitulinod15e5462009-12-10 17:16:06 -020030#include "qemu-objects.h"
Kevin Wolf68485422011-06-30 10:05:46 +020031#include "qemu-coroutine.h"
bellardfc01f7e2003-06-30 10:03:06 +000032
Juan Quintela71e72a12009-07-27 16:12:56 +020033#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000034#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000037#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000038#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000039#include <sys/disk.h>
40#endif
blueswir1c5e97232009-03-07 20:06:23 +000041#endif
bellard7674e7b2005-04-26 21:59:26 +000042
aliguori49dc7682009-03-08 16:26:59 +000043#ifdef _WIN32
44#include <windows.h>
45#endif
46
Markus Armbruster145feb12011-08-03 15:07:42 +020047static void bdrv_dev_change_media_cb(BlockDriverState *bs);
aliguorif141eaf2009-04-07 18:43:24 +000048static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
aliguoric87c0672009-04-07 18:43:20 +000050 BlockDriverCompletionFunc *cb, void *opaque);
aliguorif141eaf2009-04-07 18:43:24 +000051static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +000053 BlockDriverCompletionFunc *cb, void *opaque);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +020054static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55 BlockDriverCompletionFunc *cb, void *opaque);
Alexander Graf016f5cf2010-05-26 17:51:49 +020056static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57 BlockDriverCompletionFunc *cb, void *opaque);
ths5fafdf22007-09-16 21:08:06 +000058static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +000059 uint8_t *buf, int nb_sectors);
60static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61 const uint8_t *buf, int nb_sectors);
Kevin Wolf68485422011-06-30 10:05:46 +020062static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64 BlockDriverCompletionFunc *cb, void *opaque);
65static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67 BlockDriverCompletionFunc *cb, void *opaque);
Kevin Wolff9f05dc2011-07-15 13:50:26 +020068static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69 int64_t sector_num, int nb_sectors,
70 QEMUIOVector *iov);
71static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72 int64_t sector_num, int nb_sectors,
73 QEMUIOVector *iov);
Kevin Wolfe7a8a782011-07-15 16:05:00 +020074static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
bellardec530c82006-04-25 22:36:06 +000075
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +010076static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(bdrv_states);
blueswir17ee930d2008-09-17 19:04:14 +000078
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010079static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000081
Markus Armbrusterf9092b12010-06-25 10:33:39 +020082/* The device to use for VM snapshots */
83static BlockDriverState *bs_snapshots;
84
Markus Armbrustereb852012009-10-27 18:41:44 +010085/* If non-zero, use only whitelisted block drivers */
86static int use_bdrv_whitelist;
87
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000088#ifdef _WIN32
89static int is_windows_drive_prefix(const char *filename)
90{
91 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
93 filename[1] == ':');
94}
95
96int is_windows_drive(const char *filename)
97{
98 if (is_windows_drive_prefix(filename) &&
99 filename[2] == '\0')
100 return 1;
101 if (strstart(filename, "\\\\.\\", NULL) ||
102 strstart(filename, "//./", NULL))
103 return 1;
104 return 0;
105}
106#endif
107
108/* check if the path starts with "<protocol>:" */
109static int path_has_protocol(const char *path)
110{
111#ifdef _WIN32
112 if (is_windows_drive(path) ||
113 is_windows_drive_prefix(path)) {
114 return 0;
115 }
116#endif
117
118 return strchr(path, ':') != NULL;
119}
120
bellard83f64092006-08-01 16:21:11 +0000121int path_is_absolute(const char *path)
122{
123 const char *p;
bellard21664422007-01-07 18:22:37 +0000124#ifdef _WIN32
125 /* specific case for names like: "\\.\d:" */
126 if (*path == '/' || *path == '\\')
127 return 1;
128#endif
bellard83f64092006-08-01 16:21:11 +0000129 p = strchr(path, ':');
130 if (p)
131 p++;
132 else
133 p = path;
bellard3b9f94e2007-01-07 17:27:07 +0000134#ifdef _WIN32
135 return (*p == '/' || *p == '\\');
136#else
137 return (*p == '/');
138#endif
bellard83f64092006-08-01 16:21:11 +0000139}
140
141/* if filename is absolute, just copy it to dest. Otherwise, build a
142 path to it by considering it is relative to base_path. URL are
143 supported. */
144void path_combine(char *dest, int dest_size,
145 const char *base_path,
146 const char *filename)
147{
148 const char *p, *p1;
149 int len;
150
151 if (dest_size <= 0)
152 return;
153 if (path_is_absolute(filename)) {
154 pstrcpy(dest, dest_size, filename);
155 } else {
156 p = strchr(base_path, ':');
157 if (p)
158 p++;
159 else
160 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000161 p1 = strrchr(base_path, '/');
162#ifdef _WIN32
163 {
164 const char *p2;
165 p2 = strrchr(base_path, '\\');
166 if (!p1 || p2 > p1)
167 p1 = p2;
168 }
169#endif
bellard83f64092006-08-01 16:21:11 +0000170 if (p1)
171 p1++;
172 else
173 p1 = base_path;
174 if (p1 > p)
175 p = p1;
176 len = p - base_path;
177 if (len > dest_size - 1)
178 len = dest_size - 1;
179 memcpy(dest, base_path, len);
180 dest[len] = '\0';
181 pstrcat(dest, dest_size, filename);
182 }
183}
184
Anthony Liguori5efa9d52009-05-09 17:03:42 -0500185void bdrv_register(BlockDriver *bdrv)
bellardea2384d2004-08-01 21:59:26 +0000186{
Kevin Wolf68485422011-06-30 10:05:46 +0200187 if (bdrv->bdrv_co_readv) {
188 /* Emulate AIO by coroutines, and sync by AIO */
189 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
190 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
191 bdrv->bdrv_read = bdrv_read_em;
192 bdrv->bdrv_write = bdrv_write_em;
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200193 } else {
194 bdrv->bdrv_co_readv = bdrv_co_readv_em;
195 bdrv->bdrv_co_writev = bdrv_co_writev_em;
196
197 if (!bdrv->bdrv_aio_readv) {
198 /* add AIO emulation layer */
199 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
200 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
201 } else if (!bdrv->bdrv_read) {
202 /* add synchronous IO emulation layer */
203 bdrv->bdrv_read = bdrv_read_em;
204 bdrv->bdrv_write = bdrv_write_em;
205 }
bellard83f64092006-08-01 16:21:11 +0000206 }
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +0200207
208 if (!bdrv->bdrv_aio_flush)
209 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
210
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100211 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000212}
bellardb3380822004-03-14 21:38:54 +0000213
214/* create a new block device (by default it is empty) */
215BlockDriverState *bdrv_new(const char *device_name)
bellardfc01f7e2003-06-30 10:03:06 +0000216{
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100217 BlockDriverState *bs;
bellardb3380822004-03-14 21:38:54 +0000218
Anthony Liguori7267c092011-08-20 22:09:37 -0500219 bs = g_malloc0(sizeof(BlockDriverState));
bellardb3380822004-03-14 21:38:54 +0000220 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellardea2384d2004-08-01 21:59:26 +0000221 if (device_name[0] != '\0') {
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100222 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellardea2384d2004-08-01 21:59:26 +0000223 }
bellardb3380822004-03-14 21:38:54 +0000224 return bs;
225}
226
bellardea2384d2004-08-01 21:59:26 +0000227BlockDriver *bdrv_find_format(const char *format_name)
228{
229 BlockDriver *drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100230 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
231 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000232 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100233 }
bellardea2384d2004-08-01 21:59:26 +0000234 }
235 return NULL;
236}
237
Markus Armbrustereb852012009-10-27 18:41:44 +0100238static int bdrv_is_whitelisted(BlockDriver *drv)
239{
240 static const char *whitelist[] = {
241 CONFIG_BDRV_WHITELIST
242 };
243 const char **p;
244
245 if (!whitelist[0])
246 return 1; /* no whitelist, anything goes */
247
248 for (p = whitelist; *p; p++) {
249 if (!strcmp(drv->format_name, *p)) {
250 return 1;
251 }
252 }
253 return 0;
254}
255
256BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
257{
258 BlockDriver *drv = bdrv_find_format(format_name);
259 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
260}
261
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200262int bdrv_create(BlockDriver *drv, const char* filename,
263 QEMUOptionParameter *options)
bellardea2384d2004-08-01 21:59:26 +0000264{
265 if (!drv->bdrv_create)
266 return -ENOTSUP;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200267
268 return drv->bdrv_create(filename, options);
bellardea2384d2004-08-01 21:59:26 +0000269}
270
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200271int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
272{
273 BlockDriver *drv;
274
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900275 drv = bdrv_find_protocol(filename);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200276 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000277 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200278 }
279
280 return bdrv_create(drv, filename, options);
281}
282
bellardd5249392004-08-03 21:14:23 +0000283#ifdef _WIN32
bellard95389c82005-12-18 18:28:15 +0000284void get_tmp_filename(char *filename, int size)
bellardd5249392004-08-03 21:14:23 +0000285{
bellard3b9f94e2007-01-07 17:27:07 +0000286 char temp_dir[MAX_PATH];
ths3b46e622007-09-17 08:09:54 +0000287
bellard3b9f94e2007-01-07 17:27:07 +0000288 GetTempPath(MAX_PATH, temp_dir);
289 GetTempFileName(temp_dir, "qem", 0, filename);
bellardd5249392004-08-03 21:14:23 +0000290}
291#else
bellard95389c82005-12-18 18:28:15 +0000292void get_tmp_filename(char *filename, int size)
bellardea2384d2004-08-01 21:59:26 +0000293{
294 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000295 const char *tmpdir;
bellardd5249392004-08-03 21:14:23 +0000296 /* XXX: race condition possible */
aurel320badc1e2008-03-10 00:05:34 +0000297 tmpdir = getenv("TMPDIR");
298 if (!tmpdir)
299 tmpdir = "/tmp";
300 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
bellardea2384d2004-08-01 21:59:26 +0000301 fd = mkstemp(filename);
302 close(fd);
303}
bellardd5249392004-08-03 21:14:23 +0000304#endif
bellardea2384d2004-08-01 21:59:26 +0000305
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200306/*
307 * Detect host devices. By convention, /dev/cdrom[N] is always
308 * recognized as a host CDROM.
309 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200310static BlockDriver *find_hdev_driver(const char *filename)
311{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200312 int score_max = 0, score;
313 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200314
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100315 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200316 if (d->bdrv_probe_device) {
317 score = d->bdrv_probe_device(filename);
318 if (score > score_max) {
319 score_max = score;
320 drv = d;
321 }
322 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200323 }
324
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200325 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200326}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200327
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900328BlockDriver *bdrv_find_protocol(const char *filename)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200329{
330 BlockDriver *drv1;
331 char protocol[128];
332 int len;
333 const char *p;
334
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200335 /* TODO Drivers without bdrv_file_open must be specified explicitly */
336
Christoph Hellwig39508e72010-06-23 12:25:17 +0200337 /*
338 * XXX(hch): we really should not let host device detection
339 * override an explicit protocol specification, but moving this
340 * later breaks access to device names with colons in them.
341 * Thanks to the brain-dead persistent naming schemes on udev-
342 * based Linux systems those actually are quite common.
343 */
344 drv1 = find_hdev_driver(filename);
345 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200346 return drv1;
347 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200348
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000349 if (!path_has_protocol(filename)) {
Christoph Hellwig39508e72010-06-23 12:25:17 +0200350 return bdrv_find_format("file");
351 }
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000352 p = strchr(filename, ':');
353 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200354 len = p - filename;
355 if (len > sizeof(protocol) - 1)
356 len = sizeof(protocol) - 1;
357 memcpy(protocol, filename, len);
358 protocol[len] = '\0';
359 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
360 if (drv1->protocol_name &&
361 !strcmp(drv1->protocol_name, protocol)) {
362 return drv1;
363 }
364 }
365 return NULL;
366}
367
Stefan Weilc98ac352010-07-21 21:51:51 +0200368static int find_image_format(const char *filename, BlockDriver **pdrv)
bellardea2384d2004-08-01 21:59:26 +0000369{
bellard83f64092006-08-01 16:21:11 +0000370 int ret, score, score_max;
bellardea2384d2004-08-01 21:59:26 +0000371 BlockDriver *drv1, *drv;
bellard83f64092006-08-01 16:21:11 +0000372 uint8_t buf[2048];
373 BlockDriverState *bs;
ths3b46e622007-09-17 08:09:54 +0000374
Naphtali Spreif5edb012010-01-17 16:48:13 +0200375 ret = bdrv_file_open(&bs, filename, 0);
Stefan Weilc98ac352010-07-21 21:51:51 +0200376 if (ret < 0) {
377 *pdrv = NULL;
378 return ret;
379 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700380
Kevin Wolf08a00552010-06-01 18:37:31 +0200381 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382 if (bs->sg || !bdrv_is_inserted(bs)) {
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700383 bdrv_delete(bs);
Stefan Weilc98ac352010-07-21 21:51:51 +0200384 drv = bdrv_find_format("raw");
385 if (!drv) {
386 ret = -ENOENT;
387 }
388 *pdrv = drv;
389 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700390 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700391
bellard83f64092006-08-01 16:21:11 +0000392 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
393 bdrv_delete(bs);
394 if (ret < 0) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200395 *pdrv = NULL;
396 return ret;
bellard83f64092006-08-01 16:21:11 +0000397 }
398
bellardea2384d2004-08-01 21:59:26 +0000399 score_max = 0;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200400 drv = NULL;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100401 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard83f64092006-08-01 16:21:11 +0000402 if (drv1->bdrv_probe) {
403 score = drv1->bdrv_probe(buf, ret, filename);
404 if (score > score_max) {
405 score_max = score;
406 drv = drv1;
407 }
bellardea2384d2004-08-01 21:59:26 +0000408 }
409 }
Stefan Weilc98ac352010-07-21 21:51:51 +0200410 if (!drv) {
411 ret = -ENOENT;
412 }
413 *pdrv = drv;
414 return ret;
bellardea2384d2004-08-01 21:59:26 +0000415}
416
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100417/**
418 * Set the current 'total_sectors' value
419 */
420static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
421{
422 BlockDriver *drv = bs->drv;
423
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700424 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
425 if (bs->sg)
426 return 0;
427
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100428 /* query actual device if possible, otherwise just trust the hint */
429 if (drv->bdrv_getlength) {
430 int64_t length = drv->bdrv_getlength(bs);
431 if (length < 0) {
432 return length;
433 }
434 hint = length >> BDRV_SECTOR_BITS;
435 }
436
437 bs->total_sectors = hint;
438 return 0;
439}
440
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100441/**
442 * Set open flags for a given cache mode
443 *
444 * Return 0 on success, -1 if the cache mode was invalid.
445 */
446int bdrv_parse_cache_flags(const char *mode, int *flags)
447{
448 *flags &= ~BDRV_O_CACHE_MASK;
449
450 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
451 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100452 } else if (!strcmp(mode, "directsync")) {
453 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100454 } else if (!strcmp(mode, "writeback")) {
455 *flags |= BDRV_O_CACHE_WB;
456 } else if (!strcmp(mode, "unsafe")) {
457 *flags |= BDRV_O_CACHE_WB;
458 *flags |= BDRV_O_NO_FLUSH;
459 } else if (!strcmp(mode, "writethrough")) {
460 /* this is the default */
461 } else {
462 return -1;
463 }
464
465 return 0;
466}
467
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200468/*
Kevin Wolf57915332010-04-14 15:24:50 +0200469 * Common part for opening disk images and files
470 */
471static int bdrv_open_common(BlockDriverState *bs, const char *filename,
472 int flags, BlockDriver *drv)
473{
474 int ret, open_flags;
475
476 assert(drv != NULL);
477
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200478 bs->file = NULL;
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100479 bs->total_sectors = 0;
Kevin Wolf57915332010-04-14 15:24:50 +0200480 bs->encrypted = 0;
481 bs->valid_key = 0;
482 bs->open_flags = flags;
483 /* buffer_alignment defaulted to 512, drivers can change this value */
484 bs->buffer_alignment = 512;
485
486 pstrcpy(bs->filename, sizeof(bs->filename), filename);
487
488 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
489 return -ENOTSUP;
490 }
491
492 bs->drv = drv;
Anthony Liguori7267c092011-08-20 22:09:37 -0500493 bs->opaque = g_malloc0(drv->instance_size);
Kevin Wolf57915332010-04-14 15:24:50 +0200494
Christoph Hellwiga6599792011-05-17 18:04:06 +0200495 if (flags & BDRV_O_CACHE_WB)
Kevin Wolf57915332010-04-14 15:24:50 +0200496 bs->enable_write_cache = 1;
497
498 /*
499 * Clear flags that are internal to the block layer before opening the
500 * image.
501 */
502 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
503
504 /*
Stefan Weilebabb672011-04-26 10:29:36 +0200505 * Snapshots should be writable.
Kevin Wolf57915332010-04-14 15:24:50 +0200506 */
507 if (bs->is_temporary) {
508 open_flags |= BDRV_O_RDWR;
509 }
510
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200511 /* Open the image, either directly or using a protocol */
512 if (drv->bdrv_file_open) {
513 ret = drv->bdrv_file_open(bs, filename, open_flags);
514 } else {
515 ret = bdrv_file_open(&bs->file, filename, open_flags);
516 if (ret >= 0) {
517 ret = drv->bdrv_open(bs, open_flags);
518 }
519 }
520
Kevin Wolf57915332010-04-14 15:24:50 +0200521 if (ret < 0) {
522 goto free_and_fail;
523 }
524
525 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100526
527 ret = refresh_total_sectors(bs, bs->total_sectors);
528 if (ret < 0) {
529 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200530 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100531
Kevin Wolf57915332010-04-14 15:24:50 +0200532#ifndef _WIN32
533 if (bs->is_temporary) {
534 unlink(filename);
535 }
536#endif
537 return 0;
538
539free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200540 if (bs->file) {
541 bdrv_delete(bs->file);
542 bs->file = NULL;
543 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500544 g_free(bs->opaque);
Kevin Wolf57915332010-04-14 15:24:50 +0200545 bs->opaque = NULL;
546 bs->drv = NULL;
547 return ret;
548}
549
550/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200551 * Opens a file using a protocol (file, host_device, nbd, ...)
552 */
bellard83f64092006-08-01 16:21:11 +0000553int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000554{
bellard83f64092006-08-01 16:21:11 +0000555 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200556 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000557 int ret;
558
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900559 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200560 if (!drv) {
561 return -ENOENT;
562 }
563
bellard83f64092006-08-01 16:21:11 +0000564 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200565 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000566 if (ret < 0) {
567 bdrv_delete(bs);
568 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000569 }
aliguori71d07702009-03-03 17:37:16 +0000570 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000571 *pbs = bs;
572 return 0;
bellardea2384d2004-08-01 21:59:26 +0000573}
bellardfc01f7e2003-06-30 10:03:06 +0000574
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200575/*
576 * Opens a disk image (raw, qcow2, vmdk, ...)
577 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200578int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
579 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000580{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200581 int ret;
bellard712e7872005-04-28 21:09:32 +0000582
bellard83f64092006-08-01 16:21:11 +0000583 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000584 BlockDriverState *bs1;
585 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000586 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200587 BlockDriver *bdrv_qcow2;
588 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200589 char tmp_filename[PATH_MAX];
590 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000591
bellardea2384d2004-08-01 21:59:26 +0000592 /* if snapshot, we create a temporary backing file and open it
593 instead of opening 'filename' directly */
594
595 /* if there is a backing file, use it */
596 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200597 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000598 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000599 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000600 return ret;
bellardea2384d2004-08-01 21:59:26 +0000601 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200602 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000603
604 if (bs1->drv && bs1->drv->protocol_name)
605 is_protocol = 1;
606
bellardea2384d2004-08-01 21:59:26 +0000607 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000608
bellardea2384d2004-08-01 21:59:26 +0000609 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
aliguori7c96d462008-09-12 17:54:13 +0000610
611 /* Real path is meaningless for protocols */
612 if (is_protocol)
613 snprintf(backing_filename, sizeof(backing_filename),
614 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000615 else if (!realpath(filename, backing_filename))
616 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000617
Kevin Wolf91a073a2009-05-27 14:48:06 +0200618 bdrv_qcow2 = bdrv_find_format("qcow2");
619 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
620
Jes Sorensen3e829902010-05-27 16:20:30 +0200621 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200622 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
623 if (drv) {
624 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
625 drv->format_name);
626 }
627
628 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200629 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000630 if (ret < 0) {
631 return ret;
bellardea2384d2004-08-01 21:59:26 +0000632 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200633
bellardea2384d2004-08-01 21:59:26 +0000634 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200635 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000636 bs->is_temporary = 1;
637 }
bellard712e7872005-04-28 21:09:32 +0000638
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200639 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200640 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200641 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000642 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100643
aliguori51d7c002009-03-05 23:00:29 +0000644 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000645 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000646 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200647
648 /* Open the image */
649 ret = bdrv_open_common(bs, filename, flags, drv);
650 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100651 goto unlink_and_fail;
652 }
653
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200654 /* If there is a backing file, use it */
655 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
656 char backing_filename[PATH_MAX];
657 int back_flags;
658 BlockDriver *back_drv = NULL;
659
660 bs->backing_hd = bdrv_new("");
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000661
662 if (path_has_protocol(bs->backing_file)) {
663 pstrcpy(backing_filename, sizeof(backing_filename),
664 bs->backing_file);
665 } else {
666 path_combine(backing_filename, sizeof(backing_filename),
667 filename, bs->backing_file);
668 }
669
670 if (bs->backing_format[0] != '\0') {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200671 back_drv = bdrv_find_format(bs->backing_format);
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000672 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200673
674 /* backing files always opened read-only */
675 back_flags =
676 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
677
678 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
679 if (ret < 0) {
680 bdrv_close(bs);
681 return ret;
682 }
683 if (bs->is_temporary) {
684 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
685 } else {
686 /* base image inherits from "parent" */
687 bs->backing_hd->keep_read_only = bs->keep_read_only;
688 }
689 }
690
691 if (!bdrv_key_required(bs)) {
Markus Armbruster145feb12011-08-03 15:07:42 +0200692 bdrv_dev_change_media_cb(bs);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200693 }
694
695 return 0;
696
697unlink_and_fail:
698 if (bs->is_temporary) {
699 unlink(filename);
700 }
701 return ret;
702}
703
bellardfc01f7e2003-06-30 10:03:06 +0000704void bdrv_close(BlockDriverState *bs)
705{
bellard19cb3732006-08-19 11:45:59 +0000706 if (bs->drv) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200707 if (bs == bs_snapshots) {
708 bs_snapshots = NULL;
709 }
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100710 if (bs->backing_hd) {
bellardea2384d2004-08-01 21:59:26 +0000711 bdrv_delete(bs->backing_hd);
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100712 bs->backing_hd = NULL;
713 }
bellardea2384d2004-08-01 21:59:26 +0000714 bs->drv->bdrv_close(bs);
Anthony Liguori7267c092011-08-20 22:09:37 -0500715 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +0000716#ifdef _WIN32
717 if (bs->is_temporary) {
718 unlink(bs->filename);
719 }
bellard67b915a2004-03-31 23:37:16 +0000720#endif
bellardea2384d2004-08-01 21:59:26 +0000721 bs->opaque = NULL;
722 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +0000723
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200724 if (bs->file != NULL) {
725 bdrv_close(bs->file);
726 }
727
Markus Armbruster145feb12011-08-03 15:07:42 +0200728 bdrv_dev_change_media_cb(bs);
bellardb3380822004-03-14 21:38:54 +0000729 }
730}
731
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +0900732void bdrv_close_all(void)
733{
734 BlockDriverState *bs;
735
736 QTAILQ_FOREACH(bs, &bdrv_states, list) {
737 bdrv_close(bs);
738 }
739}
740
Ryan Harperd22b2f42011-03-29 20:51:47 -0500741/* make a BlockDriverState anonymous by removing from bdrv_state list.
742 Also, NULL terminate the device_name to prevent double remove */
743void bdrv_make_anon(BlockDriverState *bs)
744{
745 if (bs->device_name[0] != '\0') {
746 QTAILQ_REMOVE(&bdrv_states, bs, list);
747 }
748 bs->device_name[0] = '\0';
749}
750
bellardb3380822004-03-14 21:38:54 +0000751void bdrv_delete(BlockDriverState *bs)
752{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200753 assert(!bs->dev);
Markus Armbruster18846de2010-06-29 16:58:30 +0200754
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100755 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -0500756 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +0000757
bellardb3380822004-03-14 21:38:54 +0000758 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200759 if (bs->file != NULL) {
760 bdrv_delete(bs->file);
761 }
762
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200763 assert(bs != bs_snapshots);
Anthony Liguori7267c092011-08-20 22:09:37 -0500764 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +0000765}
766
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200767int bdrv_attach_dev(BlockDriverState *bs, void *dev)
768/* TODO change to DeviceState *dev when all users are qdevified */
Markus Armbruster18846de2010-06-29 16:58:30 +0200769{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200770 if (bs->dev) {
Markus Armbruster18846de2010-06-29 16:58:30 +0200771 return -EBUSY;
772 }
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200773 bs->dev = dev;
Markus Armbruster18846de2010-06-29 16:58:30 +0200774 return 0;
775}
776
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200777/* TODO qdevified devices don't use this, remove when devices are qdevified */
778void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
Markus Armbruster18846de2010-06-29 16:58:30 +0200779{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200780 if (bdrv_attach_dev(bs, dev) < 0) {
781 abort();
782 }
783}
784
785void bdrv_detach_dev(BlockDriverState *bs, void *dev)
786/* TODO change to DeviceState *dev when all users are qdevified */
787{
788 assert(bs->dev == dev);
789 bs->dev = NULL;
Markus Armbruster0e49de52011-08-03 15:07:41 +0200790 bs->dev_ops = NULL;
791 bs->dev_opaque = NULL;
Markus Armbruster18846de2010-06-29 16:58:30 +0200792}
793
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200794/* TODO change to return DeviceState * when all users are qdevified */
795void *bdrv_get_attached_dev(BlockDriverState *bs)
Markus Armbruster18846de2010-06-29 16:58:30 +0200796{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200797 return bs->dev;
Markus Armbruster18846de2010-06-29 16:58:30 +0200798}
799
Markus Armbruster0e49de52011-08-03 15:07:41 +0200800void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
801 void *opaque)
802{
803 bs->dev_ops = ops;
804 bs->dev_opaque = opaque;
Markus Armbruster2c6942f2011-09-06 18:58:51 +0200805 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
806 bs_snapshots = NULL;
807 }
Markus Armbruster0e49de52011-08-03 15:07:41 +0200808}
809
Markus Armbruster145feb12011-08-03 15:07:42 +0200810static void bdrv_dev_change_media_cb(BlockDriverState *bs)
Markus Armbruster0e49de52011-08-03 15:07:41 +0200811{
Markus Armbruster145feb12011-08-03 15:07:42 +0200812 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
813 bs->dev_ops->change_media_cb(bs->dev_opaque);
814 }
815}
816
Markus Armbruster2c6942f2011-09-06 18:58:51 +0200817bool bdrv_dev_has_removable_media(BlockDriverState *bs)
818{
819 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
820}
821
Markus Armbruster145feb12011-08-03 15:07:42 +0200822static void bdrv_dev_resize_cb(BlockDriverState *bs)
823{
824 if (bs->dev_ops && bs->dev_ops->resize_cb) {
825 bs->dev_ops->resize_cb(bs->dev_opaque);
Markus Armbruster0e49de52011-08-03 15:07:41 +0200826 }
827}
828
Markus Armbrusterf1076392011-09-06 18:58:46 +0200829bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
830{
831 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
832 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
833 }
834 return false;
835}
836
aliguorie97fc192009-04-21 23:11:50 +0000837/*
838 * Run consistency checks on an image
839 *
Kevin Wolfe076f332010-06-29 11:43:13 +0200840 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +0200841 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +0200842 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +0000843 */
Kevin Wolfe076f332010-06-29 11:43:13 +0200844int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
aliguorie97fc192009-04-21 23:11:50 +0000845{
846 if (bs->drv->bdrv_check == NULL) {
847 return -ENOTSUP;
848 }
849
Kevin Wolfe076f332010-06-29 11:43:13 +0200850 memset(res, 0, sizeof(*res));
Kevin Wolf9ac228e2010-06-29 12:37:54 +0200851 return bs->drv->bdrv_check(bs, res);
aliguorie97fc192009-04-21 23:11:50 +0000852}
853
Kevin Wolf8a426612010-07-16 17:17:01 +0200854#define COMMIT_BUF_SECTORS 2048
855
bellard33e39632003-07-06 17:15:21 +0000856/* commit COW file into the raw image */
857int bdrv_commit(BlockDriverState *bs)
858{
bellard19cb3732006-08-19 11:45:59 +0000859 BlockDriver *drv = bs->drv;
Kevin Wolfee181192010-08-05 13:05:22 +0200860 BlockDriver *backing_drv;
Kevin Wolf8a426612010-07-16 17:17:01 +0200861 int64_t sector, total_sectors;
862 int n, ro, open_flags;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200863 int ret = 0, rw_ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +0200864 uint8_t *buf;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200865 char filename[1024];
866 BlockDriverState *bs_rw, *bs_ro;
bellard33e39632003-07-06 17:15:21 +0000867
bellard19cb3732006-08-19 11:45:59 +0000868 if (!drv)
869 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200870
871 if (!bs->backing_hd) {
872 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +0000873 }
874
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200875 if (bs->backing_hd->keep_read_only) {
876 return -EACCES;
877 }
Kevin Wolfee181192010-08-05 13:05:22 +0200878
879 backing_drv = bs->backing_hd->drv;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200880 ro = bs->backing_hd->read_only;
881 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
882 open_flags = bs->backing_hd->open_flags;
883
884 if (ro) {
885 /* re-open as RW */
886 bdrv_delete(bs->backing_hd);
887 bs->backing_hd = NULL;
888 bs_rw = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200889 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
890 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200891 if (rw_ret < 0) {
892 bdrv_delete(bs_rw);
893 /* try to re-open read-only */
894 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200895 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
896 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200897 if (ret < 0) {
898 bdrv_delete(bs_ro);
899 /* drive not functional anymore */
900 bs->drv = NULL;
901 return ret;
902 }
903 bs->backing_hd = bs_ro;
904 return rw_ret;
905 }
906 bs->backing_hd = bs_rw;
bellard33e39632003-07-06 17:15:21 +0000907 }
bellardea2384d2004-08-01 21:59:26 +0000908
Jan Kiszka6ea44302009-11-30 18:21:19 +0100909 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Anthony Liguori7267c092011-08-20 22:09:37 -0500910 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +0000911
Kevin Wolf8a426612010-07-16 17:17:01 +0200912 for (sector = 0; sector < total_sectors; sector += n) {
913 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
914
915 if (bdrv_read(bs, sector, buf, n) != 0) {
916 ret = -EIO;
917 goto ro_cleanup;
918 }
919
920 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
921 ret = -EIO;
922 goto ro_cleanup;
923 }
bellardea2384d2004-08-01 21:59:26 +0000924 }
925 }
bellard95389c82005-12-18 18:28:15 +0000926
Christoph Hellwig1d449522010-01-17 12:32:30 +0100927 if (drv->bdrv_make_empty) {
928 ret = drv->bdrv_make_empty(bs);
929 bdrv_flush(bs);
930 }
bellard95389c82005-12-18 18:28:15 +0000931
Christoph Hellwig3f5075a2010-01-12 13:49:23 +0100932 /*
933 * Make sure all data we wrote to the backing device is actually
934 * stable on disk.
935 */
936 if (bs->backing_hd)
937 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200938
939ro_cleanup:
Anthony Liguori7267c092011-08-20 22:09:37 -0500940 g_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200941
942 if (ro) {
943 /* re-open as RO */
944 bdrv_delete(bs->backing_hd);
945 bs->backing_hd = NULL;
946 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200947 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
948 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200949 if (ret < 0) {
950 bdrv_delete(bs_ro);
951 /* drive not functional anymore */
952 bs->drv = NULL;
953 return ret;
954 }
955 bs->backing_hd = bs_ro;
956 bs->backing_hd->keep_read_only = 0;
957 }
958
Christoph Hellwig1d449522010-01-17 12:32:30 +0100959 return ret;
bellard33e39632003-07-06 17:15:21 +0000960}
961
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +0200962void bdrv_commit_all(void)
963{
964 BlockDriverState *bs;
965
966 QTAILQ_FOREACH(bs, &bdrv_states, list) {
967 bdrv_commit(bs);
968 }
969}
970
Kevin Wolf756e6732010-01-12 12:55:17 +0100971/*
972 * Return values:
973 * 0 - success
974 * -EINVAL - backing format specified, but no file
975 * -ENOSPC - can't update the backing file because no space is left in the
976 * image file header
977 * -ENOTSUP - format driver doesn't support changing the backing file
978 */
979int bdrv_change_backing_file(BlockDriverState *bs,
980 const char *backing_file, const char *backing_fmt)
981{
982 BlockDriver *drv = bs->drv;
983
984 if (drv->bdrv_change_backing_file != NULL) {
985 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
986 } else {
987 return -ENOTSUP;
988 }
989}
990
aliguori71d07702009-03-03 17:37:16 +0000991static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
992 size_t size)
993{
994 int64_t len;
995
996 if (!bdrv_is_inserted(bs))
997 return -ENOMEDIUM;
998
999 if (bs->growable)
1000 return 0;
1001
1002 len = bdrv_getlength(bs);
1003
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02001004 if (offset < 0)
1005 return -EIO;
1006
1007 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +00001008 return -EIO;
1009
1010 return 0;
1011}
1012
1013static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1014 int nb_sectors)
1015{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001016 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1017 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +00001018}
1019
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001020static inline bool bdrv_has_async_rw(BlockDriver *drv)
1021{
1022 return drv->bdrv_co_readv != bdrv_co_readv_em
1023 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1024}
1025
1026static inline bool bdrv_has_async_flush(BlockDriver *drv)
1027{
1028 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1029}
1030
bellard19cb3732006-08-19 11:45:59 +00001031/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +00001032int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001033 uint8_t *buf, int nb_sectors)
1034{
bellardea2384d2004-08-01 21:59:26 +00001035 BlockDriver *drv = bs->drv;
1036
bellard19cb3732006-08-19 11:45:59 +00001037 if (!drv)
1038 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001039
1040 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1041 QEMUIOVector qiov;
1042 struct iovec iov = {
1043 .iov_base = (void *)buf,
1044 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1045 };
1046
1047 qemu_iovec_init_external(&qiov, &iov, 1);
1048 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1049 }
1050
aliguori71d07702009-03-03 17:37:16 +00001051 if (bdrv_check_request(bs, sector_num, nb_sectors))
1052 return -EIO;
bellardb3380822004-03-14 21:38:54 +00001053
aliguorieda578e2009-03-12 19:57:16 +00001054 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
bellardfc01f7e2003-06-30 10:03:06 +00001055}
1056
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001057static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001058 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001059{
1060 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001061 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001062
Jan Kiszka6ea44302009-11-30 18:21:19 +01001063 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001064 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001065
1066 for (; start <= end; start++) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01001067 idx = start / (sizeof(unsigned long) * 8);
1068 bit = start % (sizeof(unsigned long) * 8);
1069 val = bs->dirty_bitmap[idx];
1070 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001071 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001072 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001073 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +02001074 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001075 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001076 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001077 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001078 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +02001079 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001080 }
1081 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001082 }
1083}
1084
ths5fafdf22007-09-16 21:08:06 +00001085/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +00001086 -EIO generic I/O error (may happen for all errors)
1087 -ENOMEDIUM No media inserted.
1088 -EINVAL Invalid sector number or nb_sectors
1089 -EACCES Trying to write a read-only device
1090*/
ths5fafdf22007-09-16 21:08:06 +00001091int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001092 const uint8_t *buf, int nb_sectors)
1093{
bellard83f64092006-08-01 16:21:11 +00001094 BlockDriver *drv = bs->drv;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001095
bellard19cb3732006-08-19 11:45:59 +00001096 if (!bs->drv)
1097 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001098
1099 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1100 QEMUIOVector qiov;
1101 struct iovec iov = {
1102 .iov_base = (void *)buf,
1103 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1104 };
1105
1106 qemu_iovec_init_external(&qiov, &iov, 1);
1107 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1108 }
1109
bellard0849bf02003-06-30 23:17:31 +00001110 if (bs->read_only)
bellard19cb3732006-08-19 11:45:59 +00001111 return -EACCES;
aliguori71d07702009-03-03 17:37:16 +00001112 if (bdrv_check_request(bs, sector_num, nb_sectors))
1113 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001114
Jan Kiszkac6d22832009-11-30 18:21:20 +01001115 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001116 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1117 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001118
Kevin Wolf294cc352010-04-28 14:34:01 +02001119 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1120 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1121 }
1122
aliguori42fb2802009-01-15 20:43:39 +00001123 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
bellard83f64092006-08-01 16:21:11 +00001124}
1125
aliguorieda578e2009-03-12 19:57:16 +00001126int bdrv_pread(BlockDriverState *bs, int64_t offset,
1127 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001128{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001129 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001130 int len, nb_sectors, count;
1131 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001132 int ret;
bellard83f64092006-08-01 16:21:11 +00001133
1134 count = count1;
1135 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001136 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001137 if (len > count)
1138 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001139 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001140 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001141 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1142 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001143 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00001144 count -= len;
1145 if (count == 0)
1146 return count1;
1147 sector_num++;
1148 buf += len;
1149 }
1150
1151 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001152 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001153 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001154 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1155 return ret;
bellard83f64092006-08-01 16:21:11 +00001156 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001157 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001158 buf += len;
1159 count -= len;
1160 }
1161
1162 /* add data from the last sector */
1163 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001164 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1165 return ret;
bellard83f64092006-08-01 16:21:11 +00001166 memcpy(buf, tmp_buf, count);
1167 }
1168 return count1;
1169}
1170
aliguorieda578e2009-03-12 19:57:16 +00001171int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1172 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001173{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001174 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001175 int len, nb_sectors, count;
1176 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001177 int ret;
bellard83f64092006-08-01 16:21:11 +00001178
1179 count = count1;
1180 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001181 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001182 if (len > count)
1183 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001184 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001185 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001186 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1187 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001188 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001189 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1190 return ret;
bellard83f64092006-08-01 16:21:11 +00001191 count -= len;
1192 if (count == 0)
1193 return count1;
1194 sector_num++;
1195 buf += len;
1196 }
1197
1198 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001199 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001200 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001201 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1202 return ret;
bellard83f64092006-08-01 16:21:11 +00001203 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001204 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001205 buf += len;
1206 count -= len;
1207 }
1208
1209 /* add data from the last sector */
1210 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001211 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1212 return ret;
bellard83f64092006-08-01 16:21:11 +00001213 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001214 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1215 return ret;
bellard83f64092006-08-01 16:21:11 +00001216 }
1217 return count1;
1218}
bellard83f64092006-08-01 16:21:11 +00001219
Kevin Wolff08145f2010-06-16 16:38:15 +02001220/*
1221 * Writes to the file and ensures that no writes are reordered across this
1222 * request (acts as a barrier)
1223 *
1224 * Returns 0 on success, -errno in error cases.
1225 */
1226int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1227 const void *buf, int count)
1228{
1229 int ret;
1230
1231 ret = bdrv_pwrite(bs, offset, buf, count);
1232 if (ret < 0) {
1233 return ret;
1234 }
1235
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001236 /* No flush needed for cache modes that use O_DSYNC */
1237 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
Kevin Wolff08145f2010-06-16 16:38:15 +02001238 bdrv_flush(bs);
1239 }
1240
1241 return 0;
1242}
1243
Kevin Wolfda1fa912011-07-14 17:27:13 +02001244int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1245 int nb_sectors, QEMUIOVector *qiov)
1246{
1247 BlockDriver *drv = bs->drv;
1248
1249 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1250
1251 if (!drv) {
1252 return -ENOMEDIUM;
1253 }
1254 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1255 return -EIO;
1256 }
1257
1258 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1259}
1260
1261int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1262 int nb_sectors, QEMUIOVector *qiov)
1263{
1264 BlockDriver *drv = bs->drv;
1265
1266 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1267
1268 if (!bs->drv) {
1269 return -ENOMEDIUM;
1270 }
1271 if (bs->read_only) {
1272 return -EACCES;
1273 }
1274 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1275 return -EIO;
1276 }
1277
1278 if (bs->dirty_bitmap) {
1279 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1280 }
1281
1282 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1283 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1284 }
1285
1286 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1287}
1288
bellard83f64092006-08-01 16:21:11 +00001289/**
bellard83f64092006-08-01 16:21:11 +00001290 * Truncate file to 'offset' bytes (needed only for file protocols)
1291 */
1292int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1293{
1294 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001295 int ret;
bellard83f64092006-08-01 16:21:11 +00001296 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001297 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00001298 if (!drv->bdrv_truncate)
1299 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02001300 if (bs->read_only)
1301 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02001302 if (bdrv_in_use(bs))
1303 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001304 ret = drv->bdrv_truncate(bs, offset);
1305 if (ret == 0) {
1306 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Markus Armbruster145feb12011-08-03 15:07:42 +02001307 bdrv_dev_resize_cb(bs);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001308 }
1309 return ret;
bellard83f64092006-08-01 16:21:11 +00001310}
1311
1312/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08001313 * Length of a allocated file in bytes. Sparse files are counted by actual
1314 * allocated space. Return < 0 if error or unknown.
1315 */
1316int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1317{
1318 BlockDriver *drv = bs->drv;
1319 if (!drv) {
1320 return -ENOMEDIUM;
1321 }
1322 if (drv->bdrv_get_allocated_file_size) {
1323 return drv->bdrv_get_allocated_file_size(bs);
1324 }
1325 if (bs->file) {
1326 return bdrv_get_allocated_file_size(bs->file);
1327 }
1328 return -ENOTSUP;
1329}
1330
1331/**
bellard83f64092006-08-01 16:21:11 +00001332 * Length of a file in bytes. Return < 0 if error or unknown.
1333 */
1334int64_t bdrv_getlength(BlockDriverState *bs)
1335{
1336 BlockDriver *drv = bs->drv;
1337 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001338 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001339
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001340 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001341 if (drv->bdrv_getlength) {
1342 return drv->bdrv_getlength(bs);
1343 }
bellard83f64092006-08-01 16:21:11 +00001344 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001345 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00001346}
1347
bellard19cb3732006-08-19 11:45:59 +00001348/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00001349void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00001350{
bellard19cb3732006-08-19 11:45:59 +00001351 int64_t length;
1352 length = bdrv_getlength(bs);
1353 if (length < 0)
1354 length = 0;
1355 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01001356 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00001357 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00001358}
bellardcf989512004-02-16 21:56:36 +00001359
aliguorif3d54fc2008-11-25 21:50:24 +00001360struct partition {
1361 uint8_t boot_ind; /* 0x80 - active */
1362 uint8_t head; /* starting head */
1363 uint8_t sector; /* starting sector */
1364 uint8_t cyl; /* starting cylinder */
1365 uint8_t sys_ind; /* What partition type */
1366 uint8_t end_head; /* end head */
1367 uint8_t end_sector; /* end sector */
1368 uint8_t end_cyl; /* end cylinder */
1369 uint32_t start_sect; /* starting sector counting from 0 */
1370 uint32_t nr_sects; /* nr of sectors in partition */
Stefan Weil541dc0d2011-08-31 12:38:01 +02001371} QEMU_PACKED;
aliguorif3d54fc2008-11-25 21:50:24 +00001372
1373/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1374static int guess_disk_lchs(BlockDriverState *bs,
1375 int *pcylinders, int *pheads, int *psectors)
1376{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001377 uint8_t buf[BDRV_SECTOR_SIZE];
aliguorif3d54fc2008-11-25 21:50:24 +00001378 int ret, i, heads, sectors, cylinders;
1379 struct partition *p;
1380 uint32_t nr_sects;
blueswir1a38131b2008-12-05 17:56:40 +00001381 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001382
1383 bdrv_get_geometry(bs, &nb_sectors);
1384
1385 ret = bdrv_read(bs, 0, buf, 1);
1386 if (ret < 0)
1387 return -1;
1388 /* test msdos magic */
1389 if (buf[510] != 0x55 || buf[511] != 0xaa)
1390 return -1;
1391 for(i = 0; i < 4; i++) {
1392 p = ((struct partition *)(buf + 0x1be)) + i;
1393 nr_sects = le32_to_cpu(p->nr_sects);
1394 if (nr_sects && p->end_head) {
1395 /* We make the assumption that the partition terminates on
1396 a cylinder boundary */
1397 heads = p->end_head + 1;
1398 sectors = p->end_sector & 63;
1399 if (sectors == 0)
1400 continue;
1401 cylinders = nb_sectors / (heads * sectors);
1402 if (cylinders < 1 || cylinders > 16383)
1403 continue;
1404 *pheads = heads;
1405 *psectors = sectors;
1406 *pcylinders = cylinders;
1407#if 0
1408 printf("guessed geometry: LCHS=%d %d %d\n",
1409 cylinders, heads, sectors);
1410#endif
1411 return 0;
1412 }
1413 }
1414 return -1;
1415}
1416
1417void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1418{
1419 int translation, lba_detected = 0;
1420 int cylinders, heads, secs;
blueswir1a38131b2008-12-05 17:56:40 +00001421 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001422
1423 /* if a geometry hint is available, use it */
1424 bdrv_get_geometry(bs, &nb_sectors);
1425 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1426 translation = bdrv_get_translation_hint(bs);
1427 if (cylinders != 0) {
1428 *pcyls = cylinders;
1429 *pheads = heads;
1430 *psecs = secs;
1431 } else {
1432 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1433 if (heads > 16) {
1434 /* if heads > 16, it means that a BIOS LBA
1435 translation was active, so the default
1436 hardware geometry is OK */
1437 lba_detected = 1;
1438 goto default_geometry;
1439 } else {
1440 *pcyls = cylinders;
1441 *pheads = heads;
1442 *psecs = secs;
1443 /* disable any translation to be in sync with
1444 the logical geometry */
1445 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1446 bdrv_set_translation_hint(bs,
1447 BIOS_ATA_TRANSLATION_NONE);
1448 }
1449 }
1450 } else {
1451 default_geometry:
1452 /* if no geometry, use a standard physical disk geometry */
1453 cylinders = nb_sectors / (16 * 63);
1454
1455 if (cylinders > 16383)
1456 cylinders = 16383;
1457 else if (cylinders < 2)
1458 cylinders = 2;
1459 *pcyls = cylinders;
1460 *pheads = 16;
1461 *psecs = 63;
1462 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1463 if ((*pcyls * *pheads) <= 131072) {
1464 bdrv_set_translation_hint(bs,
1465 BIOS_ATA_TRANSLATION_LARGE);
1466 } else {
1467 bdrv_set_translation_hint(bs,
1468 BIOS_ATA_TRANSLATION_LBA);
1469 }
1470 }
1471 }
1472 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1473 }
1474}
1475
ths5fafdf22007-09-16 21:08:06 +00001476void bdrv_set_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001477 int cyls, int heads, int secs)
1478{
1479 bs->cyls = cyls;
1480 bs->heads = heads;
1481 bs->secs = secs;
1482}
1483
bellard46d47672004-11-16 01:45:27 +00001484void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1485{
1486 bs->translation = translation;
1487}
1488
ths5fafdf22007-09-16 21:08:06 +00001489void bdrv_get_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001490 int *pcyls, int *pheads, int *psecs)
1491{
1492 *pcyls = bs->cyls;
1493 *pheads = bs->heads;
1494 *psecs = bs->secs;
1495}
1496
Blue Swirl5bbdbb42011-02-12 20:43:32 +00001497/* Recognize floppy formats */
1498typedef struct FDFormat {
1499 FDriveType drive;
1500 uint8_t last_sect;
1501 uint8_t max_track;
1502 uint8_t max_head;
1503} FDFormat;
1504
1505static const FDFormat fd_formats[] = {
1506 /* First entry is default format */
1507 /* 1.44 MB 3"1/2 floppy disks */
1508 { FDRIVE_DRV_144, 18, 80, 1, },
1509 { FDRIVE_DRV_144, 20, 80, 1, },
1510 { FDRIVE_DRV_144, 21, 80, 1, },
1511 { FDRIVE_DRV_144, 21, 82, 1, },
1512 { FDRIVE_DRV_144, 21, 83, 1, },
1513 { FDRIVE_DRV_144, 22, 80, 1, },
1514 { FDRIVE_DRV_144, 23, 80, 1, },
1515 { FDRIVE_DRV_144, 24, 80, 1, },
1516 /* 2.88 MB 3"1/2 floppy disks */
1517 { FDRIVE_DRV_288, 36, 80, 1, },
1518 { FDRIVE_DRV_288, 39, 80, 1, },
1519 { FDRIVE_DRV_288, 40, 80, 1, },
1520 { FDRIVE_DRV_288, 44, 80, 1, },
1521 { FDRIVE_DRV_288, 48, 80, 1, },
1522 /* 720 kB 3"1/2 floppy disks */
1523 { FDRIVE_DRV_144, 9, 80, 1, },
1524 { FDRIVE_DRV_144, 10, 80, 1, },
1525 { FDRIVE_DRV_144, 10, 82, 1, },
1526 { FDRIVE_DRV_144, 10, 83, 1, },
1527 { FDRIVE_DRV_144, 13, 80, 1, },
1528 { FDRIVE_DRV_144, 14, 80, 1, },
1529 /* 1.2 MB 5"1/4 floppy disks */
1530 { FDRIVE_DRV_120, 15, 80, 1, },
1531 { FDRIVE_DRV_120, 18, 80, 1, },
1532 { FDRIVE_DRV_120, 18, 82, 1, },
1533 { FDRIVE_DRV_120, 18, 83, 1, },
1534 { FDRIVE_DRV_120, 20, 80, 1, },
1535 /* 720 kB 5"1/4 floppy disks */
1536 { FDRIVE_DRV_120, 9, 80, 1, },
1537 { FDRIVE_DRV_120, 11, 80, 1, },
1538 /* 360 kB 5"1/4 floppy disks */
1539 { FDRIVE_DRV_120, 9, 40, 1, },
1540 { FDRIVE_DRV_120, 9, 40, 0, },
1541 { FDRIVE_DRV_120, 10, 41, 1, },
1542 { FDRIVE_DRV_120, 10, 42, 1, },
1543 /* 320 kB 5"1/4 floppy disks */
1544 { FDRIVE_DRV_120, 8, 40, 1, },
1545 { FDRIVE_DRV_120, 8, 40, 0, },
1546 /* 360 kB must match 5"1/4 better than 3"1/2... */
1547 { FDRIVE_DRV_144, 9, 80, 0, },
1548 /* end */
1549 { FDRIVE_DRV_NONE, -1, -1, 0, },
1550};
1551
1552void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1553 int *max_track, int *last_sect,
1554 FDriveType drive_in, FDriveType *drive)
1555{
1556 const FDFormat *parse;
1557 uint64_t nb_sectors, size;
1558 int i, first_match, match;
1559
1560 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1561 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1562 /* User defined disk */
1563 } else {
1564 bdrv_get_geometry(bs, &nb_sectors);
1565 match = -1;
1566 first_match = -1;
1567 for (i = 0; ; i++) {
1568 parse = &fd_formats[i];
1569 if (parse->drive == FDRIVE_DRV_NONE) {
1570 break;
1571 }
1572 if (drive_in == parse->drive ||
1573 drive_in == FDRIVE_DRV_NONE) {
1574 size = (parse->max_head + 1) * parse->max_track *
1575 parse->last_sect;
1576 if (nb_sectors == size) {
1577 match = i;
1578 break;
1579 }
1580 if (first_match == -1) {
1581 first_match = i;
1582 }
1583 }
1584 }
1585 if (match == -1) {
1586 if (first_match == -1) {
1587 match = 1;
1588 } else {
1589 match = first_match;
1590 }
1591 parse = &fd_formats[match];
1592 }
1593 *nb_heads = parse->max_head + 1;
1594 *max_track = parse->max_track;
1595 *last_sect = parse->last_sect;
1596 *drive = parse->drive;
1597 }
1598}
1599
bellard46d47672004-11-16 01:45:27 +00001600int bdrv_get_translation_hint(BlockDriverState *bs)
1601{
1602 return bs->translation;
1603}
1604
Markus Armbrusterabd7f682010-06-02 18:55:17 +02001605void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1606 BlockErrorAction on_write_error)
1607{
1608 bs->on_read_error = on_read_error;
1609 bs->on_write_error = on_write_error;
1610}
1611
1612BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1613{
1614 return is_read ? bs->on_read_error : bs->on_write_error;
1615}
1616
bellardb3380822004-03-14 21:38:54 +00001617int bdrv_is_read_only(BlockDriverState *bs)
1618{
1619 return bs->read_only;
1620}
1621
ths985a03b2007-12-24 16:10:43 +00001622int bdrv_is_sg(BlockDriverState *bs)
1623{
1624 return bs->sg;
1625}
1626
Christoph Hellwige900a7b2009-09-04 19:01:15 +02001627int bdrv_enable_write_cache(BlockDriverState *bs)
1628{
1629 return bs->enable_write_cache;
1630}
1631
bellardea2384d2004-08-01 21:59:26 +00001632int bdrv_is_encrypted(BlockDriverState *bs)
1633{
1634 if (bs->backing_hd && bs->backing_hd->encrypted)
1635 return 1;
1636 return bs->encrypted;
1637}
1638
aliguoric0f4ce72009-03-05 23:01:01 +00001639int bdrv_key_required(BlockDriverState *bs)
1640{
1641 BlockDriverState *backing_hd = bs->backing_hd;
1642
1643 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1644 return 1;
1645 return (bs->encrypted && !bs->valid_key);
1646}
1647
bellardea2384d2004-08-01 21:59:26 +00001648int bdrv_set_key(BlockDriverState *bs, const char *key)
1649{
1650 int ret;
1651 if (bs->backing_hd && bs->backing_hd->encrypted) {
1652 ret = bdrv_set_key(bs->backing_hd, key);
1653 if (ret < 0)
1654 return ret;
1655 if (!bs->encrypted)
1656 return 0;
1657 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02001658 if (!bs->encrypted) {
1659 return -EINVAL;
1660 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1661 return -ENOMEDIUM;
1662 }
aliguoric0f4ce72009-03-05 23:01:01 +00001663 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00001664 if (ret < 0) {
1665 bs->valid_key = 0;
1666 } else if (!bs->valid_key) {
1667 bs->valid_key = 1;
1668 /* call the change callback now, we skipped it on open */
Markus Armbruster145feb12011-08-03 15:07:42 +02001669 bdrv_dev_change_media_cb(bs);
aliguoribb5fc202009-03-05 23:01:15 +00001670 }
aliguoric0f4ce72009-03-05 23:01:01 +00001671 return ret;
bellardea2384d2004-08-01 21:59:26 +00001672}
1673
1674void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1675{
bellard19cb3732006-08-19 11:45:59 +00001676 if (!bs->drv) {
bellardea2384d2004-08-01 21:59:26 +00001677 buf[0] = '\0';
1678 } else {
1679 pstrcpy(buf, buf_size, bs->drv->format_name);
1680 }
1681}
1682
ths5fafdf22007-09-16 21:08:06 +00001683void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00001684 void *opaque)
1685{
1686 BlockDriver *drv;
1687
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01001688 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00001689 it(opaque, drv->format_name);
1690 }
1691}
1692
bellardb3380822004-03-14 21:38:54 +00001693BlockDriverState *bdrv_find(const char *name)
1694{
1695 BlockDriverState *bs;
1696
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001697 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1698 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00001699 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001700 }
bellardb3380822004-03-14 21:38:54 +00001701 }
1702 return NULL;
1703}
1704
Markus Armbruster2f399b02010-06-02 18:55:20 +02001705BlockDriverState *bdrv_next(BlockDriverState *bs)
1706{
1707 if (!bs) {
1708 return QTAILQ_FIRST(&bdrv_states);
1709 }
1710 return QTAILQ_NEXT(bs, list);
1711}
1712
aliguori51de9762009-03-05 23:00:43 +00001713void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00001714{
1715 BlockDriverState *bs;
1716
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001717 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00001718 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00001719 }
1720}
1721
bellardea2384d2004-08-01 21:59:26 +00001722const char *bdrv_get_device_name(BlockDriverState *bs)
1723{
1724 return bs->device_name;
1725}
1726
Kevin Wolf205ef792010-10-21 16:43:43 +02001727int bdrv_flush(BlockDriverState *bs)
pbrook7a6cba62006-06-04 11:39:07 +00001728{
Alexander Graf016f5cf2010-05-26 17:51:49 +02001729 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolf205ef792010-10-21 16:43:43 +02001730 return 0;
Alexander Graf016f5cf2010-05-26 17:51:49 +02001731 }
1732
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001733 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1734 return bdrv_co_flush_em(bs);
1735 }
1736
Kevin Wolf205ef792010-10-21 16:43:43 +02001737 if (bs->drv && bs->drv->bdrv_flush) {
1738 return bs->drv->bdrv_flush(bs);
1739 }
1740
1741 /*
1742 * Some block drivers always operate in either writethrough or unsafe mode
1743 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1744 * the server works (because the behaviour is hardcoded or depends on
1745 * server-side configuration), so we can't ensure that everything is safe
1746 * on disk. Returning an error doesn't work because that would break guests
1747 * even if the server operates in writethrough mode.
1748 *
1749 * Let's hope the user knows what he's doing.
1750 */
1751 return 0;
pbrook7a6cba62006-06-04 11:39:07 +00001752}
1753
aliguoric6ca28d2008-10-06 13:55:43 +00001754void bdrv_flush_all(void)
1755{
1756 BlockDriverState *bs;
1757
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001758 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Markus Armbrusterc602a482011-08-03 15:08:10 +02001759 if (!bdrv_is_read_only(bs) && bdrv_is_inserted(bs)) {
aliguoric6ca28d2008-10-06 13:55:43 +00001760 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001761 }
1762 }
aliguoric6ca28d2008-10-06 13:55:43 +00001763}
1764
Kevin Wolff2feebb2010-04-14 17:30:35 +02001765int bdrv_has_zero_init(BlockDriverState *bs)
1766{
1767 assert(bs->drv);
1768
Kevin Wolf336c1c12010-07-28 11:26:29 +02001769 if (bs->drv->bdrv_has_zero_init) {
1770 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02001771 }
1772
1773 return 1;
1774}
1775
Christoph Hellwigbb8bf762010-12-16 19:36:31 +01001776int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1777{
1778 if (!bs->drv) {
1779 return -ENOMEDIUM;
1780 }
1781 if (!bs->drv->bdrv_discard) {
1782 return 0;
1783 }
1784 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1785}
1786
thsf58c7b32008-06-05 21:53:49 +00001787/*
1788 * Returns true iff the specified sector is present in the disk image. Drivers
1789 * not implementing the functionality are assumed to not support backing files,
1790 * hence all their sectors are reported as allocated.
1791 *
1792 * 'pnum' is set to the number of sectors (including and immediately following
1793 * the specified sector) that are known to be in the same
1794 * allocated/unallocated state.
1795 *
1796 * 'nb_sectors' is the max value 'pnum' should be set to.
1797 */
1798int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1799 int *pnum)
1800{
1801 int64_t n;
1802 if (!bs->drv->bdrv_is_allocated) {
1803 if (sector_num >= bs->total_sectors) {
1804 *pnum = 0;
1805 return 0;
1806 }
1807 n = bs->total_sectors - sector_num;
1808 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1809 return 1;
1810 }
1811 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1812}
1813
Luiz Capitulino2582bfe2010-02-03 12:41:01 -02001814void bdrv_mon_event(const BlockDriverState *bdrv,
1815 BlockMonEventAction action, int is_read)
1816{
1817 QObject *data;
1818 const char *action_str;
1819
1820 switch (action) {
1821 case BDRV_ACTION_REPORT:
1822 action_str = "report";
1823 break;
1824 case BDRV_ACTION_IGNORE:
1825 action_str = "ignore";
1826 break;
1827 case BDRV_ACTION_STOP:
1828 action_str = "stop";
1829 break;
1830 default:
1831 abort();
1832 }
1833
1834 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1835 bdrv->device_name,
1836 action_str,
1837 is_read ? "read" : "write");
1838 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1839
1840 qobject_decref(data);
1841}
1842
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001843static void bdrv_print_dict(QObject *obj, void *opaque)
bellardb3380822004-03-14 21:38:54 +00001844{
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001845 QDict *bs_dict;
1846 Monitor *mon = opaque;
1847
1848 bs_dict = qobject_to_qdict(obj);
1849
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001850 monitor_printf(mon, "%s: removable=%d",
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001851 qdict_get_str(bs_dict, "device"),
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001852 qdict_get_bool(bs_dict, "removable"));
1853
1854 if (qdict_get_bool(bs_dict, "removable")) {
1855 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1856 }
1857
1858 if (qdict_haskey(bs_dict, "inserted")) {
1859 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1860
1861 monitor_printf(mon, " file=");
1862 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1863 if (qdict_haskey(qdict, "backing_file")) {
1864 monitor_printf(mon, " backing_file=");
1865 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1866 }
1867 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1868 qdict_get_bool(qdict, "ro"),
1869 qdict_get_str(qdict, "drv"),
1870 qdict_get_bool(qdict, "encrypted"));
1871 } else {
1872 monitor_printf(mon, " [not inserted]");
1873 }
1874
1875 monitor_printf(mon, "\n");
1876}
1877
1878void bdrv_info_print(Monitor *mon, const QObject *data)
1879{
1880 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1881}
1882
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001883void bdrv_info(Monitor *mon, QObject **ret_data)
1884{
1885 QList *bs_list;
bellardb3380822004-03-14 21:38:54 +00001886 BlockDriverState *bs;
1887
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001888 bs_list = qlist_new();
1889
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001890 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001891 QObject *bs_obj;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001892
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001893 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001894 "'removable': %i, 'locked': %i }",
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001895 bs->device_name,
1896 bdrv_dev_has_removable_media(bs),
Markus Armbrusterf1076392011-09-06 18:58:46 +02001897 bdrv_dev_is_medium_locked(bs));
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001898
bellard19cb3732006-08-19 11:45:59 +00001899 if (bs->drv) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001900 QObject *obj;
1901 QDict *bs_dict = qobject_to_qdict(bs_obj);
1902
1903 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1904 "'encrypted': %i }",
1905 bs->filename, bs->read_only,
1906 bs->drv->format_name,
1907 bdrv_is_encrypted(bs));
thsfef30742006-12-22 14:11:32 +00001908 if (bs->backing_file[0] != '\0') {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001909 QDict *qdict = qobject_to_qdict(obj);
1910 qdict_put(qdict, "backing_file",
1911 qstring_from_str(bs->backing_file));
aliguori376253e2009-03-05 23:01:23 +00001912 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001913
1914 qdict_put_obj(bs_dict, "inserted", obj);
bellardb3380822004-03-14 21:38:54 +00001915 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001916 qlist_append_obj(bs_list, bs_obj);
bellardb3380822004-03-14 21:38:54 +00001917 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001918
1919 *ret_data = QOBJECT(bs_list);
bellardb3380822004-03-14 21:38:54 +00001920}
thsa36e69d2007-12-02 05:18:19 +00001921
Luiz Capitulino218a5362009-12-10 17:16:07 -02001922static void bdrv_stats_iter(QObject *data, void *opaque)
thsa36e69d2007-12-02 05:18:19 +00001923{
Luiz Capitulino218a5362009-12-10 17:16:07 -02001924 QDict *qdict;
1925 Monitor *mon = opaque;
1926
1927 qdict = qobject_to_qdict(data);
1928 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1929
1930 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1931 monitor_printf(mon, " rd_bytes=%" PRId64
1932 " wr_bytes=%" PRId64
1933 " rd_operations=%" PRId64
1934 " wr_operations=%" PRId64
Christoph Hellwige8045d62011-08-22 00:25:58 +02001935 " flush_operations=%" PRId64
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001936 " wr_total_time_ns=%" PRId64
1937 " rd_total_time_ns=%" PRId64
1938 " flush_total_time_ns=%" PRId64
Luiz Capitulino218a5362009-12-10 17:16:07 -02001939 "\n",
1940 qdict_get_int(qdict, "rd_bytes"),
1941 qdict_get_int(qdict, "wr_bytes"),
1942 qdict_get_int(qdict, "rd_operations"),
Christoph Hellwige8045d62011-08-22 00:25:58 +02001943 qdict_get_int(qdict, "wr_operations"),
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001944 qdict_get_int(qdict, "flush_operations"),
1945 qdict_get_int(qdict, "wr_total_time_ns"),
1946 qdict_get_int(qdict, "rd_total_time_ns"),
1947 qdict_get_int(qdict, "flush_total_time_ns"));
Luiz Capitulino218a5362009-12-10 17:16:07 -02001948}
1949
1950void bdrv_stats_print(Monitor *mon, const QObject *data)
1951{
1952 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1953}
1954
Kevin Wolf294cc352010-04-28 14:34:01 +02001955static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1956{
1957 QObject *res;
1958 QDict *dict;
1959
1960 res = qobject_from_jsonf("{ 'stats': {"
1961 "'rd_bytes': %" PRId64 ","
1962 "'wr_bytes': %" PRId64 ","
1963 "'rd_operations': %" PRId64 ","
1964 "'wr_operations': %" PRId64 ","
Christoph Hellwige8045d62011-08-22 00:25:58 +02001965 "'wr_highest_offset': %" PRId64 ","
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001966 "'flush_operations': %" PRId64 ","
1967 "'wr_total_time_ns': %" PRId64 ","
1968 "'rd_total_time_ns': %" PRId64 ","
1969 "'flush_total_time_ns': %" PRId64
Kevin Wolf294cc352010-04-28 14:34:01 +02001970 "} }",
Christoph Hellwiga597e792011-08-25 08:26:01 +02001971 bs->nr_bytes[BDRV_ACCT_READ],
1972 bs->nr_bytes[BDRV_ACCT_WRITE],
1973 bs->nr_ops[BDRV_ACCT_READ],
1974 bs->nr_ops[BDRV_ACCT_WRITE],
Blue Swirl5ffbbc62010-06-14 18:55:33 +00001975 bs->wr_highest_sector *
Christoph Hellwige8045d62011-08-22 00:25:58 +02001976 (uint64_t)BDRV_SECTOR_SIZE,
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001977 bs->nr_ops[BDRV_ACCT_FLUSH],
1978 bs->total_time_ns[BDRV_ACCT_WRITE],
1979 bs->total_time_ns[BDRV_ACCT_READ],
1980 bs->total_time_ns[BDRV_ACCT_FLUSH]);
Kevin Wolf294cc352010-04-28 14:34:01 +02001981 dict = qobject_to_qdict(res);
1982
1983 if (*bs->device_name) {
1984 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1985 }
1986
1987 if (bs->file) {
1988 QObject *parent = bdrv_info_stats_bs(bs->file);
1989 qdict_put_obj(dict, "parent", parent);
1990 }
1991
1992 return res;
1993}
1994
Luiz Capitulino218a5362009-12-10 17:16:07 -02001995void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1996{
1997 QObject *obj;
1998 QList *devices;
thsa36e69d2007-12-02 05:18:19 +00001999 BlockDriverState *bs;
2000
Luiz Capitulino218a5362009-12-10 17:16:07 -02002001 devices = qlist_new();
2002
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002003 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002004 obj = bdrv_info_stats_bs(bs);
Luiz Capitulino218a5362009-12-10 17:16:07 -02002005 qlist_append_obj(devices, obj);
thsa36e69d2007-12-02 05:18:19 +00002006 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02002007
2008 *ret_data = QOBJECT(devices);
thsa36e69d2007-12-02 05:18:19 +00002009}
bellardea2384d2004-08-01 21:59:26 +00002010
aliguori045df332009-03-05 23:00:48 +00002011const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2012{
2013 if (bs->backing_hd && bs->backing_hd->encrypted)
2014 return bs->backing_file;
2015 else if (bs->encrypted)
2016 return bs->filename;
2017 else
2018 return NULL;
2019}
2020
ths5fafdf22007-09-16 21:08:06 +00002021void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00002022 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00002023{
Kevin Wolfb783e402010-01-12 12:55:16 +01002024 if (!bs->backing_file) {
bellard83f64092006-08-01 16:21:11 +00002025 pstrcpy(filename, filename_size, "");
2026 } else {
2027 pstrcpy(filename, filename_size, bs->backing_file);
2028 }
bellardea2384d2004-08-01 21:59:26 +00002029}
2030
ths5fafdf22007-09-16 21:08:06 +00002031int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00002032 const uint8_t *buf, int nb_sectors)
2033{
2034 BlockDriver *drv = bs->drv;
2035 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002036 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002037 if (!drv->bdrv_write_compressed)
2038 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02002039 if (bdrv_check_request(bs, sector_num, nb_sectors))
2040 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002041
Jan Kiszkac6d22832009-11-30 18:21:20 +01002042 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002043 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2044 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002045
bellardfaea38e2006-08-05 21:31:00 +00002046 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2047}
ths3b46e622007-09-17 08:09:54 +00002048
bellardfaea38e2006-08-05 21:31:00 +00002049int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2050{
2051 BlockDriver *drv = bs->drv;
2052 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002053 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002054 if (!drv->bdrv_get_info)
2055 return -ENOTSUP;
2056 memset(bdi, 0, sizeof(*bdi));
2057 return drv->bdrv_get_info(bs, bdi);
2058}
2059
Christoph Hellwig45566e92009-07-10 23:11:57 +02002060int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2061 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002062{
2063 BlockDriver *drv = bs->drv;
2064 if (!drv)
2065 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002066 if (drv->bdrv_save_vmstate)
2067 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2068 if (bs->file)
2069 return bdrv_save_vmstate(bs->file, buf, pos, size);
2070 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002071}
2072
Christoph Hellwig45566e92009-07-10 23:11:57 +02002073int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2074 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002075{
2076 BlockDriver *drv = bs->drv;
2077 if (!drv)
2078 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002079 if (drv->bdrv_load_vmstate)
2080 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2081 if (bs->file)
2082 return bdrv_load_vmstate(bs->file, buf, pos, size);
2083 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002084}
2085
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01002086void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2087{
2088 BlockDriver *drv = bs->drv;
2089
2090 if (!drv || !drv->bdrv_debug_event) {
2091 return;
2092 }
2093
2094 return drv->bdrv_debug_event(bs, event);
2095
2096}
2097
bellardfaea38e2006-08-05 21:31:00 +00002098/**************************************************************/
2099/* handling of snapshots */
2100
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002101int bdrv_can_snapshot(BlockDriverState *bs)
2102{
2103 BlockDriver *drv = bs->drv;
Markus Armbruster07b70bf2011-08-03 15:08:11 +02002104 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002105 return 0;
2106 }
2107
2108 if (!drv->bdrv_snapshot_create) {
2109 if (bs->file != NULL) {
2110 return bdrv_can_snapshot(bs->file);
2111 }
2112 return 0;
2113 }
2114
2115 return 1;
2116}
2117
Blue Swirl199630b2010-07-25 20:49:34 +00002118int bdrv_is_snapshot(BlockDriverState *bs)
2119{
2120 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2121}
2122
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002123BlockDriverState *bdrv_snapshots(void)
2124{
2125 BlockDriverState *bs;
2126
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002127 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002128 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002129 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002130
2131 bs = NULL;
2132 while ((bs = bdrv_next(bs))) {
2133 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002134 bs_snapshots = bs;
2135 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002136 }
2137 }
2138 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002139}
2140
ths5fafdf22007-09-16 21:08:06 +00002141int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002142 QEMUSnapshotInfo *sn_info)
2143{
2144 BlockDriver *drv = bs->drv;
2145 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002146 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002147 if (drv->bdrv_snapshot_create)
2148 return drv->bdrv_snapshot_create(bs, sn_info);
2149 if (bs->file)
2150 return bdrv_snapshot_create(bs->file, sn_info);
2151 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002152}
2153
ths5fafdf22007-09-16 21:08:06 +00002154int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002155 const char *snapshot_id)
2156{
2157 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002158 int ret, open_ret;
2159
bellardfaea38e2006-08-05 21:31:00 +00002160 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002161 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002162 if (drv->bdrv_snapshot_goto)
2163 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2164
2165 if (bs->file) {
2166 drv->bdrv_close(bs);
2167 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2168 open_ret = drv->bdrv_open(bs, bs->open_flags);
2169 if (open_ret < 0) {
2170 bdrv_delete(bs->file);
2171 bs->drv = NULL;
2172 return open_ret;
2173 }
2174 return ret;
2175 }
2176
2177 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002178}
2179
2180int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2181{
2182 BlockDriver *drv = bs->drv;
2183 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002184 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002185 if (drv->bdrv_snapshot_delete)
2186 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2187 if (bs->file)
2188 return bdrv_snapshot_delete(bs->file, snapshot_id);
2189 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002190}
2191
ths5fafdf22007-09-16 21:08:06 +00002192int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002193 QEMUSnapshotInfo **psn_info)
2194{
2195 BlockDriver *drv = bs->drv;
2196 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002197 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002198 if (drv->bdrv_snapshot_list)
2199 return drv->bdrv_snapshot_list(bs, psn_info);
2200 if (bs->file)
2201 return bdrv_snapshot_list(bs->file, psn_info);
2202 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002203}
2204
edison51ef6722010-09-21 19:58:41 -07002205int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2206 const char *snapshot_name)
2207{
2208 BlockDriver *drv = bs->drv;
2209 if (!drv) {
2210 return -ENOMEDIUM;
2211 }
2212 if (!bs->read_only) {
2213 return -EINVAL;
2214 }
2215 if (drv->bdrv_snapshot_load_tmp) {
2216 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2217 }
2218 return -ENOTSUP;
2219}
2220
bellardfaea38e2006-08-05 21:31:00 +00002221#define NB_SUFFIXES 4
2222
2223char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2224{
2225 static const char suffixes[NB_SUFFIXES] = "KMGT";
2226 int64_t base;
2227 int i;
2228
2229 if (size <= 999) {
2230 snprintf(buf, buf_size, "%" PRId64, size);
2231 } else {
2232 base = 1024;
2233 for(i = 0; i < NB_SUFFIXES; i++) {
2234 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00002235 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00002236 (double)size / base,
2237 suffixes[i]);
2238 break;
2239 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00002240 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00002241 ((size + (base >> 1)) / base),
2242 suffixes[i]);
2243 break;
2244 }
2245 base = base * 1024;
2246 }
2247 }
2248 return buf;
2249}
2250
2251char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2252{
2253 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00002254#ifdef _WIN32
2255 struct tm *ptm;
2256#else
bellardfaea38e2006-08-05 21:31:00 +00002257 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00002258#endif
bellardfaea38e2006-08-05 21:31:00 +00002259 time_t ti;
2260 int64_t secs;
2261
2262 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00002263 snprintf(buf, buf_size,
2264 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002265 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2266 } else {
2267 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00002268#ifdef _WIN32
2269 ptm = localtime(&ti);
2270 strftime(date_buf, sizeof(date_buf),
2271 "%Y-%m-%d %H:%M:%S", ptm);
2272#else
bellardfaea38e2006-08-05 21:31:00 +00002273 localtime_r(&ti, &tm);
2274 strftime(date_buf, sizeof(date_buf),
2275 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00002276#endif
bellardfaea38e2006-08-05 21:31:00 +00002277 secs = sn->vm_clock_nsec / 1000000000;
2278 snprintf(clock_buf, sizeof(clock_buf),
2279 "%02d:%02d:%02d.%03d",
2280 (int)(secs / 3600),
2281 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00002282 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00002283 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2284 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00002285 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002286 sn->id_str, sn->name,
2287 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2288 date_buf,
2289 clock_buf);
2290 }
2291 return buf;
2292}
2293
bellard83f64092006-08-01 16:21:11 +00002294/**************************************************************/
2295/* async I/Os */
2296
aliguori3b69e4b2009-01-22 16:59:24 +00002297BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00002298 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00002299 BlockDriverCompletionFunc *cb, void *opaque)
2300{
bellard83f64092006-08-01 16:21:11 +00002301 BlockDriver *drv = bs->drv;
bellard83f64092006-08-01 16:21:11 +00002302
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002303 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2304
bellard19cb3732006-08-19 11:45:59 +00002305 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002306 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002307 if (bdrv_check_request(bs, sector_num, nb_sectors))
2308 return NULL;
ths3b46e622007-09-17 08:09:54 +00002309
Christoph Hellwiga597e792011-08-25 08:26:01 +02002310 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2311 cb, opaque);
bellard83f64092006-08-01 16:21:11 +00002312}
2313
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002314typedef struct BlockCompleteData {
2315 BlockDriverCompletionFunc *cb;
2316 void *opaque;
2317 BlockDriverState *bs;
2318 int64_t sector_num;
2319 int nb_sectors;
2320} BlockCompleteData;
2321
2322static void block_complete_cb(void *opaque, int ret)
2323{
2324 BlockCompleteData *b = opaque;
2325
2326 if (b->bs->dirty_bitmap) {
2327 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2328 }
2329 b->cb(b->opaque, ret);
Anthony Liguori7267c092011-08-20 22:09:37 -05002330 g_free(b);
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002331}
2332
2333static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2334 int64_t sector_num,
2335 int nb_sectors,
2336 BlockDriverCompletionFunc *cb,
2337 void *opaque)
2338{
Anthony Liguori7267c092011-08-20 22:09:37 -05002339 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002340
2341 blkdata->bs = bs;
2342 blkdata->cb = cb;
2343 blkdata->opaque = opaque;
2344 blkdata->sector_num = sector_num;
2345 blkdata->nb_sectors = nb_sectors;
2346
2347 return blkdata;
2348}
2349
aliguorif141eaf2009-04-07 18:43:24 +00002350BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2351 QEMUIOVector *qiov, int nb_sectors,
2352 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002353{
bellard83f64092006-08-01 16:21:11 +00002354 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002355 BlockDriverAIOCB *ret;
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002356 BlockCompleteData *blk_cb_data;
bellard83f64092006-08-01 16:21:11 +00002357
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002358 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2359
bellard19cb3732006-08-19 11:45:59 +00002360 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002361 return NULL;
bellard83f64092006-08-01 16:21:11 +00002362 if (bs->read_only)
pbrookce1a14d2006-08-07 02:38:06 +00002363 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002364 if (bdrv_check_request(bs, sector_num, nb_sectors))
2365 return NULL;
bellard83f64092006-08-01 16:21:11 +00002366
Jan Kiszkac6d22832009-11-30 18:21:20 +01002367 if (bs->dirty_bitmap) {
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002368 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2369 opaque);
2370 cb = &block_complete_cb;
2371 opaque = blk_cb_data;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002372 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002373
aliguorif141eaf2009-04-07 18:43:24 +00002374 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2375 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002376
2377 if (ret) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002378 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2379 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2380 }
thsa36e69d2007-12-02 05:18:19 +00002381 }
2382
2383 return ret;
bellard83f64092006-08-01 16:21:11 +00002384}
2385
Kevin Wolf40b4f532009-09-09 17:53:37 +02002386
2387typedef struct MultiwriteCB {
2388 int error;
2389 int num_requests;
2390 int num_callbacks;
2391 struct {
2392 BlockDriverCompletionFunc *cb;
2393 void *opaque;
2394 QEMUIOVector *free_qiov;
2395 void *free_buf;
2396 } callbacks[];
2397} MultiwriteCB;
2398
2399static void multiwrite_user_cb(MultiwriteCB *mcb)
2400{
2401 int i;
2402
2403 for (i = 0; i < mcb->num_callbacks; i++) {
2404 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01002405 if (mcb->callbacks[i].free_qiov) {
2406 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2407 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002408 g_free(mcb->callbacks[i].free_qiov);
Herve Poussineauf8a83242010-01-24 21:23:56 +00002409 qemu_vfree(mcb->callbacks[i].free_buf);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002410 }
2411}
2412
2413static void multiwrite_cb(void *opaque, int ret)
2414{
2415 MultiwriteCB *mcb = opaque;
2416
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002417 trace_multiwrite_cb(mcb, ret);
2418
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02002419 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02002420 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002421 }
2422
2423 mcb->num_requests--;
2424 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02002425 multiwrite_user_cb(mcb);
Anthony Liguori7267c092011-08-20 22:09:37 -05002426 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002427 }
2428}
2429
2430static int multiwrite_req_compare(const void *a, const void *b)
2431{
Christoph Hellwig77be4362010-05-19 20:53:10 +02002432 const BlockRequest *req1 = a, *req2 = b;
2433
2434 /*
2435 * Note that we can't simply subtract req2->sector from req1->sector
2436 * here as that could overflow the return value.
2437 */
2438 if (req1->sector > req2->sector) {
2439 return 1;
2440 } else if (req1->sector < req2->sector) {
2441 return -1;
2442 } else {
2443 return 0;
2444 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002445}
2446
2447/*
2448 * Takes a bunch of requests and tries to merge them. Returns the number of
2449 * requests that remain after merging.
2450 */
2451static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2452 int num_reqs, MultiwriteCB *mcb)
2453{
2454 int i, outidx;
2455
2456 // Sort requests by start sector
2457 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2458
2459 // Check if adjacent requests touch the same clusters. If so, combine them,
2460 // filling up gaps with zero sectors.
2461 outidx = 0;
2462 for (i = 1; i < num_reqs; i++) {
2463 int merge = 0;
2464 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2465
2466 // This handles the cases that are valid for all block drivers, namely
2467 // exactly sequential writes and overlapping writes.
2468 if (reqs[i].sector <= oldreq_last) {
2469 merge = 1;
2470 }
2471
2472 // The block driver may decide that it makes sense to combine requests
2473 // even if there is a gap of some sectors between them. In this case,
2474 // the gap is filled with zeros (therefore only applicable for yet
2475 // unused space in format like qcow2).
2476 if (!merge && bs->drv->bdrv_merge_requests) {
2477 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2478 }
2479
Christoph Hellwige2a305f2010-01-26 14:49:08 +01002480 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2481 merge = 0;
2482 }
2483
Kevin Wolf40b4f532009-09-09 17:53:37 +02002484 if (merge) {
2485 size_t size;
Anthony Liguori7267c092011-08-20 22:09:37 -05002486 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002487 qemu_iovec_init(qiov,
2488 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2489
2490 // Add the first request to the merged one. If the requests are
2491 // overlapping, drop the last sectors of the first request.
2492 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2493 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2494
2495 // We might need to add some zeros between the two requests
2496 if (reqs[i].sector > oldreq_last) {
2497 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2498 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2499 memset(buf, 0, zero_bytes);
2500 qemu_iovec_add(qiov, buf, zero_bytes);
2501 mcb->callbacks[i].free_buf = buf;
2502 }
2503
2504 // Add the second request
2505 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2506
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02002507 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002508 reqs[outidx].qiov = qiov;
2509
2510 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2511 } else {
2512 outidx++;
2513 reqs[outidx].sector = reqs[i].sector;
2514 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2515 reqs[outidx].qiov = reqs[i].qiov;
2516 }
2517 }
2518
2519 return outidx + 1;
2520}
2521
2522/*
2523 * Submit multiple AIO write requests at once.
2524 *
2525 * On success, the function returns 0 and all requests in the reqs array have
2526 * been submitted. In error case this function returns -1, and any of the
2527 * requests may or may not be submitted yet. In particular, this means that the
2528 * callback will be called for some of the requests, for others it won't. The
2529 * caller must check the error field of the BlockRequest to wait for the right
2530 * callbacks (if error != 0, no callback will be called).
2531 *
2532 * The implementation may modify the contents of the reqs array, e.g. to merge
2533 * requests. However, the fields opaque and error are left unmodified as they
2534 * are used to signal failure for a single request to the caller.
2535 */
2536int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2537{
2538 BlockDriverAIOCB *acb;
2539 MultiwriteCB *mcb;
2540 int i;
2541
Ryan Harper301db7c2011-03-07 10:01:04 -06002542 /* don't submit writes if we don't have a medium */
2543 if (bs->drv == NULL) {
2544 for (i = 0; i < num_reqs; i++) {
2545 reqs[i].error = -ENOMEDIUM;
2546 }
2547 return -1;
2548 }
2549
Kevin Wolf40b4f532009-09-09 17:53:37 +02002550 if (num_reqs == 0) {
2551 return 0;
2552 }
2553
2554 // Create MultiwriteCB structure
Anthony Liguori7267c092011-08-20 22:09:37 -05002555 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002556 mcb->num_requests = 0;
2557 mcb->num_callbacks = num_reqs;
2558
2559 for (i = 0; i < num_reqs; i++) {
2560 mcb->callbacks[i].cb = reqs[i].cb;
2561 mcb->callbacks[i].opaque = reqs[i].opaque;
2562 }
2563
2564 // Check for mergable requests
2565 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2566
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002567 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2568
Kevin Wolf453f9a12010-07-02 14:01:21 +02002569 /*
2570 * Run the aio requests. As soon as one request can't be submitted
2571 * successfully, fail all requests that are not yet submitted (we must
2572 * return failure for all requests anyway)
2573 *
2574 * num_requests cannot be set to the right value immediately: If
2575 * bdrv_aio_writev fails for some request, num_requests would be too high
2576 * and therefore multiwrite_cb() would never recognize the multiwrite
2577 * request as completed. We also cannot use the loop variable i to set it
2578 * when the first request fails because the callback may already have been
2579 * called for previously submitted requests. Thus, num_requests must be
2580 * incremented for each request that is submitted.
2581 *
2582 * The problem that callbacks may be called early also means that we need
2583 * to take care that num_requests doesn't become 0 before all requests are
2584 * submitted - multiwrite_cb() would consider the multiwrite request
2585 * completed. A dummy request that is "completed" by a manual call to
2586 * multiwrite_cb() takes care of this.
2587 */
2588 mcb->num_requests = 1;
2589
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002590 // Run the aio requests
Kevin Wolf40b4f532009-09-09 17:53:37 +02002591 for (i = 0; i < num_reqs; i++) {
Kevin Wolf453f9a12010-07-02 14:01:21 +02002592 mcb->num_requests++;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002593 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2594 reqs[i].nb_sectors, multiwrite_cb, mcb);
2595
2596 if (acb == NULL) {
2597 // We can only fail the whole thing if no request has been
2598 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2599 // complete and report the error in the callback.
Kevin Wolf453f9a12010-07-02 14:01:21 +02002600 if (i == 0) {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002601 trace_bdrv_aio_multiwrite_earlyfail(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002602 goto fail;
2603 } else {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002604 trace_bdrv_aio_multiwrite_latefail(mcb, i);
Kevin Wolf7eb58a62010-04-06 18:24:07 +02002605 multiwrite_cb(mcb, -EIO);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002606 break;
2607 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002608 }
2609 }
2610
Kevin Wolf453f9a12010-07-02 14:01:21 +02002611 /* Complete the dummy request */
2612 multiwrite_cb(mcb, 0);
2613
Kevin Wolf40b4f532009-09-09 17:53:37 +02002614 return 0;
2615
2616fail:
Kevin Wolf453f9a12010-07-02 14:01:21 +02002617 for (i = 0; i < mcb->num_callbacks; i++) {
2618 reqs[i].error = -EIO;
2619 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002620 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002621 return -1;
2622}
2623
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002624BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2625 BlockDriverCompletionFunc *cb, void *opaque)
2626{
2627 BlockDriver *drv = bs->drv;
2628
Stefan Hajnoczia13aac02011-03-07 07:58:04 +00002629 trace_bdrv_aio_flush(bs, opaque);
2630
Alexander Graf016f5cf2010-05-26 17:51:49 +02002631 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2632 return bdrv_aio_noop_em(bs, cb, opaque);
2633 }
2634
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002635 if (!drv)
2636 return NULL;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002637 return drv->bdrv_aio_flush(bs, cb, opaque);
2638}
2639
bellard83f64092006-08-01 16:21:11 +00002640void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00002641{
aliguori6bbff9a2009-03-20 18:25:59 +00002642 acb->pool->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00002643}
2644
pbrookce1a14d2006-08-07 02:38:06 +00002645
bellard83f64092006-08-01 16:21:11 +00002646/**************************************************************/
2647/* async block device emulation */
2648
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002649typedef struct BlockDriverAIOCBSync {
2650 BlockDriverAIOCB common;
2651 QEMUBH *bh;
2652 int ret;
2653 /* vector translation state */
2654 QEMUIOVector *qiov;
2655 uint8_t *bounce;
2656 int is_write;
2657} BlockDriverAIOCBSync;
2658
2659static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2660{
Kevin Wolfb666d232010-05-05 11:44:39 +02002661 BlockDriverAIOCBSync *acb =
2662 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03002663 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002664 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002665 qemu_aio_release(acb);
2666}
2667
2668static AIOPool bdrv_em_aio_pool = {
2669 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2670 .cancel = bdrv_aio_cancel_em,
2671};
2672
bellard83f64092006-08-01 16:21:11 +00002673static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00002674{
pbrookce1a14d2006-08-07 02:38:06 +00002675 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00002676
aliguorif141eaf2009-04-07 18:43:24 +00002677 if (!acb->is_write)
2678 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00002679 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00002680 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03002681 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002682 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00002683 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00002684}
bellardbeac80c2006-06-26 20:08:57 +00002685
aliguorif141eaf2009-04-07 18:43:24 +00002686static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2687 int64_t sector_num,
2688 QEMUIOVector *qiov,
2689 int nb_sectors,
2690 BlockDriverCompletionFunc *cb,
2691 void *opaque,
2692 int is_write)
2693
bellardea2384d2004-08-01 21:59:26 +00002694{
pbrookce1a14d2006-08-07 02:38:06 +00002695 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00002696
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002697 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00002698 acb->is_write = is_write;
2699 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00002700 acb->bounce = qemu_blockalign(bs, qiov->size);
aliguorif141eaf2009-04-07 18:43:24 +00002701
pbrookce1a14d2006-08-07 02:38:06 +00002702 if (!acb->bh)
2703 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00002704
2705 if (is_write) {
2706 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2707 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2708 } else {
2709 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2710 }
2711
pbrookce1a14d2006-08-07 02:38:06 +00002712 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00002713
pbrookce1a14d2006-08-07 02:38:06 +00002714 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00002715}
2716
aliguorif141eaf2009-04-07 18:43:24 +00002717static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2718 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00002719 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002720{
aliguorif141eaf2009-04-07 18:43:24 +00002721 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00002722}
2723
aliguorif141eaf2009-04-07 18:43:24 +00002724static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2725 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2726 BlockDriverCompletionFunc *cb, void *opaque)
2727{
2728 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2729}
2730
Kevin Wolf68485422011-06-30 10:05:46 +02002731
2732typedef struct BlockDriverAIOCBCoroutine {
2733 BlockDriverAIOCB common;
2734 BlockRequest req;
2735 bool is_write;
2736 QEMUBH* bh;
2737} BlockDriverAIOCBCoroutine;
2738
2739static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2740{
2741 qemu_aio_flush();
2742}
2743
2744static AIOPool bdrv_em_co_aio_pool = {
2745 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2746 .cancel = bdrv_aio_co_cancel_em,
2747};
2748
2749static void bdrv_co_rw_bh(void *opaque)
2750{
2751 BlockDriverAIOCBCoroutine *acb = opaque;
2752
2753 acb->common.cb(acb->common.opaque, acb->req.error);
2754 qemu_bh_delete(acb->bh);
2755 qemu_aio_release(acb);
2756}
2757
2758static void coroutine_fn bdrv_co_rw(void *opaque)
2759{
2760 BlockDriverAIOCBCoroutine *acb = opaque;
2761 BlockDriverState *bs = acb->common.bs;
2762
2763 if (!acb->is_write) {
2764 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2765 acb->req.nb_sectors, acb->req.qiov);
2766 } else {
2767 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2768 acb->req.nb_sectors, acb->req.qiov);
2769 }
2770
2771 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2772 qemu_bh_schedule(acb->bh);
2773}
2774
2775static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2776 int64_t sector_num,
2777 QEMUIOVector *qiov,
2778 int nb_sectors,
2779 BlockDriverCompletionFunc *cb,
2780 void *opaque,
2781 bool is_write)
2782{
2783 Coroutine *co;
2784 BlockDriverAIOCBCoroutine *acb;
2785
2786 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2787 acb->req.sector = sector_num;
2788 acb->req.nb_sectors = nb_sectors;
2789 acb->req.qiov = qiov;
2790 acb->is_write = is_write;
2791
2792 co = qemu_coroutine_create(bdrv_co_rw);
2793 qemu_coroutine_enter(co, acb);
2794
2795 return &acb->common;
2796}
2797
2798static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2799 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2800 BlockDriverCompletionFunc *cb, void *opaque)
2801{
2802 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2803 false);
2804}
2805
2806static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2807 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2808 BlockDriverCompletionFunc *cb, void *opaque)
2809{
2810 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2811 true);
2812}
2813
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002814static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2815 BlockDriverCompletionFunc *cb, void *opaque)
2816{
2817 BlockDriverAIOCBSync *acb;
2818
2819 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2820 acb->is_write = 1; /* don't bounce in the completion hadler */
2821 acb->qiov = NULL;
2822 acb->bounce = NULL;
2823 acb->ret = 0;
2824
2825 if (!acb->bh)
2826 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2827
2828 bdrv_flush(bs);
2829 qemu_bh_schedule(acb->bh);
2830 return &acb->common;
2831}
2832
Alexander Graf016f5cf2010-05-26 17:51:49 +02002833static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2834 BlockDriverCompletionFunc *cb, void *opaque)
2835{
2836 BlockDriverAIOCBSync *acb;
2837
2838 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2839 acb->is_write = 1; /* don't bounce in the completion handler */
2840 acb->qiov = NULL;
2841 acb->bounce = NULL;
2842 acb->ret = 0;
2843
2844 if (!acb->bh) {
2845 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2846 }
2847
2848 qemu_bh_schedule(acb->bh);
2849 return &acb->common;
2850}
2851
bellard83f64092006-08-01 16:21:11 +00002852/**************************************************************/
2853/* sync block device emulation */
2854
2855static void bdrv_rw_em_cb(void *opaque, int ret)
2856{
2857 *(int *)opaque = ret;
2858}
2859
2860#define NOT_DONE 0x7fffffff
2861
ths5fafdf22007-09-16 21:08:06 +00002862static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +00002863 uint8_t *buf, int nb_sectors)
2864{
pbrookce1a14d2006-08-07 02:38:06 +00002865 int async_ret;
2866 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002867 struct iovec iov;
2868 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002869
bellard83f64092006-08-01 16:21:11 +00002870 async_ret = NOT_DONE;
blueswir13f4cb3d2009-04-13 16:31:01 +00002871 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002872 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002873 qemu_iovec_init_external(&qiov, &iov, 1);
2874 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2875 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002876 if (acb == NULL) {
2877 async_ret = -1;
2878 goto fail;
2879 }
aliguoribaf35cb2008-09-10 15:45:19 +00002880
bellard83f64092006-08-01 16:21:11 +00002881 while (async_ret == NOT_DONE) {
2882 qemu_aio_wait();
2883 }
aliguoribaf35cb2008-09-10 15:45:19 +00002884
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002885
2886fail:
bellard83f64092006-08-01 16:21:11 +00002887 return async_ret;
2888}
2889
2890static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2891 const uint8_t *buf, int nb_sectors)
2892{
pbrookce1a14d2006-08-07 02:38:06 +00002893 int async_ret;
2894 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002895 struct iovec iov;
2896 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002897
bellard83f64092006-08-01 16:21:11 +00002898 async_ret = NOT_DONE;
aliguorif141eaf2009-04-07 18:43:24 +00002899 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002900 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002901 qemu_iovec_init_external(&qiov, &iov, 1);
2902 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2903 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002904 if (acb == NULL) {
2905 async_ret = -1;
2906 goto fail;
2907 }
bellard83f64092006-08-01 16:21:11 +00002908 while (async_ret == NOT_DONE) {
2909 qemu_aio_wait();
2910 }
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002911
2912fail:
bellard83f64092006-08-01 16:21:11 +00002913 return async_ret;
2914}
bellardea2384d2004-08-01 21:59:26 +00002915
2916void bdrv_init(void)
2917{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05002918 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00002919}
pbrookce1a14d2006-08-07 02:38:06 +00002920
Markus Armbrustereb852012009-10-27 18:41:44 +01002921void bdrv_init_with_whitelist(void)
2922{
2923 use_bdrv_whitelist = 1;
2924 bdrv_init();
2925}
2926
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002927void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2928 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00002929{
pbrookce1a14d2006-08-07 02:38:06 +00002930 BlockDriverAIOCB *acb;
2931
aliguori6bbff9a2009-03-20 18:25:59 +00002932 if (pool->free_aiocb) {
2933 acb = pool->free_aiocb;
2934 pool->free_aiocb = acb->next;
pbrookce1a14d2006-08-07 02:38:06 +00002935 } else {
Anthony Liguori7267c092011-08-20 22:09:37 -05002936 acb = g_malloc0(pool->aiocb_size);
aliguori6bbff9a2009-03-20 18:25:59 +00002937 acb->pool = pool;
pbrookce1a14d2006-08-07 02:38:06 +00002938 }
2939 acb->bs = bs;
2940 acb->cb = cb;
2941 acb->opaque = opaque;
2942 return acb;
2943}
2944
2945void qemu_aio_release(void *p)
2946{
aliguori6bbff9a2009-03-20 18:25:59 +00002947 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2948 AIOPool *pool = acb->pool;
2949 acb->next = pool->free_aiocb;
2950 pool->free_aiocb = acb;
pbrookce1a14d2006-08-07 02:38:06 +00002951}
bellard19cb3732006-08-19 11:45:59 +00002952
2953/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02002954/* Coroutine block device emulation */
2955
2956typedef struct CoroutineIOCompletion {
2957 Coroutine *coroutine;
2958 int ret;
2959} CoroutineIOCompletion;
2960
2961static void bdrv_co_io_em_complete(void *opaque, int ret)
2962{
2963 CoroutineIOCompletion *co = opaque;
2964
2965 co->ret = ret;
2966 qemu_coroutine_enter(co->coroutine, NULL);
2967}
2968
2969static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2970 int nb_sectors, QEMUIOVector *iov,
2971 bool is_write)
2972{
2973 CoroutineIOCompletion co = {
2974 .coroutine = qemu_coroutine_self(),
2975 };
2976 BlockDriverAIOCB *acb;
2977
2978 if (is_write) {
2979 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2980 bdrv_co_io_em_complete, &co);
2981 } else {
2982 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2983 bdrv_co_io_em_complete, &co);
2984 }
2985
2986 trace_bdrv_co_io(is_write, acb);
2987 if (!acb) {
2988 return -EIO;
2989 }
2990 qemu_coroutine_yield();
2991
2992 return co.ret;
2993}
2994
2995static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2996 int64_t sector_num, int nb_sectors,
2997 QEMUIOVector *iov)
2998{
2999 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3000}
3001
3002static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3003 int64_t sector_num, int nb_sectors,
3004 QEMUIOVector *iov)
3005{
3006 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3007}
3008
Kevin Wolfe7a8a782011-07-15 16:05:00 +02003009static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3010{
3011 CoroutineIOCompletion co = {
3012 .coroutine = qemu_coroutine_self(),
3013 };
3014 BlockDriverAIOCB *acb;
3015
3016 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3017 if (!acb) {
3018 return -EIO;
3019 }
3020 qemu_coroutine_yield();
3021 return co.ret;
3022}
3023
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003024/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00003025/* removable device support */
3026
3027/**
3028 * Return TRUE if the media is present
3029 */
3030int bdrv_is_inserted(BlockDriverState *bs)
3031{
3032 BlockDriver *drv = bs->drv;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003033
bellard19cb3732006-08-19 11:45:59 +00003034 if (!drv)
3035 return 0;
3036 if (!drv->bdrv_is_inserted)
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003037 return 1;
3038 return drv->bdrv_is_inserted(bs);
bellard19cb3732006-08-19 11:45:59 +00003039}
3040
3041/**
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003042 * Return whether the media changed since the last call to this
3043 * function, or -ENOTSUP if we don't know. Most drivers don't know.
bellard19cb3732006-08-19 11:45:59 +00003044 */
3045int bdrv_media_changed(BlockDriverState *bs)
3046{
3047 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003048
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003049 if (drv && drv->bdrv_media_changed) {
3050 return drv->bdrv_media_changed(bs);
3051 }
3052 return -ENOTSUP;
bellard19cb3732006-08-19 11:45:59 +00003053}
3054
3055/**
3056 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3057 */
Markus Armbrusterfdec4402011-09-06 18:58:45 +02003058void bdrv_eject(BlockDriverState *bs, int eject_flag)
bellard19cb3732006-08-19 11:45:59 +00003059{
3060 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003061
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003062 if (drv && drv->bdrv_eject) {
3063 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00003064 }
bellard19cb3732006-08-19 11:45:59 +00003065}
3066
bellard19cb3732006-08-19 11:45:59 +00003067/**
3068 * Lock or unlock the media (if it is locked, the user won't be able
3069 * to eject it manually).
3070 */
Markus Armbruster025e8492011-09-06 18:58:47 +02003071void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00003072{
3073 BlockDriver *drv = bs->drv;
3074
Markus Armbruster025e8492011-09-06 18:58:47 +02003075 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01003076
Markus Armbruster025e8492011-09-06 18:58:47 +02003077 if (drv && drv->bdrv_lock_medium) {
3078 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00003079 }
3080}
ths985a03b2007-12-24 16:10:43 +00003081
3082/* needed for generic scsi interface */
3083
3084int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3085{
3086 BlockDriver *drv = bs->drv;
3087
3088 if (drv && drv->bdrv_ioctl)
3089 return drv->bdrv_ioctl(bs, req, buf);
3090 return -ENOTSUP;
3091}
aliguori7d780662009-03-12 19:57:08 +00003092
aliguori221f7152009-03-28 17:28:41 +00003093BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3094 unsigned long int req, void *buf,
3095 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00003096{
aliguori221f7152009-03-28 17:28:41 +00003097 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00003098
aliguori221f7152009-03-28 17:28:41 +00003099 if (drv && drv->bdrv_aio_ioctl)
3100 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3101 return NULL;
aliguori7d780662009-03-12 19:57:08 +00003102}
aliguorie268ca52009-04-22 20:20:00 +00003103
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003104
3105
aliguorie268ca52009-04-22 20:20:00 +00003106void *qemu_blockalign(BlockDriverState *bs, size_t size)
3107{
3108 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3109}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003110
3111void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3112{
3113 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003114
Liran Schouraaa0eb72010-01-26 10:31:48 +02003115 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003116 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003117 if (!bs->dirty_bitmap) {
3118 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3119 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3120 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003121
Anthony Liguori7267c092011-08-20 22:09:37 -05003122 bs->dirty_bitmap = g_malloc0(bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003123 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003124 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003125 if (bs->dirty_bitmap) {
Anthony Liguori7267c092011-08-20 22:09:37 -05003126 g_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01003127 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003128 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003129 }
3130}
3131
3132int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3133{
Jan Kiszka6ea44302009-11-30 18:21:19 +01003134 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003135
Jan Kiszkac6d22832009-11-30 18:21:20 +01003136 if (bs->dirty_bitmap &&
3137 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02003138 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3139 (1UL << (chunk % (sizeof(unsigned long) * 8))));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003140 } else {
3141 return 0;
3142 }
3143}
3144
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003145void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3146 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003147{
3148 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3149}
Liran Schouraaa0eb72010-01-26 10:31:48 +02003150
3151int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3152{
3153 return bs->dirty_count;
3154}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003155
Marcelo Tosattidb593f22011-01-26 12:12:34 -02003156void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3157{
3158 assert(bs->in_use != in_use);
3159 bs->in_use = in_use;
3160}
3161
3162int bdrv_in_use(BlockDriverState *bs)
3163{
3164 return bs->in_use;
3165}
3166
Christoph Hellwiga597e792011-08-25 08:26:01 +02003167void
3168bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3169 enum BlockAcctType type)
3170{
3171 assert(type < BDRV_MAX_IOTYPE);
3172
3173 cookie->bytes = bytes;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003174 cookie->start_time_ns = get_clock();
Christoph Hellwiga597e792011-08-25 08:26:01 +02003175 cookie->type = type;
3176}
3177
3178void
3179bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3180{
3181 assert(cookie->type < BDRV_MAX_IOTYPE);
3182
3183 bs->nr_bytes[cookie->type] += cookie->bytes;
3184 bs->nr_ops[cookie->type]++;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003185 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
Christoph Hellwiga597e792011-08-25 08:26:01 +02003186}
3187
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003188int bdrv_img_create(const char *filename, const char *fmt,
3189 const char *base_filename, const char *base_fmt,
3190 char *options, uint64_t img_size, int flags)
3191{
3192 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02003193 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003194 BlockDriverState *bs = NULL;
3195 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003196 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003197 int ret = 0;
3198
3199 /* Find driver and parse its options */
3200 drv = bdrv_find_format(fmt);
3201 if (!drv) {
3202 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003203 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003204 goto out;
3205 }
3206
3207 proto_drv = bdrv_find_protocol(filename);
3208 if (!proto_drv) {
3209 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003210 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003211 goto out;
3212 }
3213
3214 create_options = append_option_parameters(create_options,
3215 drv->create_options);
3216 create_options = append_option_parameters(create_options,
3217 proto_drv->create_options);
3218
3219 /* Create parameter list with default values */
3220 param = parse_option_parameters("", create_options, param);
3221
3222 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3223
3224 /* Parse -o options */
3225 if (options) {
3226 param = parse_option_parameters(options, create_options, param);
3227 if (param == NULL) {
3228 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003229 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003230 goto out;
3231 }
3232 }
3233
3234 if (base_filename) {
3235 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3236 base_filename)) {
3237 error_report("Backing file not supported for file format '%s'",
3238 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003239 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003240 goto out;
3241 }
3242 }
3243
3244 if (base_fmt) {
3245 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3246 error_report("Backing file format not supported for file "
3247 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003248 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003249 goto out;
3250 }
3251 }
3252
Jes Sorensen792da932010-12-16 13:52:17 +01003253 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3254 if (backing_file && backing_file->value.s) {
3255 if (!strcmp(filename, backing_file->value.s)) {
3256 error_report("Error: Trying to create an image with the "
3257 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003258 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01003259 goto out;
3260 }
3261 }
3262
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003263 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3264 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003265 backing_drv = bdrv_find_format(backing_fmt->value.s);
3266 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003267 error_report("Unknown backing file format '%s'",
3268 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003269 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003270 goto out;
3271 }
3272 }
3273
3274 // The size for the image must always be specified, with one exception:
3275 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02003276 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3277 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003278 if (backing_file && backing_file->value.s) {
3279 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003280 char buf[32];
3281
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003282 bs = bdrv_new("");
3283
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003284 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003285 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003286 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003287 goto out;
3288 }
3289 bdrv_get_geometry(bs, &size);
3290 size *= 512;
3291
3292 snprintf(buf, sizeof(buf), "%" PRId64, size);
3293 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3294 } else {
3295 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003296 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003297 goto out;
3298 }
3299 }
3300
3301 printf("Formatting '%s', fmt=%s ", filename, fmt);
3302 print_option_parameters(param);
3303 puts("");
3304
3305 ret = bdrv_create(drv, filename, param);
3306
3307 if (ret < 0) {
3308 if (ret == -ENOTSUP) {
3309 error_report("Formatting or formatting option not supported for "
3310 "file format '%s'", fmt);
3311 } else if (ret == -EFBIG) {
3312 error_report("The image size is too large for file format '%s'",
3313 fmt);
3314 } else {
3315 error_report("%s: error while creating %s: %s", filename, fmt,
3316 strerror(-ret));
3317 }
3318 }
3319
3320out:
3321 free_option_parameters(create_options);
3322 free_option_parameters(param);
3323
3324 if (bs) {
3325 bdrv_delete(bs);
3326 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01003327
3328 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003329}