blob: e3fe97f27533ce3f2919a8cff97bba21ce41e362 [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 Armbruster7d4b4ba2011-09-06 18:58:59 +020047static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
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;
Kevin Wolf57915332010-04-14 15:24:50 +0200483 bs->buffer_alignment = 512;
484
485 pstrcpy(bs->filename, sizeof(bs->filename), filename);
486
487 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
488 return -ENOTSUP;
489 }
490
491 bs->drv = drv;
Anthony Liguori7267c092011-08-20 22:09:37 -0500492 bs->opaque = g_malloc0(drv->instance_size);
Kevin Wolf57915332010-04-14 15:24:50 +0200493
Christoph Hellwiga6599792011-05-17 18:04:06 +0200494 if (flags & BDRV_O_CACHE_WB)
Kevin Wolf57915332010-04-14 15:24:50 +0200495 bs->enable_write_cache = 1;
496
497 /*
498 * Clear flags that are internal to the block layer before opening the
499 * image.
500 */
501 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
502
503 /*
Stefan Weilebabb672011-04-26 10:29:36 +0200504 * Snapshots should be writable.
Kevin Wolf57915332010-04-14 15:24:50 +0200505 */
506 if (bs->is_temporary) {
507 open_flags |= BDRV_O_RDWR;
508 }
509
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200510 /* Open the image, either directly or using a protocol */
511 if (drv->bdrv_file_open) {
512 ret = drv->bdrv_file_open(bs, filename, open_flags);
513 } else {
514 ret = bdrv_file_open(&bs->file, filename, open_flags);
515 if (ret >= 0) {
516 ret = drv->bdrv_open(bs, open_flags);
517 }
518 }
519
Kevin Wolf57915332010-04-14 15:24:50 +0200520 if (ret < 0) {
521 goto free_and_fail;
522 }
523
524 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100525
526 ret = refresh_total_sectors(bs, bs->total_sectors);
527 if (ret < 0) {
528 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200529 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100530
Kevin Wolf57915332010-04-14 15:24:50 +0200531#ifndef _WIN32
532 if (bs->is_temporary) {
533 unlink(filename);
534 }
535#endif
536 return 0;
537
538free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200539 if (bs->file) {
540 bdrv_delete(bs->file);
541 bs->file = NULL;
542 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500543 g_free(bs->opaque);
Kevin Wolf57915332010-04-14 15:24:50 +0200544 bs->opaque = NULL;
545 bs->drv = NULL;
546 return ret;
547}
548
549/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200550 * Opens a file using a protocol (file, host_device, nbd, ...)
551 */
bellard83f64092006-08-01 16:21:11 +0000552int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000553{
bellard83f64092006-08-01 16:21:11 +0000554 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200555 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000556 int ret;
557
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900558 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200559 if (!drv) {
560 return -ENOENT;
561 }
562
bellard83f64092006-08-01 16:21:11 +0000563 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200564 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000565 if (ret < 0) {
566 bdrv_delete(bs);
567 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000568 }
aliguori71d07702009-03-03 17:37:16 +0000569 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000570 *pbs = bs;
571 return 0;
bellardea2384d2004-08-01 21:59:26 +0000572}
bellardfc01f7e2003-06-30 10:03:06 +0000573
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200574/*
575 * Opens a disk image (raw, qcow2, vmdk, ...)
576 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200577int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
578 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000579{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200580 int ret;
bellard712e7872005-04-28 21:09:32 +0000581
bellard83f64092006-08-01 16:21:11 +0000582 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000583 BlockDriverState *bs1;
584 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000585 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200586 BlockDriver *bdrv_qcow2;
587 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200588 char tmp_filename[PATH_MAX];
589 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000590
bellardea2384d2004-08-01 21:59:26 +0000591 /* if snapshot, we create a temporary backing file and open it
592 instead of opening 'filename' directly */
593
594 /* if there is a backing file, use it */
595 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200596 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000597 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000598 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000599 return ret;
bellardea2384d2004-08-01 21:59:26 +0000600 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200601 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000602
603 if (bs1->drv && bs1->drv->protocol_name)
604 is_protocol = 1;
605
bellardea2384d2004-08-01 21:59:26 +0000606 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000607
bellardea2384d2004-08-01 21:59:26 +0000608 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
aliguori7c96d462008-09-12 17:54:13 +0000609
610 /* Real path is meaningless for protocols */
611 if (is_protocol)
612 snprintf(backing_filename, sizeof(backing_filename),
613 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000614 else if (!realpath(filename, backing_filename))
615 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000616
Kevin Wolf91a073a2009-05-27 14:48:06 +0200617 bdrv_qcow2 = bdrv_find_format("qcow2");
618 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
619
Jes Sorensen3e829902010-05-27 16:20:30 +0200620 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200621 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
622 if (drv) {
623 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
624 drv->format_name);
625 }
626
627 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200628 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000629 if (ret < 0) {
630 return ret;
bellardea2384d2004-08-01 21:59:26 +0000631 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200632
bellardea2384d2004-08-01 21:59:26 +0000633 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200634 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000635 bs->is_temporary = 1;
636 }
bellard712e7872005-04-28 21:09:32 +0000637
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200638 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200639 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200640 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000641 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100642
aliguori51d7c002009-03-05 23:00:29 +0000643 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000644 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000645 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200646
647 /* Open the image */
648 ret = bdrv_open_common(bs, filename, flags, drv);
649 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100650 goto unlink_and_fail;
651 }
652
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200653 /* If there is a backing file, use it */
654 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
655 char backing_filename[PATH_MAX];
656 int back_flags;
657 BlockDriver *back_drv = NULL;
658
659 bs->backing_hd = bdrv_new("");
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000660
661 if (path_has_protocol(bs->backing_file)) {
662 pstrcpy(backing_filename, sizeof(backing_filename),
663 bs->backing_file);
664 } else {
665 path_combine(backing_filename, sizeof(backing_filename),
666 filename, bs->backing_file);
667 }
668
669 if (bs->backing_format[0] != '\0') {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200670 back_drv = bdrv_find_format(bs->backing_format);
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000671 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200672
673 /* backing files always opened read-only */
674 back_flags =
675 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
676
677 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
678 if (ret < 0) {
679 bdrv_close(bs);
680 return ret;
681 }
682 if (bs->is_temporary) {
683 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
684 } else {
685 /* base image inherits from "parent" */
686 bs->backing_hd->keep_read_only = bs->keep_read_only;
687 }
688 }
689
690 if (!bdrv_key_required(bs)) {
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200691 bdrv_dev_change_media_cb(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200692 }
693
694 return 0;
695
696unlink_and_fail:
697 if (bs->is_temporary) {
698 unlink(filename);
699 }
700 return ret;
701}
702
bellardfc01f7e2003-06-30 10:03:06 +0000703void bdrv_close(BlockDriverState *bs)
704{
bellard19cb3732006-08-19 11:45:59 +0000705 if (bs->drv) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200706 if (bs == bs_snapshots) {
707 bs_snapshots = NULL;
708 }
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100709 if (bs->backing_hd) {
bellardea2384d2004-08-01 21:59:26 +0000710 bdrv_delete(bs->backing_hd);
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100711 bs->backing_hd = NULL;
712 }
bellardea2384d2004-08-01 21:59:26 +0000713 bs->drv->bdrv_close(bs);
Anthony Liguori7267c092011-08-20 22:09:37 -0500714 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +0000715#ifdef _WIN32
716 if (bs->is_temporary) {
717 unlink(bs->filename);
718 }
bellard67b915a2004-03-31 23:37:16 +0000719#endif
bellardea2384d2004-08-01 21:59:26 +0000720 bs->opaque = NULL;
721 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +0000722
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200723 if (bs->file != NULL) {
724 bdrv_close(bs->file);
725 }
726
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200727 bdrv_dev_change_media_cb(bs, false);
bellardb3380822004-03-14 21:38:54 +0000728 }
729}
730
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +0900731void bdrv_close_all(void)
732{
733 BlockDriverState *bs;
734
735 QTAILQ_FOREACH(bs, &bdrv_states, list) {
736 bdrv_close(bs);
737 }
738}
739
Ryan Harperd22b2f42011-03-29 20:51:47 -0500740/* make a BlockDriverState anonymous by removing from bdrv_state list.
741 Also, NULL terminate the device_name to prevent double remove */
742void bdrv_make_anon(BlockDriverState *bs)
743{
744 if (bs->device_name[0] != '\0') {
745 QTAILQ_REMOVE(&bdrv_states, bs, list);
746 }
747 bs->device_name[0] = '\0';
748}
749
bellardb3380822004-03-14 21:38:54 +0000750void bdrv_delete(BlockDriverState *bs)
751{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200752 assert(!bs->dev);
Markus Armbruster18846de2010-06-29 16:58:30 +0200753
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100754 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -0500755 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +0000756
bellardb3380822004-03-14 21:38:54 +0000757 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200758 if (bs->file != NULL) {
759 bdrv_delete(bs->file);
760 }
761
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200762 assert(bs != bs_snapshots);
Anthony Liguori7267c092011-08-20 22:09:37 -0500763 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +0000764}
765
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200766int bdrv_attach_dev(BlockDriverState *bs, void *dev)
767/* TODO change to DeviceState *dev when all users are qdevified */
Markus Armbruster18846de2010-06-29 16:58:30 +0200768{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200769 if (bs->dev) {
Markus Armbruster18846de2010-06-29 16:58:30 +0200770 return -EBUSY;
771 }
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200772 bs->dev = dev;
Markus Armbruster18846de2010-06-29 16:58:30 +0200773 return 0;
774}
775
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200776/* TODO qdevified devices don't use this, remove when devices are qdevified */
777void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
Markus Armbruster18846de2010-06-29 16:58:30 +0200778{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200779 if (bdrv_attach_dev(bs, dev) < 0) {
780 abort();
781 }
782}
783
784void bdrv_detach_dev(BlockDriverState *bs, void *dev)
785/* TODO change to DeviceState *dev when all users are qdevified */
786{
787 assert(bs->dev == dev);
788 bs->dev = NULL;
Markus Armbruster0e49de52011-08-03 15:07:41 +0200789 bs->dev_ops = NULL;
790 bs->dev_opaque = NULL;
Markus Armbruster29e05f22011-09-06 18:58:57 +0200791 bs->buffer_alignment = 512;
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 Armbruster7d4b4ba2011-09-06 18:58:59 +0200810static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
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) {
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200813 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
Markus Armbruster145feb12011-08-03 15:07:42 +0200814 }
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 Armbrustere4def802011-09-06 18:58:53 +0200822bool bdrv_dev_is_tray_open(BlockDriverState *bs)
823{
824 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
825 return bs->dev_ops->is_tray_open(bs->dev_opaque);
826 }
827 return false;
828}
829
Markus Armbruster145feb12011-08-03 15:07:42 +0200830static void bdrv_dev_resize_cb(BlockDriverState *bs)
831{
832 if (bs->dev_ops && bs->dev_ops->resize_cb) {
833 bs->dev_ops->resize_cb(bs->dev_opaque);
Markus Armbruster0e49de52011-08-03 15:07:41 +0200834 }
835}
836
Markus Armbrusterf1076392011-09-06 18:58:46 +0200837bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
838{
839 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
840 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
841 }
842 return false;
843}
844
aliguorie97fc192009-04-21 23:11:50 +0000845/*
846 * Run consistency checks on an image
847 *
Kevin Wolfe076f332010-06-29 11:43:13 +0200848 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +0200849 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +0200850 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +0000851 */
Kevin Wolfe076f332010-06-29 11:43:13 +0200852int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
aliguorie97fc192009-04-21 23:11:50 +0000853{
854 if (bs->drv->bdrv_check == NULL) {
855 return -ENOTSUP;
856 }
857
Kevin Wolfe076f332010-06-29 11:43:13 +0200858 memset(res, 0, sizeof(*res));
Kevin Wolf9ac228e2010-06-29 12:37:54 +0200859 return bs->drv->bdrv_check(bs, res);
aliguorie97fc192009-04-21 23:11:50 +0000860}
861
Kevin Wolf8a426612010-07-16 17:17:01 +0200862#define COMMIT_BUF_SECTORS 2048
863
bellard33e39632003-07-06 17:15:21 +0000864/* commit COW file into the raw image */
865int bdrv_commit(BlockDriverState *bs)
866{
bellard19cb3732006-08-19 11:45:59 +0000867 BlockDriver *drv = bs->drv;
Kevin Wolfee181192010-08-05 13:05:22 +0200868 BlockDriver *backing_drv;
Kevin Wolf8a426612010-07-16 17:17:01 +0200869 int64_t sector, total_sectors;
870 int n, ro, open_flags;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200871 int ret = 0, rw_ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +0200872 uint8_t *buf;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200873 char filename[1024];
874 BlockDriverState *bs_rw, *bs_ro;
bellard33e39632003-07-06 17:15:21 +0000875
bellard19cb3732006-08-19 11:45:59 +0000876 if (!drv)
877 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200878
879 if (!bs->backing_hd) {
880 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +0000881 }
882
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200883 if (bs->backing_hd->keep_read_only) {
884 return -EACCES;
885 }
Kevin Wolfee181192010-08-05 13:05:22 +0200886
887 backing_drv = bs->backing_hd->drv;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200888 ro = bs->backing_hd->read_only;
889 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
890 open_flags = bs->backing_hd->open_flags;
891
892 if (ro) {
893 /* re-open as RW */
894 bdrv_delete(bs->backing_hd);
895 bs->backing_hd = NULL;
896 bs_rw = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200897 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
898 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200899 if (rw_ret < 0) {
900 bdrv_delete(bs_rw);
901 /* try to re-open read-only */
902 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200903 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
904 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200905 if (ret < 0) {
906 bdrv_delete(bs_ro);
907 /* drive not functional anymore */
908 bs->drv = NULL;
909 return ret;
910 }
911 bs->backing_hd = bs_ro;
912 return rw_ret;
913 }
914 bs->backing_hd = bs_rw;
bellard33e39632003-07-06 17:15:21 +0000915 }
bellardea2384d2004-08-01 21:59:26 +0000916
Jan Kiszka6ea44302009-11-30 18:21:19 +0100917 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Anthony Liguori7267c092011-08-20 22:09:37 -0500918 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +0000919
Kevin Wolf8a426612010-07-16 17:17:01 +0200920 for (sector = 0; sector < total_sectors; sector += n) {
921 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
922
923 if (bdrv_read(bs, sector, buf, n) != 0) {
924 ret = -EIO;
925 goto ro_cleanup;
926 }
927
928 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
929 ret = -EIO;
930 goto ro_cleanup;
931 }
bellardea2384d2004-08-01 21:59:26 +0000932 }
933 }
bellard95389c82005-12-18 18:28:15 +0000934
Christoph Hellwig1d449522010-01-17 12:32:30 +0100935 if (drv->bdrv_make_empty) {
936 ret = drv->bdrv_make_empty(bs);
937 bdrv_flush(bs);
938 }
bellard95389c82005-12-18 18:28:15 +0000939
Christoph Hellwig3f5075a2010-01-12 13:49:23 +0100940 /*
941 * Make sure all data we wrote to the backing device is actually
942 * stable on disk.
943 */
944 if (bs->backing_hd)
945 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200946
947ro_cleanup:
Anthony Liguori7267c092011-08-20 22:09:37 -0500948 g_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200949
950 if (ro) {
951 /* re-open as RO */
952 bdrv_delete(bs->backing_hd);
953 bs->backing_hd = NULL;
954 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200955 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
956 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200957 if (ret < 0) {
958 bdrv_delete(bs_ro);
959 /* drive not functional anymore */
960 bs->drv = NULL;
961 return ret;
962 }
963 bs->backing_hd = bs_ro;
964 bs->backing_hd->keep_read_only = 0;
965 }
966
Christoph Hellwig1d449522010-01-17 12:32:30 +0100967 return ret;
bellard33e39632003-07-06 17:15:21 +0000968}
969
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +0200970void bdrv_commit_all(void)
971{
972 BlockDriverState *bs;
973
974 QTAILQ_FOREACH(bs, &bdrv_states, list) {
975 bdrv_commit(bs);
976 }
977}
978
Kevin Wolf756e6732010-01-12 12:55:17 +0100979/*
980 * Return values:
981 * 0 - success
982 * -EINVAL - backing format specified, but no file
983 * -ENOSPC - can't update the backing file because no space is left in the
984 * image file header
985 * -ENOTSUP - format driver doesn't support changing the backing file
986 */
987int bdrv_change_backing_file(BlockDriverState *bs,
988 const char *backing_file, const char *backing_fmt)
989{
990 BlockDriver *drv = bs->drv;
991
992 if (drv->bdrv_change_backing_file != NULL) {
993 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
994 } else {
995 return -ENOTSUP;
996 }
997}
998
aliguori71d07702009-03-03 17:37:16 +0000999static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1000 size_t size)
1001{
1002 int64_t len;
1003
1004 if (!bdrv_is_inserted(bs))
1005 return -ENOMEDIUM;
1006
1007 if (bs->growable)
1008 return 0;
1009
1010 len = bdrv_getlength(bs);
1011
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02001012 if (offset < 0)
1013 return -EIO;
1014
1015 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +00001016 return -EIO;
1017
1018 return 0;
1019}
1020
1021static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1022 int nb_sectors)
1023{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001024 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1025 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +00001026}
1027
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001028static inline bool bdrv_has_async_rw(BlockDriver *drv)
1029{
1030 return drv->bdrv_co_readv != bdrv_co_readv_em
1031 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1032}
1033
1034static inline bool bdrv_has_async_flush(BlockDriver *drv)
1035{
1036 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1037}
1038
bellard19cb3732006-08-19 11:45:59 +00001039/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +00001040int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001041 uint8_t *buf, int nb_sectors)
1042{
bellardea2384d2004-08-01 21:59:26 +00001043 BlockDriver *drv = bs->drv;
1044
bellard19cb3732006-08-19 11:45:59 +00001045 if (!drv)
1046 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001047
1048 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1049 QEMUIOVector qiov;
1050 struct iovec iov = {
1051 .iov_base = (void *)buf,
1052 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1053 };
1054
1055 qemu_iovec_init_external(&qiov, &iov, 1);
1056 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1057 }
1058
aliguori71d07702009-03-03 17:37:16 +00001059 if (bdrv_check_request(bs, sector_num, nb_sectors))
1060 return -EIO;
bellardb3380822004-03-14 21:38:54 +00001061
aliguorieda578e2009-03-12 19:57:16 +00001062 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
bellardfc01f7e2003-06-30 10:03:06 +00001063}
1064
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001065static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001066 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001067{
1068 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001069 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001070
Jan Kiszka6ea44302009-11-30 18:21:19 +01001071 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001072 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001073
1074 for (; start <= end; start++) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01001075 idx = start / (sizeof(unsigned long) * 8);
1076 bit = start % (sizeof(unsigned long) * 8);
1077 val = bs->dirty_bitmap[idx];
1078 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001079 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001080 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001081 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +02001082 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001083 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001084 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001085 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001086 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +02001087 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001088 }
1089 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001090 }
1091}
1092
ths5fafdf22007-09-16 21:08:06 +00001093/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +00001094 -EIO generic I/O error (may happen for all errors)
1095 -ENOMEDIUM No media inserted.
1096 -EINVAL Invalid sector number or nb_sectors
1097 -EACCES Trying to write a read-only device
1098*/
ths5fafdf22007-09-16 21:08:06 +00001099int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001100 const uint8_t *buf, int nb_sectors)
1101{
bellard83f64092006-08-01 16:21:11 +00001102 BlockDriver *drv = bs->drv;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001103
bellard19cb3732006-08-19 11:45:59 +00001104 if (!bs->drv)
1105 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001106
1107 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1108 QEMUIOVector qiov;
1109 struct iovec iov = {
1110 .iov_base = (void *)buf,
1111 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1112 };
1113
1114 qemu_iovec_init_external(&qiov, &iov, 1);
1115 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1116 }
1117
bellard0849bf02003-06-30 23:17:31 +00001118 if (bs->read_only)
bellard19cb3732006-08-19 11:45:59 +00001119 return -EACCES;
aliguori71d07702009-03-03 17:37:16 +00001120 if (bdrv_check_request(bs, sector_num, nb_sectors))
1121 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001122
Jan Kiszkac6d22832009-11-30 18:21:20 +01001123 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001124 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1125 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001126
Kevin Wolf294cc352010-04-28 14:34:01 +02001127 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1128 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1129 }
1130
aliguori42fb2802009-01-15 20:43:39 +00001131 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
bellard83f64092006-08-01 16:21:11 +00001132}
1133
aliguorieda578e2009-03-12 19:57:16 +00001134int bdrv_pread(BlockDriverState *bs, int64_t offset,
1135 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001136{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001137 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001138 int len, nb_sectors, count;
1139 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001140 int ret;
bellard83f64092006-08-01 16:21:11 +00001141
1142 count = count1;
1143 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001144 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001145 if (len > count)
1146 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001147 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001148 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001149 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1150 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001151 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00001152 count -= len;
1153 if (count == 0)
1154 return count1;
1155 sector_num++;
1156 buf += len;
1157 }
1158
1159 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001160 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001161 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001162 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1163 return ret;
bellard83f64092006-08-01 16:21:11 +00001164 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001165 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001166 buf += len;
1167 count -= len;
1168 }
1169
1170 /* add data from the last sector */
1171 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001172 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1173 return ret;
bellard83f64092006-08-01 16:21:11 +00001174 memcpy(buf, tmp_buf, count);
1175 }
1176 return count1;
1177}
1178
aliguorieda578e2009-03-12 19:57:16 +00001179int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1180 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001181{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001182 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001183 int len, nb_sectors, count;
1184 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001185 int ret;
bellard83f64092006-08-01 16:21:11 +00001186
1187 count = count1;
1188 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001189 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001190 if (len > count)
1191 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001192 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001193 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001194 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1195 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001196 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001197 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1198 return ret;
bellard83f64092006-08-01 16:21:11 +00001199 count -= len;
1200 if (count == 0)
1201 return count1;
1202 sector_num++;
1203 buf += len;
1204 }
1205
1206 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001207 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001208 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001209 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1210 return ret;
bellard83f64092006-08-01 16:21:11 +00001211 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001212 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001213 buf += len;
1214 count -= len;
1215 }
1216
1217 /* add data from the last sector */
1218 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001219 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1220 return ret;
bellard83f64092006-08-01 16:21:11 +00001221 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001222 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1223 return ret;
bellard83f64092006-08-01 16:21:11 +00001224 }
1225 return count1;
1226}
bellard83f64092006-08-01 16:21:11 +00001227
Kevin Wolff08145f2010-06-16 16:38:15 +02001228/*
1229 * Writes to the file and ensures that no writes are reordered across this
1230 * request (acts as a barrier)
1231 *
1232 * Returns 0 on success, -errno in error cases.
1233 */
1234int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1235 const void *buf, int count)
1236{
1237 int ret;
1238
1239 ret = bdrv_pwrite(bs, offset, buf, count);
1240 if (ret < 0) {
1241 return ret;
1242 }
1243
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001244 /* No flush needed for cache modes that use O_DSYNC */
1245 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
Kevin Wolff08145f2010-06-16 16:38:15 +02001246 bdrv_flush(bs);
1247 }
1248
1249 return 0;
1250}
1251
Kevin Wolfda1fa912011-07-14 17:27:13 +02001252int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1253 int nb_sectors, QEMUIOVector *qiov)
1254{
1255 BlockDriver *drv = bs->drv;
1256
1257 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1258
1259 if (!drv) {
1260 return -ENOMEDIUM;
1261 }
1262 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1263 return -EIO;
1264 }
1265
1266 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1267}
1268
1269int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1270 int nb_sectors, QEMUIOVector *qiov)
1271{
1272 BlockDriver *drv = bs->drv;
1273
1274 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1275
1276 if (!bs->drv) {
1277 return -ENOMEDIUM;
1278 }
1279 if (bs->read_only) {
1280 return -EACCES;
1281 }
1282 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1283 return -EIO;
1284 }
1285
1286 if (bs->dirty_bitmap) {
1287 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1288 }
1289
1290 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1291 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1292 }
1293
1294 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1295}
1296
bellard83f64092006-08-01 16:21:11 +00001297/**
bellard83f64092006-08-01 16:21:11 +00001298 * Truncate file to 'offset' bytes (needed only for file protocols)
1299 */
1300int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1301{
1302 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001303 int ret;
bellard83f64092006-08-01 16:21:11 +00001304 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001305 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00001306 if (!drv->bdrv_truncate)
1307 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02001308 if (bs->read_only)
1309 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02001310 if (bdrv_in_use(bs))
1311 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001312 ret = drv->bdrv_truncate(bs, offset);
1313 if (ret == 0) {
1314 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Markus Armbruster145feb12011-08-03 15:07:42 +02001315 bdrv_dev_resize_cb(bs);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001316 }
1317 return ret;
bellard83f64092006-08-01 16:21:11 +00001318}
1319
1320/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08001321 * Length of a allocated file in bytes. Sparse files are counted by actual
1322 * allocated space. Return < 0 if error or unknown.
1323 */
1324int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1325{
1326 BlockDriver *drv = bs->drv;
1327 if (!drv) {
1328 return -ENOMEDIUM;
1329 }
1330 if (drv->bdrv_get_allocated_file_size) {
1331 return drv->bdrv_get_allocated_file_size(bs);
1332 }
1333 if (bs->file) {
1334 return bdrv_get_allocated_file_size(bs->file);
1335 }
1336 return -ENOTSUP;
1337}
1338
1339/**
bellard83f64092006-08-01 16:21:11 +00001340 * Length of a file in bytes. Return < 0 if error or unknown.
1341 */
1342int64_t bdrv_getlength(BlockDriverState *bs)
1343{
1344 BlockDriver *drv = bs->drv;
1345 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001346 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001347
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001348 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001349 if (drv->bdrv_getlength) {
1350 return drv->bdrv_getlength(bs);
1351 }
bellard83f64092006-08-01 16:21:11 +00001352 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001353 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00001354}
1355
bellard19cb3732006-08-19 11:45:59 +00001356/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00001357void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00001358{
bellard19cb3732006-08-19 11:45:59 +00001359 int64_t length;
1360 length = bdrv_getlength(bs);
1361 if (length < 0)
1362 length = 0;
1363 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01001364 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00001365 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00001366}
bellardcf989512004-02-16 21:56:36 +00001367
aliguorif3d54fc2008-11-25 21:50:24 +00001368struct partition {
1369 uint8_t boot_ind; /* 0x80 - active */
1370 uint8_t head; /* starting head */
1371 uint8_t sector; /* starting sector */
1372 uint8_t cyl; /* starting cylinder */
1373 uint8_t sys_ind; /* What partition type */
1374 uint8_t end_head; /* end head */
1375 uint8_t end_sector; /* end sector */
1376 uint8_t end_cyl; /* end cylinder */
1377 uint32_t start_sect; /* starting sector counting from 0 */
1378 uint32_t nr_sects; /* nr of sectors in partition */
Stefan Weil541dc0d2011-08-31 12:38:01 +02001379} QEMU_PACKED;
aliguorif3d54fc2008-11-25 21:50:24 +00001380
1381/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1382static int guess_disk_lchs(BlockDriverState *bs,
1383 int *pcylinders, int *pheads, int *psectors)
1384{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001385 uint8_t buf[BDRV_SECTOR_SIZE];
aliguorif3d54fc2008-11-25 21:50:24 +00001386 int ret, i, heads, sectors, cylinders;
1387 struct partition *p;
1388 uint32_t nr_sects;
blueswir1a38131b2008-12-05 17:56:40 +00001389 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001390
1391 bdrv_get_geometry(bs, &nb_sectors);
1392
1393 ret = bdrv_read(bs, 0, buf, 1);
1394 if (ret < 0)
1395 return -1;
1396 /* test msdos magic */
1397 if (buf[510] != 0x55 || buf[511] != 0xaa)
1398 return -1;
1399 for(i = 0; i < 4; i++) {
1400 p = ((struct partition *)(buf + 0x1be)) + i;
1401 nr_sects = le32_to_cpu(p->nr_sects);
1402 if (nr_sects && p->end_head) {
1403 /* We make the assumption that the partition terminates on
1404 a cylinder boundary */
1405 heads = p->end_head + 1;
1406 sectors = p->end_sector & 63;
1407 if (sectors == 0)
1408 continue;
1409 cylinders = nb_sectors / (heads * sectors);
1410 if (cylinders < 1 || cylinders > 16383)
1411 continue;
1412 *pheads = heads;
1413 *psectors = sectors;
1414 *pcylinders = cylinders;
1415#if 0
1416 printf("guessed geometry: LCHS=%d %d %d\n",
1417 cylinders, heads, sectors);
1418#endif
1419 return 0;
1420 }
1421 }
1422 return -1;
1423}
1424
1425void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1426{
1427 int translation, lba_detected = 0;
1428 int cylinders, heads, secs;
blueswir1a38131b2008-12-05 17:56:40 +00001429 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001430
1431 /* if a geometry hint is available, use it */
1432 bdrv_get_geometry(bs, &nb_sectors);
1433 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1434 translation = bdrv_get_translation_hint(bs);
1435 if (cylinders != 0) {
1436 *pcyls = cylinders;
1437 *pheads = heads;
1438 *psecs = secs;
1439 } else {
1440 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1441 if (heads > 16) {
1442 /* if heads > 16, it means that a BIOS LBA
1443 translation was active, so the default
1444 hardware geometry is OK */
1445 lba_detected = 1;
1446 goto default_geometry;
1447 } else {
1448 *pcyls = cylinders;
1449 *pheads = heads;
1450 *psecs = secs;
1451 /* disable any translation to be in sync with
1452 the logical geometry */
1453 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1454 bdrv_set_translation_hint(bs,
1455 BIOS_ATA_TRANSLATION_NONE);
1456 }
1457 }
1458 } else {
1459 default_geometry:
1460 /* if no geometry, use a standard physical disk geometry */
1461 cylinders = nb_sectors / (16 * 63);
1462
1463 if (cylinders > 16383)
1464 cylinders = 16383;
1465 else if (cylinders < 2)
1466 cylinders = 2;
1467 *pcyls = cylinders;
1468 *pheads = 16;
1469 *psecs = 63;
1470 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1471 if ((*pcyls * *pheads) <= 131072) {
1472 bdrv_set_translation_hint(bs,
1473 BIOS_ATA_TRANSLATION_LARGE);
1474 } else {
1475 bdrv_set_translation_hint(bs,
1476 BIOS_ATA_TRANSLATION_LBA);
1477 }
1478 }
1479 }
1480 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1481 }
1482}
1483
ths5fafdf22007-09-16 21:08:06 +00001484void bdrv_set_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001485 int cyls, int heads, int secs)
1486{
1487 bs->cyls = cyls;
1488 bs->heads = heads;
1489 bs->secs = secs;
1490}
1491
bellard46d47672004-11-16 01:45:27 +00001492void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1493{
1494 bs->translation = translation;
1495}
1496
ths5fafdf22007-09-16 21:08:06 +00001497void bdrv_get_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001498 int *pcyls, int *pheads, int *psecs)
1499{
1500 *pcyls = bs->cyls;
1501 *pheads = bs->heads;
1502 *psecs = bs->secs;
1503}
1504
Blue Swirl5bbdbb42011-02-12 20:43:32 +00001505/* Recognize floppy formats */
1506typedef struct FDFormat {
1507 FDriveType drive;
1508 uint8_t last_sect;
1509 uint8_t max_track;
1510 uint8_t max_head;
1511} FDFormat;
1512
1513static const FDFormat fd_formats[] = {
1514 /* First entry is default format */
1515 /* 1.44 MB 3"1/2 floppy disks */
1516 { FDRIVE_DRV_144, 18, 80, 1, },
1517 { FDRIVE_DRV_144, 20, 80, 1, },
1518 { FDRIVE_DRV_144, 21, 80, 1, },
1519 { FDRIVE_DRV_144, 21, 82, 1, },
1520 { FDRIVE_DRV_144, 21, 83, 1, },
1521 { FDRIVE_DRV_144, 22, 80, 1, },
1522 { FDRIVE_DRV_144, 23, 80, 1, },
1523 { FDRIVE_DRV_144, 24, 80, 1, },
1524 /* 2.88 MB 3"1/2 floppy disks */
1525 { FDRIVE_DRV_288, 36, 80, 1, },
1526 { FDRIVE_DRV_288, 39, 80, 1, },
1527 { FDRIVE_DRV_288, 40, 80, 1, },
1528 { FDRIVE_DRV_288, 44, 80, 1, },
1529 { FDRIVE_DRV_288, 48, 80, 1, },
1530 /* 720 kB 3"1/2 floppy disks */
1531 { FDRIVE_DRV_144, 9, 80, 1, },
1532 { FDRIVE_DRV_144, 10, 80, 1, },
1533 { FDRIVE_DRV_144, 10, 82, 1, },
1534 { FDRIVE_DRV_144, 10, 83, 1, },
1535 { FDRIVE_DRV_144, 13, 80, 1, },
1536 { FDRIVE_DRV_144, 14, 80, 1, },
1537 /* 1.2 MB 5"1/4 floppy disks */
1538 { FDRIVE_DRV_120, 15, 80, 1, },
1539 { FDRIVE_DRV_120, 18, 80, 1, },
1540 { FDRIVE_DRV_120, 18, 82, 1, },
1541 { FDRIVE_DRV_120, 18, 83, 1, },
1542 { FDRIVE_DRV_120, 20, 80, 1, },
1543 /* 720 kB 5"1/4 floppy disks */
1544 { FDRIVE_DRV_120, 9, 80, 1, },
1545 { FDRIVE_DRV_120, 11, 80, 1, },
1546 /* 360 kB 5"1/4 floppy disks */
1547 { FDRIVE_DRV_120, 9, 40, 1, },
1548 { FDRIVE_DRV_120, 9, 40, 0, },
1549 { FDRIVE_DRV_120, 10, 41, 1, },
1550 { FDRIVE_DRV_120, 10, 42, 1, },
1551 /* 320 kB 5"1/4 floppy disks */
1552 { FDRIVE_DRV_120, 8, 40, 1, },
1553 { FDRIVE_DRV_120, 8, 40, 0, },
1554 /* 360 kB must match 5"1/4 better than 3"1/2... */
1555 { FDRIVE_DRV_144, 9, 80, 0, },
1556 /* end */
1557 { FDRIVE_DRV_NONE, -1, -1, 0, },
1558};
1559
1560void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1561 int *max_track, int *last_sect,
1562 FDriveType drive_in, FDriveType *drive)
1563{
1564 const FDFormat *parse;
1565 uint64_t nb_sectors, size;
1566 int i, first_match, match;
1567
1568 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1569 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1570 /* User defined disk */
1571 } else {
1572 bdrv_get_geometry(bs, &nb_sectors);
1573 match = -1;
1574 first_match = -1;
1575 for (i = 0; ; i++) {
1576 parse = &fd_formats[i];
1577 if (parse->drive == FDRIVE_DRV_NONE) {
1578 break;
1579 }
1580 if (drive_in == parse->drive ||
1581 drive_in == FDRIVE_DRV_NONE) {
1582 size = (parse->max_head + 1) * parse->max_track *
1583 parse->last_sect;
1584 if (nb_sectors == size) {
1585 match = i;
1586 break;
1587 }
1588 if (first_match == -1) {
1589 first_match = i;
1590 }
1591 }
1592 }
1593 if (match == -1) {
1594 if (first_match == -1) {
1595 match = 1;
1596 } else {
1597 match = first_match;
1598 }
1599 parse = &fd_formats[match];
1600 }
1601 *nb_heads = parse->max_head + 1;
1602 *max_track = parse->max_track;
1603 *last_sect = parse->last_sect;
1604 *drive = parse->drive;
1605 }
1606}
1607
bellard46d47672004-11-16 01:45:27 +00001608int bdrv_get_translation_hint(BlockDriverState *bs)
1609{
1610 return bs->translation;
1611}
1612
Markus Armbrusterabd7f682010-06-02 18:55:17 +02001613void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1614 BlockErrorAction on_write_error)
1615{
1616 bs->on_read_error = on_read_error;
1617 bs->on_write_error = on_write_error;
1618}
1619
1620BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1621{
1622 return is_read ? bs->on_read_error : bs->on_write_error;
1623}
1624
bellardb3380822004-03-14 21:38:54 +00001625int bdrv_is_read_only(BlockDriverState *bs)
1626{
1627 return bs->read_only;
1628}
1629
ths985a03b2007-12-24 16:10:43 +00001630int bdrv_is_sg(BlockDriverState *bs)
1631{
1632 return bs->sg;
1633}
1634
Christoph Hellwige900a7b2009-09-04 19:01:15 +02001635int bdrv_enable_write_cache(BlockDriverState *bs)
1636{
1637 return bs->enable_write_cache;
1638}
1639
bellardea2384d2004-08-01 21:59:26 +00001640int bdrv_is_encrypted(BlockDriverState *bs)
1641{
1642 if (bs->backing_hd && bs->backing_hd->encrypted)
1643 return 1;
1644 return bs->encrypted;
1645}
1646
aliguoric0f4ce72009-03-05 23:01:01 +00001647int bdrv_key_required(BlockDriverState *bs)
1648{
1649 BlockDriverState *backing_hd = bs->backing_hd;
1650
1651 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1652 return 1;
1653 return (bs->encrypted && !bs->valid_key);
1654}
1655
bellardea2384d2004-08-01 21:59:26 +00001656int bdrv_set_key(BlockDriverState *bs, const char *key)
1657{
1658 int ret;
1659 if (bs->backing_hd && bs->backing_hd->encrypted) {
1660 ret = bdrv_set_key(bs->backing_hd, key);
1661 if (ret < 0)
1662 return ret;
1663 if (!bs->encrypted)
1664 return 0;
1665 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02001666 if (!bs->encrypted) {
1667 return -EINVAL;
1668 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1669 return -ENOMEDIUM;
1670 }
aliguoric0f4ce72009-03-05 23:01:01 +00001671 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00001672 if (ret < 0) {
1673 bs->valid_key = 0;
1674 } else if (!bs->valid_key) {
1675 bs->valid_key = 1;
1676 /* call the change callback now, we skipped it on open */
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +02001677 bdrv_dev_change_media_cb(bs, true);
aliguoribb5fc202009-03-05 23:01:15 +00001678 }
aliguoric0f4ce72009-03-05 23:01:01 +00001679 return ret;
bellardea2384d2004-08-01 21:59:26 +00001680}
1681
1682void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1683{
bellard19cb3732006-08-19 11:45:59 +00001684 if (!bs->drv) {
bellardea2384d2004-08-01 21:59:26 +00001685 buf[0] = '\0';
1686 } else {
1687 pstrcpy(buf, buf_size, bs->drv->format_name);
1688 }
1689}
1690
ths5fafdf22007-09-16 21:08:06 +00001691void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00001692 void *opaque)
1693{
1694 BlockDriver *drv;
1695
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01001696 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00001697 it(opaque, drv->format_name);
1698 }
1699}
1700
bellardb3380822004-03-14 21:38:54 +00001701BlockDriverState *bdrv_find(const char *name)
1702{
1703 BlockDriverState *bs;
1704
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001705 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1706 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00001707 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001708 }
bellardb3380822004-03-14 21:38:54 +00001709 }
1710 return NULL;
1711}
1712
Markus Armbruster2f399b02010-06-02 18:55:20 +02001713BlockDriverState *bdrv_next(BlockDriverState *bs)
1714{
1715 if (!bs) {
1716 return QTAILQ_FIRST(&bdrv_states);
1717 }
1718 return QTAILQ_NEXT(bs, list);
1719}
1720
aliguori51de9762009-03-05 23:00:43 +00001721void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00001722{
1723 BlockDriverState *bs;
1724
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001725 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00001726 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00001727 }
1728}
1729
bellardea2384d2004-08-01 21:59:26 +00001730const char *bdrv_get_device_name(BlockDriverState *bs)
1731{
1732 return bs->device_name;
1733}
1734
Kevin Wolf205ef792010-10-21 16:43:43 +02001735int bdrv_flush(BlockDriverState *bs)
pbrook7a6cba62006-06-04 11:39:07 +00001736{
Alexander Graf016f5cf2010-05-26 17:51:49 +02001737 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolf205ef792010-10-21 16:43:43 +02001738 return 0;
Alexander Graf016f5cf2010-05-26 17:51:49 +02001739 }
1740
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001741 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1742 return bdrv_co_flush_em(bs);
1743 }
1744
Kevin Wolf205ef792010-10-21 16:43:43 +02001745 if (bs->drv && bs->drv->bdrv_flush) {
1746 return bs->drv->bdrv_flush(bs);
1747 }
1748
1749 /*
1750 * Some block drivers always operate in either writethrough or unsafe mode
1751 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1752 * the server works (because the behaviour is hardcoded or depends on
1753 * server-side configuration), so we can't ensure that everything is safe
1754 * on disk. Returning an error doesn't work because that would break guests
1755 * even if the server operates in writethrough mode.
1756 *
1757 * Let's hope the user knows what he's doing.
1758 */
1759 return 0;
pbrook7a6cba62006-06-04 11:39:07 +00001760}
1761
aliguoric6ca28d2008-10-06 13:55:43 +00001762void bdrv_flush_all(void)
1763{
1764 BlockDriverState *bs;
1765
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001766 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Markus Armbrusterc602a482011-08-03 15:08:10 +02001767 if (!bdrv_is_read_only(bs) && bdrv_is_inserted(bs)) {
aliguoric6ca28d2008-10-06 13:55:43 +00001768 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001769 }
1770 }
aliguoric6ca28d2008-10-06 13:55:43 +00001771}
1772
Kevin Wolff2feebb2010-04-14 17:30:35 +02001773int bdrv_has_zero_init(BlockDriverState *bs)
1774{
1775 assert(bs->drv);
1776
Kevin Wolf336c1c12010-07-28 11:26:29 +02001777 if (bs->drv->bdrv_has_zero_init) {
1778 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02001779 }
1780
1781 return 1;
1782}
1783
Christoph Hellwigbb8bf762010-12-16 19:36:31 +01001784int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1785{
1786 if (!bs->drv) {
1787 return -ENOMEDIUM;
1788 }
1789 if (!bs->drv->bdrv_discard) {
1790 return 0;
1791 }
1792 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1793}
1794
thsf58c7b32008-06-05 21:53:49 +00001795/*
1796 * Returns true iff the specified sector is present in the disk image. Drivers
1797 * not implementing the functionality are assumed to not support backing files,
1798 * hence all their sectors are reported as allocated.
1799 *
1800 * 'pnum' is set to the number of sectors (including and immediately following
1801 * the specified sector) that are known to be in the same
1802 * allocated/unallocated state.
1803 *
1804 * 'nb_sectors' is the max value 'pnum' should be set to.
1805 */
1806int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1807 int *pnum)
1808{
1809 int64_t n;
1810 if (!bs->drv->bdrv_is_allocated) {
1811 if (sector_num >= bs->total_sectors) {
1812 *pnum = 0;
1813 return 0;
1814 }
1815 n = bs->total_sectors - sector_num;
1816 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1817 return 1;
1818 }
1819 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1820}
1821
Luiz Capitulino2582bfe2010-02-03 12:41:01 -02001822void bdrv_mon_event(const BlockDriverState *bdrv,
1823 BlockMonEventAction action, int is_read)
1824{
1825 QObject *data;
1826 const char *action_str;
1827
1828 switch (action) {
1829 case BDRV_ACTION_REPORT:
1830 action_str = "report";
1831 break;
1832 case BDRV_ACTION_IGNORE:
1833 action_str = "ignore";
1834 break;
1835 case BDRV_ACTION_STOP:
1836 action_str = "stop";
1837 break;
1838 default:
1839 abort();
1840 }
1841
1842 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1843 bdrv->device_name,
1844 action_str,
1845 is_read ? "read" : "write");
1846 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1847
1848 qobject_decref(data);
1849}
1850
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001851static void bdrv_print_dict(QObject *obj, void *opaque)
bellardb3380822004-03-14 21:38:54 +00001852{
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001853 QDict *bs_dict;
1854 Monitor *mon = opaque;
1855
1856 bs_dict = qobject_to_qdict(obj);
1857
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001858 monitor_printf(mon, "%s: removable=%d",
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001859 qdict_get_str(bs_dict, "device"),
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001860 qdict_get_bool(bs_dict, "removable"));
1861
1862 if (qdict_get_bool(bs_dict, "removable")) {
1863 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
Markus Armbrustere4def802011-09-06 18:58:53 +02001864 monitor_printf(mon, " tray-open=%d",
1865 qdict_get_bool(bs_dict, "tray-open"));
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001866 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001867 if (qdict_haskey(bs_dict, "inserted")) {
1868 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1869
1870 monitor_printf(mon, " file=");
1871 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1872 if (qdict_haskey(qdict, "backing_file")) {
1873 monitor_printf(mon, " backing_file=");
1874 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1875 }
1876 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1877 qdict_get_bool(qdict, "ro"),
1878 qdict_get_str(qdict, "drv"),
1879 qdict_get_bool(qdict, "encrypted"));
1880 } else {
1881 monitor_printf(mon, " [not inserted]");
1882 }
1883
1884 monitor_printf(mon, "\n");
1885}
1886
1887void bdrv_info_print(Monitor *mon, const QObject *data)
1888{
1889 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1890}
1891
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001892void bdrv_info(Monitor *mon, QObject **ret_data)
1893{
1894 QList *bs_list;
bellardb3380822004-03-14 21:38:54 +00001895 BlockDriverState *bs;
1896
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001897 bs_list = qlist_new();
1898
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001899 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001900 QObject *bs_obj;
Markus Armbrustere4def802011-09-06 18:58:53 +02001901 QDict *bs_dict;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001902
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001903 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001904 "'removable': %i, 'locked': %i }",
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001905 bs->device_name,
1906 bdrv_dev_has_removable_media(bs),
Markus Armbrusterf1076392011-09-06 18:58:46 +02001907 bdrv_dev_is_medium_locked(bs));
Markus Armbrustere4def802011-09-06 18:58:53 +02001908 bs_dict = qobject_to_qdict(bs_obj);
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001909
Markus Armbrustere4def802011-09-06 18:58:53 +02001910 if (bdrv_dev_has_removable_media(bs)) {
1911 qdict_put(bs_dict, "tray-open",
1912 qbool_from_int(bdrv_dev_is_tray_open(bs)));
1913 }
bellard19cb3732006-08-19 11:45:59 +00001914 if (bs->drv) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001915 QObject *obj;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001916
1917 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1918 "'encrypted': %i }",
1919 bs->filename, bs->read_only,
1920 bs->drv->format_name,
1921 bdrv_is_encrypted(bs));
thsfef30742006-12-22 14:11:32 +00001922 if (bs->backing_file[0] != '\0') {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001923 QDict *qdict = qobject_to_qdict(obj);
1924 qdict_put(qdict, "backing_file",
1925 qstring_from_str(bs->backing_file));
aliguori376253e2009-03-05 23:01:23 +00001926 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001927
1928 qdict_put_obj(bs_dict, "inserted", obj);
bellardb3380822004-03-14 21:38:54 +00001929 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001930 qlist_append_obj(bs_list, bs_obj);
bellardb3380822004-03-14 21:38:54 +00001931 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001932
1933 *ret_data = QOBJECT(bs_list);
bellardb3380822004-03-14 21:38:54 +00001934}
thsa36e69d2007-12-02 05:18:19 +00001935
Luiz Capitulino218a5362009-12-10 17:16:07 -02001936static void bdrv_stats_iter(QObject *data, void *opaque)
thsa36e69d2007-12-02 05:18:19 +00001937{
Luiz Capitulino218a5362009-12-10 17:16:07 -02001938 QDict *qdict;
1939 Monitor *mon = opaque;
1940
1941 qdict = qobject_to_qdict(data);
1942 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1943
1944 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1945 monitor_printf(mon, " rd_bytes=%" PRId64
1946 " wr_bytes=%" PRId64
1947 " rd_operations=%" PRId64
1948 " wr_operations=%" PRId64
Christoph Hellwige8045d62011-08-22 00:25:58 +02001949 " flush_operations=%" PRId64
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001950 " wr_total_time_ns=%" PRId64
1951 " rd_total_time_ns=%" PRId64
1952 " flush_total_time_ns=%" PRId64
Luiz Capitulino218a5362009-12-10 17:16:07 -02001953 "\n",
1954 qdict_get_int(qdict, "rd_bytes"),
1955 qdict_get_int(qdict, "wr_bytes"),
1956 qdict_get_int(qdict, "rd_operations"),
Christoph Hellwige8045d62011-08-22 00:25:58 +02001957 qdict_get_int(qdict, "wr_operations"),
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001958 qdict_get_int(qdict, "flush_operations"),
1959 qdict_get_int(qdict, "wr_total_time_ns"),
1960 qdict_get_int(qdict, "rd_total_time_ns"),
1961 qdict_get_int(qdict, "flush_total_time_ns"));
Luiz Capitulino218a5362009-12-10 17:16:07 -02001962}
1963
1964void bdrv_stats_print(Monitor *mon, const QObject *data)
1965{
1966 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1967}
1968
Kevin Wolf294cc352010-04-28 14:34:01 +02001969static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1970{
1971 QObject *res;
1972 QDict *dict;
1973
1974 res = qobject_from_jsonf("{ 'stats': {"
1975 "'rd_bytes': %" PRId64 ","
1976 "'wr_bytes': %" PRId64 ","
1977 "'rd_operations': %" PRId64 ","
1978 "'wr_operations': %" PRId64 ","
Christoph Hellwige8045d62011-08-22 00:25:58 +02001979 "'wr_highest_offset': %" PRId64 ","
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001980 "'flush_operations': %" PRId64 ","
1981 "'wr_total_time_ns': %" PRId64 ","
1982 "'rd_total_time_ns': %" PRId64 ","
1983 "'flush_total_time_ns': %" PRId64
Kevin Wolf294cc352010-04-28 14:34:01 +02001984 "} }",
Christoph Hellwiga597e792011-08-25 08:26:01 +02001985 bs->nr_bytes[BDRV_ACCT_READ],
1986 bs->nr_bytes[BDRV_ACCT_WRITE],
1987 bs->nr_ops[BDRV_ACCT_READ],
1988 bs->nr_ops[BDRV_ACCT_WRITE],
Blue Swirl5ffbbc62010-06-14 18:55:33 +00001989 bs->wr_highest_sector *
Christoph Hellwige8045d62011-08-22 00:25:58 +02001990 (uint64_t)BDRV_SECTOR_SIZE,
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001991 bs->nr_ops[BDRV_ACCT_FLUSH],
1992 bs->total_time_ns[BDRV_ACCT_WRITE],
1993 bs->total_time_ns[BDRV_ACCT_READ],
1994 bs->total_time_ns[BDRV_ACCT_FLUSH]);
Kevin Wolf294cc352010-04-28 14:34:01 +02001995 dict = qobject_to_qdict(res);
1996
1997 if (*bs->device_name) {
1998 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1999 }
2000
2001 if (bs->file) {
2002 QObject *parent = bdrv_info_stats_bs(bs->file);
2003 qdict_put_obj(dict, "parent", parent);
2004 }
2005
2006 return res;
2007}
2008
Luiz Capitulino218a5362009-12-10 17:16:07 -02002009void bdrv_info_stats(Monitor *mon, QObject **ret_data)
2010{
2011 QObject *obj;
2012 QList *devices;
thsa36e69d2007-12-02 05:18:19 +00002013 BlockDriverState *bs;
2014
Luiz Capitulino218a5362009-12-10 17:16:07 -02002015 devices = qlist_new();
2016
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002017 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002018 obj = bdrv_info_stats_bs(bs);
Luiz Capitulino218a5362009-12-10 17:16:07 -02002019 qlist_append_obj(devices, obj);
thsa36e69d2007-12-02 05:18:19 +00002020 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02002021
2022 *ret_data = QOBJECT(devices);
thsa36e69d2007-12-02 05:18:19 +00002023}
bellardea2384d2004-08-01 21:59:26 +00002024
aliguori045df332009-03-05 23:00:48 +00002025const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2026{
2027 if (bs->backing_hd && bs->backing_hd->encrypted)
2028 return bs->backing_file;
2029 else if (bs->encrypted)
2030 return bs->filename;
2031 else
2032 return NULL;
2033}
2034
ths5fafdf22007-09-16 21:08:06 +00002035void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00002036 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00002037{
Kevin Wolfb783e402010-01-12 12:55:16 +01002038 if (!bs->backing_file) {
bellard83f64092006-08-01 16:21:11 +00002039 pstrcpy(filename, filename_size, "");
2040 } else {
2041 pstrcpy(filename, filename_size, bs->backing_file);
2042 }
bellardea2384d2004-08-01 21:59:26 +00002043}
2044
ths5fafdf22007-09-16 21:08:06 +00002045int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00002046 const uint8_t *buf, int nb_sectors)
2047{
2048 BlockDriver *drv = bs->drv;
2049 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002050 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002051 if (!drv->bdrv_write_compressed)
2052 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02002053 if (bdrv_check_request(bs, sector_num, nb_sectors))
2054 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002055
Jan Kiszkac6d22832009-11-30 18:21:20 +01002056 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002057 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2058 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002059
bellardfaea38e2006-08-05 21:31:00 +00002060 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2061}
ths3b46e622007-09-17 08:09:54 +00002062
bellardfaea38e2006-08-05 21:31:00 +00002063int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2064{
2065 BlockDriver *drv = bs->drv;
2066 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002067 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002068 if (!drv->bdrv_get_info)
2069 return -ENOTSUP;
2070 memset(bdi, 0, sizeof(*bdi));
2071 return drv->bdrv_get_info(bs, bdi);
2072}
2073
Christoph Hellwig45566e92009-07-10 23:11:57 +02002074int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2075 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002076{
2077 BlockDriver *drv = bs->drv;
2078 if (!drv)
2079 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002080 if (drv->bdrv_save_vmstate)
2081 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2082 if (bs->file)
2083 return bdrv_save_vmstate(bs->file, buf, pos, size);
2084 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002085}
2086
Christoph Hellwig45566e92009-07-10 23:11:57 +02002087int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2088 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002089{
2090 BlockDriver *drv = bs->drv;
2091 if (!drv)
2092 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002093 if (drv->bdrv_load_vmstate)
2094 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2095 if (bs->file)
2096 return bdrv_load_vmstate(bs->file, buf, pos, size);
2097 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002098}
2099
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01002100void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2101{
2102 BlockDriver *drv = bs->drv;
2103
2104 if (!drv || !drv->bdrv_debug_event) {
2105 return;
2106 }
2107
2108 return drv->bdrv_debug_event(bs, event);
2109
2110}
2111
bellardfaea38e2006-08-05 21:31:00 +00002112/**************************************************************/
2113/* handling of snapshots */
2114
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002115int bdrv_can_snapshot(BlockDriverState *bs)
2116{
2117 BlockDriver *drv = bs->drv;
Markus Armbruster07b70bf2011-08-03 15:08:11 +02002118 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002119 return 0;
2120 }
2121
2122 if (!drv->bdrv_snapshot_create) {
2123 if (bs->file != NULL) {
2124 return bdrv_can_snapshot(bs->file);
2125 }
2126 return 0;
2127 }
2128
2129 return 1;
2130}
2131
Blue Swirl199630b2010-07-25 20:49:34 +00002132int bdrv_is_snapshot(BlockDriverState *bs)
2133{
2134 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2135}
2136
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002137BlockDriverState *bdrv_snapshots(void)
2138{
2139 BlockDriverState *bs;
2140
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002141 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002142 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002143 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002144
2145 bs = NULL;
2146 while ((bs = bdrv_next(bs))) {
2147 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002148 bs_snapshots = bs;
2149 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002150 }
2151 }
2152 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002153}
2154
ths5fafdf22007-09-16 21:08:06 +00002155int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002156 QEMUSnapshotInfo *sn_info)
2157{
2158 BlockDriver *drv = bs->drv;
2159 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002160 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002161 if (drv->bdrv_snapshot_create)
2162 return drv->bdrv_snapshot_create(bs, sn_info);
2163 if (bs->file)
2164 return bdrv_snapshot_create(bs->file, sn_info);
2165 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002166}
2167
ths5fafdf22007-09-16 21:08:06 +00002168int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002169 const char *snapshot_id)
2170{
2171 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002172 int ret, open_ret;
2173
bellardfaea38e2006-08-05 21:31:00 +00002174 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002175 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002176 if (drv->bdrv_snapshot_goto)
2177 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2178
2179 if (bs->file) {
2180 drv->bdrv_close(bs);
2181 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2182 open_ret = drv->bdrv_open(bs, bs->open_flags);
2183 if (open_ret < 0) {
2184 bdrv_delete(bs->file);
2185 bs->drv = NULL;
2186 return open_ret;
2187 }
2188 return ret;
2189 }
2190
2191 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002192}
2193
2194int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2195{
2196 BlockDriver *drv = bs->drv;
2197 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002198 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002199 if (drv->bdrv_snapshot_delete)
2200 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2201 if (bs->file)
2202 return bdrv_snapshot_delete(bs->file, snapshot_id);
2203 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002204}
2205
ths5fafdf22007-09-16 21:08:06 +00002206int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002207 QEMUSnapshotInfo **psn_info)
2208{
2209 BlockDriver *drv = bs->drv;
2210 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002211 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002212 if (drv->bdrv_snapshot_list)
2213 return drv->bdrv_snapshot_list(bs, psn_info);
2214 if (bs->file)
2215 return bdrv_snapshot_list(bs->file, psn_info);
2216 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002217}
2218
edison51ef6722010-09-21 19:58:41 -07002219int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2220 const char *snapshot_name)
2221{
2222 BlockDriver *drv = bs->drv;
2223 if (!drv) {
2224 return -ENOMEDIUM;
2225 }
2226 if (!bs->read_only) {
2227 return -EINVAL;
2228 }
2229 if (drv->bdrv_snapshot_load_tmp) {
2230 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2231 }
2232 return -ENOTSUP;
2233}
2234
bellardfaea38e2006-08-05 21:31:00 +00002235#define NB_SUFFIXES 4
2236
2237char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2238{
2239 static const char suffixes[NB_SUFFIXES] = "KMGT";
2240 int64_t base;
2241 int i;
2242
2243 if (size <= 999) {
2244 snprintf(buf, buf_size, "%" PRId64, size);
2245 } else {
2246 base = 1024;
2247 for(i = 0; i < NB_SUFFIXES; i++) {
2248 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00002249 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00002250 (double)size / base,
2251 suffixes[i]);
2252 break;
2253 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00002254 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00002255 ((size + (base >> 1)) / base),
2256 suffixes[i]);
2257 break;
2258 }
2259 base = base * 1024;
2260 }
2261 }
2262 return buf;
2263}
2264
2265char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2266{
2267 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00002268#ifdef _WIN32
2269 struct tm *ptm;
2270#else
bellardfaea38e2006-08-05 21:31:00 +00002271 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00002272#endif
bellardfaea38e2006-08-05 21:31:00 +00002273 time_t ti;
2274 int64_t secs;
2275
2276 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00002277 snprintf(buf, buf_size,
2278 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002279 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2280 } else {
2281 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00002282#ifdef _WIN32
2283 ptm = localtime(&ti);
2284 strftime(date_buf, sizeof(date_buf),
2285 "%Y-%m-%d %H:%M:%S", ptm);
2286#else
bellardfaea38e2006-08-05 21:31:00 +00002287 localtime_r(&ti, &tm);
2288 strftime(date_buf, sizeof(date_buf),
2289 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00002290#endif
bellardfaea38e2006-08-05 21:31:00 +00002291 secs = sn->vm_clock_nsec / 1000000000;
2292 snprintf(clock_buf, sizeof(clock_buf),
2293 "%02d:%02d:%02d.%03d",
2294 (int)(secs / 3600),
2295 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00002296 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00002297 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2298 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00002299 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002300 sn->id_str, sn->name,
2301 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2302 date_buf,
2303 clock_buf);
2304 }
2305 return buf;
2306}
2307
bellard83f64092006-08-01 16:21:11 +00002308/**************************************************************/
2309/* async I/Os */
2310
aliguori3b69e4b2009-01-22 16:59:24 +00002311BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00002312 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00002313 BlockDriverCompletionFunc *cb, void *opaque)
2314{
bellard83f64092006-08-01 16:21:11 +00002315 BlockDriver *drv = bs->drv;
bellard83f64092006-08-01 16:21:11 +00002316
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002317 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2318
bellard19cb3732006-08-19 11:45:59 +00002319 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002320 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002321 if (bdrv_check_request(bs, sector_num, nb_sectors))
2322 return NULL;
ths3b46e622007-09-17 08:09:54 +00002323
Christoph Hellwiga597e792011-08-25 08:26:01 +02002324 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2325 cb, opaque);
bellard83f64092006-08-01 16:21:11 +00002326}
2327
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002328typedef struct BlockCompleteData {
2329 BlockDriverCompletionFunc *cb;
2330 void *opaque;
2331 BlockDriverState *bs;
2332 int64_t sector_num;
2333 int nb_sectors;
2334} BlockCompleteData;
2335
2336static void block_complete_cb(void *opaque, int ret)
2337{
2338 BlockCompleteData *b = opaque;
2339
2340 if (b->bs->dirty_bitmap) {
2341 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2342 }
2343 b->cb(b->opaque, ret);
Anthony Liguori7267c092011-08-20 22:09:37 -05002344 g_free(b);
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002345}
2346
2347static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2348 int64_t sector_num,
2349 int nb_sectors,
2350 BlockDriverCompletionFunc *cb,
2351 void *opaque)
2352{
Anthony Liguori7267c092011-08-20 22:09:37 -05002353 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002354
2355 blkdata->bs = bs;
2356 blkdata->cb = cb;
2357 blkdata->opaque = opaque;
2358 blkdata->sector_num = sector_num;
2359 blkdata->nb_sectors = nb_sectors;
2360
2361 return blkdata;
2362}
2363
aliguorif141eaf2009-04-07 18:43:24 +00002364BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2365 QEMUIOVector *qiov, int nb_sectors,
2366 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002367{
bellard83f64092006-08-01 16:21:11 +00002368 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002369 BlockDriverAIOCB *ret;
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002370 BlockCompleteData *blk_cb_data;
bellard83f64092006-08-01 16:21:11 +00002371
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002372 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2373
bellard19cb3732006-08-19 11:45:59 +00002374 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002375 return NULL;
bellard83f64092006-08-01 16:21:11 +00002376 if (bs->read_only)
pbrookce1a14d2006-08-07 02:38:06 +00002377 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002378 if (bdrv_check_request(bs, sector_num, nb_sectors))
2379 return NULL;
bellard83f64092006-08-01 16:21:11 +00002380
Jan Kiszkac6d22832009-11-30 18:21:20 +01002381 if (bs->dirty_bitmap) {
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002382 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2383 opaque);
2384 cb = &block_complete_cb;
2385 opaque = blk_cb_data;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002386 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002387
aliguorif141eaf2009-04-07 18:43:24 +00002388 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2389 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002390
2391 if (ret) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002392 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2393 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2394 }
thsa36e69d2007-12-02 05:18:19 +00002395 }
2396
2397 return ret;
bellard83f64092006-08-01 16:21:11 +00002398}
2399
Kevin Wolf40b4f532009-09-09 17:53:37 +02002400
2401typedef struct MultiwriteCB {
2402 int error;
2403 int num_requests;
2404 int num_callbacks;
2405 struct {
2406 BlockDriverCompletionFunc *cb;
2407 void *opaque;
2408 QEMUIOVector *free_qiov;
2409 void *free_buf;
2410 } callbacks[];
2411} MultiwriteCB;
2412
2413static void multiwrite_user_cb(MultiwriteCB *mcb)
2414{
2415 int i;
2416
2417 for (i = 0; i < mcb->num_callbacks; i++) {
2418 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01002419 if (mcb->callbacks[i].free_qiov) {
2420 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2421 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002422 g_free(mcb->callbacks[i].free_qiov);
Herve Poussineauf8a83242010-01-24 21:23:56 +00002423 qemu_vfree(mcb->callbacks[i].free_buf);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002424 }
2425}
2426
2427static void multiwrite_cb(void *opaque, int ret)
2428{
2429 MultiwriteCB *mcb = opaque;
2430
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002431 trace_multiwrite_cb(mcb, ret);
2432
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02002433 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02002434 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002435 }
2436
2437 mcb->num_requests--;
2438 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02002439 multiwrite_user_cb(mcb);
Anthony Liguori7267c092011-08-20 22:09:37 -05002440 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002441 }
2442}
2443
2444static int multiwrite_req_compare(const void *a, const void *b)
2445{
Christoph Hellwig77be4362010-05-19 20:53:10 +02002446 const BlockRequest *req1 = a, *req2 = b;
2447
2448 /*
2449 * Note that we can't simply subtract req2->sector from req1->sector
2450 * here as that could overflow the return value.
2451 */
2452 if (req1->sector > req2->sector) {
2453 return 1;
2454 } else if (req1->sector < req2->sector) {
2455 return -1;
2456 } else {
2457 return 0;
2458 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002459}
2460
2461/*
2462 * Takes a bunch of requests and tries to merge them. Returns the number of
2463 * requests that remain after merging.
2464 */
2465static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2466 int num_reqs, MultiwriteCB *mcb)
2467{
2468 int i, outidx;
2469
2470 // Sort requests by start sector
2471 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2472
2473 // Check if adjacent requests touch the same clusters. If so, combine them,
2474 // filling up gaps with zero sectors.
2475 outidx = 0;
2476 for (i = 1; i < num_reqs; i++) {
2477 int merge = 0;
2478 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2479
2480 // This handles the cases that are valid for all block drivers, namely
2481 // exactly sequential writes and overlapping writes.
2482 if (reqs[i].sector <= oldreq_last) {
2483 merge = 1;
2484 }
2485
2486 // The block driver may decide that it makes sense to combine requests
2487 // even if there is a gap of some sectors between them. In this case,
2488 // the gap is filled with zeros (therefore only applicable for yet
2489 // unused space in format like qcow2).
2490 if (!merge && bs->drv->bdrv_merge_requests) {
2491 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2492 }
2493
Christoph Hellwige2a305f2010-01-26 14:49:08 +01002494 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2495 merge = 0;
2496 }
2497
Kevin Wolf40b4f532009-09-09 17:53:37 +02002498 if (merge) {
2499 size_t size;
Anthony Liguori7267c092011-08-20 22:09:37 -05002500 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002501 qemu_iovec_init(qiov,
2502 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2503
2504 // Add the first request to the merged one. If the requests are
2505 // overlapping, drop the last sectors of the first request.
2506 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2507 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2508
2509 // We might need to add some zeros between the two requests
2510 if (reqs[i].sector > oldreq_last) {
2511 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2512 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2513 memset(buf, 0, zero_bytes);
2514 qemu_iovec_add(qiov, buf, zero_bytes);
2515 mcb->callbacks[i].free_buf = buf;
2516 }
2517
2518 // Add the second request
2519 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2520
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02002521 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002522 reqs[outidx].qiov = qiov;
2523
2524 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2525 } else {
2526 outidx++;
2527 reqs[outidx].sector = reqs[i].sector;
2528 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2529 reqs[outidx].qiov = reqs[i].qiov;
2530 }
2531 }
2532
2533 return outidx + 1;
2534}
2535
2536/*
2537 * Submit multiple AIO write requests at once.
2538 *
2539 * On success, the function returns 0 and all requests in the reqs array have
2540 * been submitted. In error case this function returns -1, and any of the
2541 * requests may or may not be submitted yet. In particular, this means that the
2542 * callback will be called for some of the requests, for others it won't. The
2543 * caller must check the error field of the BlockRequest to wait for the right
2544 * callbacks (if error != 0, no callback will be called).
2545 *
2546 * The implementation may modify the contents of the reqs array, e.g. to merge
2547 * requests. However, the fields opaque and error are left unmodified as they
2548 * are used to signal failure for a single request to the caller.
2549 */
2550int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2551{
2552 BlockDriverAIOCB *acb;
2553 MultiwriteCB *mcb;
2554 int i;
2555
Ryan Harper301db7c2011-03-07 10:01:04 -06002556 /* don't submit writes if we don't have a medium */
2557 if (bs->drv == NULL) {
2558 for (i = 0; i < num_reqs; i++) {
2559 reqs[i].error = -ENOMEDIUM;
2560 }
2561 return -1;
2562 }
2563
Kevin Wolf40b4f532009-09-09 17:53:37 +02002564 if (num_reqs == 0) {
2565 return 0;
2566 }
2567
2568 // Create MultiwriteCB structure
Anthony Liguori7267c092011-08-20 22:09:37 -05002569 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002570 mcb->num_requests = 0;
2571 mcb->num_callbacks = num_reqs;
2572
2573 for (i = 0; i < num_reqs; i++) {
2574 mcb->callbacks[i].cb = reqs[i].cb;
2575 mcb->callbacks[i].opaque = reqs[i].opaque;
2576 }
2577
2578 // Check for mergable requests
2579 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2580
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002581 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2582
Kevin Wolf453f9a12010-07-02 14:01:21 +02002583 /*
2584 * Run the aio requests. As soon as one request can't be submitted
2585 * successfully, fail all requests that are not yet submitted (we must
2586 * return failure for all requests anyway)
2587 *
2588 * num_requests cannot be set to the right value immediately: If
2589 * bdrv_aio_writev fails for some request, num_requests would be too high
2590 * and therefore multiwrite_cb() would never recognize the multiwrite
2591 * request as completed. We also cannot use the loop variable i to set it
2592 * when the first request fails because the callback may already have been
2593 * called for previously submitted requests. Thus, num_requests must be
2594 * incremented for each request that is submitted.
2595 *
2596 * The problem that callbacks may be called early also means that we need
2597 * to take care that num_requests doesn't become 0 before all requests are
2598 * submitted - multiwrite_cb() would consider the multiwrite request
2599 * completed. A dummy request that is "completed" by a manual call to
2600 * multiwrite_cb() takes care of this.
2601 */
2602 mcb->num_requests = 1;
2603
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002604 // Run the aio requests
Kevin Wolf40b4f532009-09-09 17:53:37 +02002605 for (i = 0; i < num_reqs; i++) {
Kevin Wolf453f9a12010-07-02 14:01:21 +02002606 mcb->num_requests++;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002607 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2608 reqs[i].nb_sectors, multiwrite_cb, mcb);
2609
2610 if (acb == NULL) {
2611 // We can only fail the whole thing if no request has been
2612 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2613 // complete and report the error in the callback.
Kevin Wolf453f9a12010-07-02 14:01:21 +02002614 if (i == 0) {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002615 trace_bdrv_aio_multiwrite_earlyfail(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002616 goto fail;
2617 } else {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002618 trace_bdrv_aio_multiwrite_latefail(mcb, i);
Kevin Wolf7eb58a62010-04-06 18:24:07 +02002619 multiwrite_cb(mcb, -EIO);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002620 break;
2621 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002622 }
2623 }
2624
Kevin Wolf453f9a12010-07-02 14:01:21 +02002625 /* Complete the dummy request */
2626 multiwrite_cb(mcb, 0);
2627
Kevin Wolf40b4f532009-09-09 17:53:37 +02002628 return 0;
2629
2630fail:
Kevin Wolf453f9a12010-07-02 14:01:21 +02002631 for (i = 0; i < mcb->num_callbacks; i++) {
2632 reqs[i].error = -EIO;
2633 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002634 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002635 return -1;
2636}
2637
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002638BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2639 BlockDriverCompletionFunc *cb, void *opaque)
2640{
2641 BlockDriver *drv = bs->drv;
2642
Stefan Hajnoczia13aac02011-03-07 07:58:04 +00002643 trace_bdrv_aio_flush(bs, opaque);
2644
Alexander Graf016f5cf2010-05-26 17:51:49 +02002645 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2646 return bdrv_aio_noop_em(bs, cb, opaque);
2647 }
2648
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002649 if (!drv)
2650 return NULL;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002651 return drv->bdrv_aio_flush(bs, cb, opaque);
2652}
2653
bellard83f64092006-08-01 16:21:11 +00002654void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00002655{
aliguori6bbff9a2009-03-20 18:25:59 +00002656 acb->pool->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00002657}
2658
pbrookce1a14d2006-08-07 02:38:06 +00002659
bellard83f64092006-08-01 16:21:11 +00002660/**************************************************************/
2661/* async block device emulation */
2662
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002663typedef struct BlockDriverAIOCBSync {
2664 BlockDriverAIOCB common;
2665 QEMUBH *bh;
2666 int ret;
2667 /* vector translation state */
2668 QEMUIOVector *qiov;
2669 uint8_t *bounce;
2670 int is_write;
2671} BlockDriverAIOCBSync;
2672
2673static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2674{
Kevin Wolfb666d232010-05-05 11:44:39 +02002675 BlockDriverAIOCBSync *acb =
2676 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03002677 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002678 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002679 qemu_aio_release(acb);
2680}
2681
2682static AIOPool bdrv_em_aio_pool = {
2683 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2684 .cancel = bdrv_aio_cancel_em,
2685};
2686
bellard83f64092006-08-01 16:21:11 +00002687static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00002688{
pbrookce1a14d2006-08-07 02:38:06 +00002689 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00002690
aliguorif141eaf2009-04-07 18:43:24 +00002691 if (!acb->is_write)
2692 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00002693 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00002694 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03002695 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002696 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00002697 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00002698}
bellardbeac80c2006-06-26 20:08:57 +00002699
aliguorif141eaf2009-04-07 18:43:24 +00002700static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2701 int64_t sector_num,
2702 QEMUIOVector *qiov,
2703 int nb_sectors,
2704 BlockDriverCompletionFunc *cb,
2705 void *opaque,
2706 int is_write)
2707
bellardea2384d2004-08-01 21:59:26 +00002708{
pbrookce1a14d2006-08-07 02:38:06 +00002709 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00002710
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002711 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00002712 acb->is_write = is_write;
2713 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00002714 acb->bounce = qemu_blockalign(bs, qiov->size);
aliguorif141eaf2009-04-07 18:43:24 +00002715
pbrookce1a14d2006-08-07 02:38:06 +00002716 if (!acb->bh)
2717 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00002718
2719 if (is_write) {
2720 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2721 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2722 } else {
2723 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2724 }
2725
pbrookce1a14d2006-08-07 02:38:06 +00002726 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00002727
pbrookce1a14d2006-08-07 02:38:06 +00002728 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00002729}
2730
aliguorif141eaf2009-04-07 18:43:24 +00002731static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2732 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00002733 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002734{
aliguorif141eaf2009-04-07 18:43:24 +00002735 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00002736}
2737
aliguorif141eaf2009-04-07 18:43:24 +00002738static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2739 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2740 BlockDriverCompletionFunc *cb, void *opaque)
2741{
2742 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2743}
2744
Kevin Wolf68485422011-06-30 10:05:46 +02002745
2746typedef struct BlockDriverAIOCBCoroutine {
2747 BlockDriverAIOCB common;
2748 BlockRequest req;
2749 bool is_write;
2750 QEMUBH* bh;
2751} BlockDriverAIOCBCoroutine;
2752
2753static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2754{
2755 qemu_aio_flush();
2756}
2757
2758static AIOPool bdrv_em_co_aio_pool = {
2759 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2760 .cancel = bdrv_aio_co_cancel_em,
2761};
2762
2763static void bdrv_co_rw_bh(void *opaque)
2764{
2765 BlockDriverAIOCBCoroutine *acb = opaque;
2766
2767 acb->common.cb(acb->common.opaque, acb->req.error);
2768 qemu_bh_delete(acb->bh);
2769 qemu_aio_release(acb);
2770}
2771
2772static void coroutine_fn bdrv_co_rw(void *opaque)
2773{
2774 BlockDriverAIOCBCoroutine *acb = opaque;
2775 BlockDriverState *bs = acb->common.bs;
2776
2777 if (!acb->is_write) {
2778 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2779 acb->req.nb_sectors, acb->req.qiov);
2780 } else {
2781 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2782 acb->req.nb_sectors, acb->req.qiov);
2783 }
2784
2785 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2786 qemu_bh_schedule(acb->bh);
2787}
2788
2789static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2790 int64_t sector_num,
2791 QEMUIOVector *qiov,
2792 int nb_sectors,
2793 BlockDriverCompletionFunc *cb,
2794 void *opaque,
2795 bool is_write)
2796{
2797 Coroutine *co;
2798 BlockDriverAIOCBCoroutine *acb;
2799
2800 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2801 acb->req.sector = sector_num;
2802 acb->req.nb_sectors = nb_sectors;
2803 acb->req.qiov = qiov;
2804 acb->is_write = is_write;
2805
2806 co = qemu_coroutine_create(bdrv_co_rw);
2807 qemu_coroutine_enter(co, acb);
2808
2809 return &acb->common;
2810}
2811
2812static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2813 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2814 BlockDriverCompletionFunc *cb, void *opaque)
2815{
2816 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2817 false);
2818}
2819
2820static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2821 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2822 BlockDriverCompletionFunc *cb, void *opaque)
2823{
2824 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2825 true);
2826}
2827
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002828static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2829 BlockDriverCompletionFunc *cb, void *opaque)
2830{
2831 BlockDriverAIOCBSync *acb;
2832
2833 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2834 acb->is_write = 1; /* don't bounce in the completion hadler */
2835 acb->qiov = NULL;
2836 acb->bounce = NULL;
2837 acb->ret = 0;
2838
2839 if (!acb->bh)
2840 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2841
2842 bdrv_flush(bs);
2843 qemu_bh_schedule(acb->bh);
2844 return &acb->common;
2845}
2846
Alexander Graf016f5cf2010-05-26 17:51:49 +02002847static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2848 BlockDriverCompletionFunc *cb, void *opaque)
2849{
2850 BlockDriverAIOCBSync *acb;
2851
2852 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2853 acb->is_write = 1; /* don't bounce in the completion handler */
2854 acb->qiov = NULL;
2855 acb->bounce = NULL;
2856 acb->ret = 0;
2857
2858 if (!acb->bh) {
2859 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2860 }
2861
2862 qemu_bh_schedule(acb->bh);
2863 return &acb->common;
2864}
2865
bellard83f64092006-08-01 16:21:11 +00002866/**************************************************************/
2867/* sync block device emulation */
2868
2869static void bdrv_rw_em_cb(void *opaque, int ret)
2870{
2871 *(int *)opaque = ret;
2872}
2873
2874#define NOT_DONE 0x7fffffff
2875
ths5fafdf22007-09-16 21:08:06 +00002876static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +00002877 uint8_t *buf, int nb_sectors)
2878{
pbrookce1a14d2006-08-07 02:38:06 +00002879 int async_ret;
2880 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002881 struct iovec iov;
2882 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002883
bellard83f64092006-08-01 16:21:11 +00002884 async_ret = NOT_DONE;
blueswir13f4cb3d2009-04-13 16:31:01 +00002885 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002886 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002887 qemu_iovec_init_external(&qiov, &iov, 1);
2888 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2889 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002890 if (acb == NULL) {
2891 async_ret = -1;
2892 goto fail;
2893 }
aliguoribaf35cb2008-09-10 15:45:19 +00002894
bellard83f64092006-08-01 16:21:11 +00002895 while (async_ret == NOT_DONE) {
2896 qemu_aio_wait();
2897 }
aliguoribaf35cb2008-09-10 15:45:19 +00002898
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002899
2900fail:
bellard83f64092006-08-01 16:21:11 +00002901 return async_ret;
2902}
2903
2904static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2905 const uint8_t *buf, int nb_sectors)
2906{
pbrookce1a14d2006-08-07 02:38:06 +00002907 int async_ret;
2908 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002909 struct iovec iov;
2910 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002911
bellard83f64092006-08-01 16:21:11 +00002912 async_ret = NOT_DONE;
aliguorif141eaf2009-04-07 18:43:24 +00002913 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002914 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002915 qemu_iovec_init_external(&qiov, &iov, 1);
2916 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2917 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002918 if (acb == NULL) {
2919 async_ret = -1;
2920 goto fail;
2921 }
bellard83f64092006-08-01 16:21:11 +00002922 while (async_ret == NOT_DONE) {
2923 qemu_aio_wait();
2924 }
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002925
2926fail:
bellard83f64092006-08-01 16:21:11 +00002927 return async_ret;
2928}
bellardea2384d2004-08-01 21:59:26 +00002929
2930void bdrv_init(void)
2931{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05002932 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00002933}
pbrookce1a14d2006-08-07 02:38:06 +00002934
Markus Armbrustereb852012009-10-27 18:41:44 +01002935void bdrv_init_with_whitelist(void)
2936{
2937 use_bdrv_whitelist = 1;
2938 bdrv_init();
2939}
2940
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002941void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2942 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00002943{
pbrookce1a14d2006-08-07 02:38:06 +00002944 BlockDriverAIOCB *acb;
2945
aliguori6bbff9a2009-03-20 18:25:59 +00002946 if (pool->free_aiocb) {
2947 acb = pool->free_aiocb;
2948 pool->free_aiocb = acb->next;
pbrookce1a14d2006-08-07 02:38:06 +00002949 } else {
Anthony Liguori7267c092011-08-20 22:09:37 -05002950 acb = g_malloc0(pool->aiocb_size);
aliguori6bbff9a2009-03-20 18:25:59 +00002951 acb->pool = pool;
pbrookce1a14d2006-08-07 02:38:06 +00002952 }
2953 acb->bs = bs;
2954 acb->cb = cb;
2955 acb->opaque = opaque;
2956 return acb;
2957}
2958
2959void qemu_aio_release(void *p)
2960{
aliguori6bbff9a2009-03-20 18:25:59 +00002961 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2962 AIOPool *pool = acb->pool;
2963 acb->next = pool->free_aiocb;
2964 pool->free_aiocb = acb;
pbrookce1a14d2006-08-07 02:38:06 +00002965}
bellard19cb3732006-08-19 11:45:59 +00002966
2967/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02002968/* Coroutine block device emulation */
2969
2970typedef struct CoroutineIOCompletion {
2971 Coroutine *coroutine;
2972 int ret;
2973} CoroutineIOCompletion;
2974
2975static void bdrv_co_io_em_complete(void *opaque, int ret)
2976{
2977 CoroutineIOCompletion *co = opaque;
2978
2979 co->ret = ret;
2980 qemu_coroutine_enter(co->coroutine, NULL);
2981}
2982
2983static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2984 int nb_sectors, QEMUIOVector *iov,
2985 bool is_write)
2986{
2987 CoroutineIOCompletion co = {
2988 .coroutine = qemu_coroutine_self(),
2989 };
2990 BlockDriverAIOCB *acb;
2991
2992 if (is_write) {
2993 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2994 bdrv_co_io_em_complete, &co);
2995 } else {
2996 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2997 bdrv_co_io_em_complete, &co);
2998 }
2999
3000 trace_bdrv_co_io(is_write, acb);
3001 if (!acb) {
3002 return -EIO;
3003 }
3004 qemu_coroutine_yield();
3005
3006 return co.ret;
3007}
3008
3009static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3010 int64_t sector_num, int nb_sectors,
3011 QEMUIOVector *iov)
3012{
3013 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3014}
3015
3016static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3017 int64_t sector_num, int nb_sectors,
3018 QEMUIOVector *iov)
3019{
3020 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3021}
3022
Kevin Wolfe7a8a782011-07-15 16:05:00 +02003023static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3024{
3025 CoroutineIOCompletion co = {
3026 .coroutine = qemu_coroutine_self(),
3027 };
3028 BlockDriverAIOCB *acb;
3029
3030 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3031 if (!acb) {
3032 return -EIO;
3033 }
3034 qemu_coroutine_yield();
3035 return co.ret;
3036}
3037
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003038/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00003039/* removable device support */
3040
3041/**
3042 * Return TRUE if the media is present
3043 */
3044int bdrv_is_inserted(BlockDriverState *bs)
3045{
3046 BlockDriver *drv = bs->drv;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003047
bellard19cb3732006-08-19 11:45:59 +00003048 if (!drv)
3049 return 0;
3050 if (!drv->bdrv_is_inserted)
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003051 return 1;
3052 return drv->bdrv_is_inserted(bs);
bellard19cb3732006-08-19 11:45:59 +00003053}
3054
3055/**
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003056 * Return whether the media changed since the last call to this
3057 * function, or -ENOTSUP if we don't know. Most drivers don't know.
bellard19cb3732006-08-19 11:45:59 +00003058 */
3059int bdrv_media_changed(BlockDriverState *bs)
3060{
3061 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003062
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003063 if (drv && drv->bdrv_media_changed) {
3064 return drv->bdrv_media_changed(bs);
3065 }
3066 return -ENOTSUP;
bellard19cb3732006-08-19 11:45:59 +00003067}
3068
3069/**
3070 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3071 */
Markus Armbrusterfdec4402011-09-06 18:58:45 +02003072void bdrv_eject(BlockDriverState *bs, int eject_flag)
bellard19cb3732006-08-19 11:45:59 +00003073{
3074 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003075
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003076 if (drv && drv->bdrv_eject) {
3077 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00003078 }
bellard19cb3732006-08-19 11:45:59 +00003079}
3080
bellard19cb3732006-08-19 11:45:59 +00003081/**
3082 * Lock or unlock the media (if it is locked, the user won't be able
3083 * to eject it manually).
3084 */
Markus Armbruster025e8492011-09-06 18:58:47 +02003085void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00003086{
3087 BlockDriver *drv = bs->drv;
3088
Markus Armbruster025e8492011-09-06 18:58:47 +02003089 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01003090
Markus Armbruster025e8492011-09-06 18:58:47 +02003091 if (drv && drv->bdrv_lock_medium) {
3092 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00003093 }
3094}
ths985a03b2007-12-24 16:10:43 +00003095
3096/* needed for generic scsi interface */
3097
3098int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3099{
3100 BlockDriver *drv = bs->drv;
3101
3102 if (drv && drv->bdrv_ioctl)
3103 return drv->bdrv_ioctl(bs, req, buf);
3104 return -ENOTSUP;
3105}
aliguori7d780662009-03-12 19:57:08 +00003106
aliguori221f7152009-03-28 17:28:41 +00003107BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3108 unsigned long int req, void *buf,
3109 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00003110{
aliguori221f7152009-03-28 17:28:41 +00003111 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00003112
aliguori221f7152009-03-28 17:28:41 +00003113 if (drv && drv->bdrv_aio_ioctl)
3114 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3115 return NULL;
aliguori7d780662009-03-12 19:57:08 +00003116}
aliguorie268ca52009-04-22 20:20:00 +00003117
Markus Armbruster7b6f9302011-09-06 18:58:56 +02003118void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
3119{
3120 bs->buffer_alignment = align;
3121}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003122
aliguorie268ca52009-04-22 20:20:00 +00003123void *qemu_blockalign(BlockDriverState *bs, size_t size)
3124{
3125 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3126}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003127
3128void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3129{
3130 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003131
Liran Schouraaa0eb72010-01-26 10:31:48 +02003132 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003133 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003134 if (!bs->dirty_bitmap) {
3135 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3136 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3137 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003138
Anthony Liguori7267c092011-08-20 22:09:37 -05003139 bs->dirty_bitmap = g_malloc0(bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003140 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003141 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003142 if (bs->dirty_bitmap) {
Anthony Liguori7267c092011-08-20 22:09:37 -05003143 g_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01003144 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003145 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003146 }
3147}
3148
3149int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3150{
Jan Kiszka6ea44302009-11-30 18:21:19 +01003151 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003152
Jan Kiszkac6d22832009-11-30 18:21:20 +01003153 if (bs->dirty_bitmap &&
3154 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02003155 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3156 (1UL << (chunk % (sizeof(unsigned long) * 8))));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003157 } else {
3158 return 0;
3159 }
3160}
3161
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003162void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3163 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003164{
3165 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3166}
Liran Schouraaa0eb72010-01-26 10:31:48 +02003167
3168int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3169{
3170 return bs->dirty_count;
3171}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003172
Marcelo Tosattidb593f22011-01-26 12:12:34 -02003173void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3174{
3175 assert(bs->in_use != in_use);
3176 bs->in_use = in_use;
3177}
3178
3179int bdrv_in_use(BlockDriverState *bs)
3180{
3181 return bs->in_use;
3182}
3183
Christoph Hellwiga597e792011-08-25 08:26:01 +02003184void
3185bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3186 enum BlockAcctType type)
3187{
3188 assert(type < BDRV_MAX_IOTYPE);
3189
3190 cookie->bytes = bytes;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003191 cookie->start_time_ns = get_clock();
Christoph Hellwiga597e792011-08-25 08:26:01 +02003192 cookie->type = type;
3193}
3194
3195void
3196bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3197{
3198 assert(cookie->type < BDRV_MAX_IOTYPE);
3199
3200 bs->nr_bytes[cookie->type] += cookie->bytes;
3201 bs->nr_ops[cookie->type]++;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003202 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
Christoph Hellwiga597e792011-08-25 08:26:01 +02003203}
3204
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003205int bdrv_img_create(const char *filename, const char *fmt,
3206 const char *base_filename, const char *base_fmt,
3207 char *options, uint64_t img_size, int flags)
3208{
3209 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02003210 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003211 BlockDriverState *bs = NULL;
3212 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003213 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003214 int ret = 0;
3215
3216 /* Find driver and parse its options */
3217 drv = bdrv_find_format(fmt);
3218 if (!drv) {
3219 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003220 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003221 goto out;
3222 }
3223
3224 proto_drv = bdrv_find_protocol(filename);
3225 if (!proto_drv) {
3226 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003227 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003228 goto out;
3229 }
3230
3231 create_options = append_option_parameters(create_options,
3232 drv->create_options);
3233 create_options = append_option_parameters(create_options,
3234 proto_drv->create_options);
3235
3236 /* Create parameter list with default values */
3237 param = parse_option_parameters("", create_options, param);
3238
3239 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3240
3241 /* Parse -o options */
3242 if (options) {
3243 param = parse_option_parameters(options, create_options, param);
3244 if (param == NULL) {
3245 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003246 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003247 goto out;
3248 }
3249 }
3250
3251 if (base_filename) {
3252 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3253 base_filename)) {
3254 error_report("Backing file not supported for file format '%s'",
3255 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003256 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003257 goto out;
3258 }
3259 }
3260
3261 if (base_fmt) {
3262 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3263 error_report("Backing file format not supported for file "
3264 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003265 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003266 goto out;
3267 }
3268 }
3269
Jes Sorensen792da932010-12-16 13:52:17 +01003270 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3271 if (backing_file && backing_file->value.s) {
3272 if (!strcmp(filename, backing_file->value.s)) {
3273 error_report("Error: Trying to create an image with the "
3274 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003275 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01003276 goto out;
3277 }
3278 }
3279
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003280 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3281 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003282 backing_drv = bdrv_find_format(backing_fmt->value.s);
3283 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003284 error_report("Unknown backing file format '%s'",
3285 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003286 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003287 goto out;
3288 }
3289 }
3290
3291 // The size for the image must always be specified, with one exception:
3292 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02003293 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3294 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003295 if (backing_file && backing_file->value.s) {
3296 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003297 char buf[32];
3298
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003299 bs = bdrv_new("");
3300
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003301 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003302 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003303 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003304 goto out;
3305 }
3306 bdrv_get_geometry(bs, &size);
3307 size *= 512;
3308
3309 snprintf(buf, sizeof(buf), "%" PRId64, size);
3310 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3311 } else {
3312 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003313 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003314 goto out;
3315 }
3316 }
3317
3318 printf("Formatting '%s', fmt=%s ", filename, fmt);
3319 print_option_parameters(param);
3320 puts("");
3321
3322 ret = bdrv_create(drv, filename, param);
3323
3324 if (ret < 0) {
3325 if (ret == -ENOTSUP) {
3326 error_report("Formatting or formatting option not supported for "
3327 "file format '%s'", fmt);
3328 } else if (ret == -EFBIG) {
3329 error_report("The image size is too large for file format '%s'",
3330 fmt);
3331 } else {
3332 error_report("%s: error while creating %s: %s", filename, fmt,
3333 strerror(-ret));
3334 }
3335 }
3336
3337out:
3338 free_option_parameters(create_options);
3339 free_option_parameters(param);
3340
3341 if (bs) {
3342 bdrv_delete(bs);
3343 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01003344
3345 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003346}