blob: 00fe3450c948f355f13a915904557e957b4a9c3e [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 Armbruster0e49de52011-08-03 15:07:41 +020047static void bdrv_dev_change_cb(BlockDriverState *bs, int reason);
aliguorif141eaf2009-04-07 18:43:24 +000048static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
aliguoric87c0672009-04-07 18:43:20 +000050 BlockDriverCompletionFunc *cb, void *opaque);
aliguorif141eaf2009-04-07 18:43:24 +000051static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +000053 BlockDriverCompletionFunc *cb, void *opaque);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +020054static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55 BlockDriverCompletionFunc *cb, void *opaque);
Alexander Graf016f5cf2010-05-26 17:51:49 +020056static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57 BlockDriverCompletionFunc *cb, void *opaque);
ths5fafdf22007-09-16 21:08:06 +000058static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +000059 uint8_t *buf, int nb_sectors);
60static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61 const uint8_t *buf, int nb_sectors);
Kevin Wolf68485422011-06-30 10:05:46 +020062static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64 BlockDriverCompletionFunc *cb, void *opaque);
65static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67 BlockDriverCompletionFunc *cb, void *opaque);
Kevin Wolff9f05dc2011-07-15 13:50:26 +020068static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69 int64_t sector_num, int nb_sectors,
70 QEMUIOVector *iov);
71static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72 int64_t sector_num, int nb_sectors,
73 QEMUIOVector *iov);
Kevin Wolfe7a8a782011-07-15 16:05:00 +020074static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
bellardec530c82006-04-25 22:36:06 +000075
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +010076static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(bdrv_states);
blueswir17ee930d2008-09-17 19:04:14 +000078
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010079static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000081
Markus Armbrusterf9092b12010-06-25 10:33:39 +020082/* The device to use for VM snapshots */
83static BlockDriverState *bs_snapshots;
84
Markus Armbrustereb852012009-10-27 18:41:44 +010085/* If non-zero, use only whitelisted block drivers */
86static int use_bdrv_whitelist;
87
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000088#ifdef _WIN32
89static int is_windows_drive_prefix(const char *filename)
90{
91 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
93 filename[1] == ':');
94}
95
96int is_windows_drive(const char *filename)
97{
98 if (is_windows_drive_prefix(filename) &&
99 filename[2] == '\0')
100 return 1;
101 if (strstart(filename, "\\\\.\\", NULL) ||
102 strstart(filename, "//./", NULL))
103 return 1;
104 return 0;
105}
106#endif
107
108/* check if the path starts with "<protocol>:" */
109static int path_has_protocol(const char *path)
110{
111#ifdef _WIN32
112 if (is_windows_drive(path) ||
113 is_windows_drive_prefix(path)) {
114 return 0;
115 }
116#endif
117
118 return strchr(path, ':') != NULL;
119}
120
bellard83f64092006-08-01 16:21:11 +0000121int path_is_absolute(const char *path)
122{
123 const char *p;
bellard21664422007-01-07 18:22:37 +0000124#ifdef _WIN32
125 /* specific case for names like: "\\.\d:" */
126 if (*path == '/' || *path == '\\')
127 return 1;
128#endif
bellard83f64092006-08-01 16:21:11 +0000129 p = strchr(path, ':');
130 if (p)
131 p++;
132 else
133 p = path;
bellard3b9f94e2007-01-07 17:27:07 +0000134#ifdef _WIN32
135 return (*p == '/' || *p == '\\');
136#else
137 return (*p == '/');
138#endif
bellard83f64092006-08-01 16:21:11 +0000139}
140
141/* if filename is absolute, just copy it to dest. Otherwise, build a
142 path to it by considering it is relative to base_path. URL are
143 supported. */
144void path_combine(char *dest, int dest_size,
145 const char *base_path,
146 const char *filename)
147{
148 const char *p, *p1;
149 int len;
150
151 if (dest_size <= 0)
152 return;
153 if (path_is_absolute(filename)) {
154 pstrcpy(dest, dest_size, filename);
155 } else {
156 p = strchr(base_path, ':');
157 if (p)
158 p++;
159 else
160 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000161 p1 = strrchr(base_path, '/');
162#ifdef _WIN32
163 {
164 const char *p2;
165 p2 = strrchr(base_path, '\\');
166 if (!p1 || p2 > p1)
167 p1 = p2;
168 }
169#endif
bellard83f64092006-08-01 16:21:11 +0000170 if (p1)
171 p1++;
172 else
173 p1 = base_path;
174 if (p1 > p)
175 p = p1;
176 len = p - base_path;
177 if (len > dest_size - 1)
178 len = dest_size - 1;
179 memcpy(dest, base_path, len);
180 dest[len] = '\0';
181 pstrcat(dest, dest_size, filename);
182 }
183}
184
Anthony Liguori5efa9d52009-05-09 17:03:42 -0500185void bdrv_register(BlockDriver *bdrv)
bellardea2384d2004-08-01 21:59:26 +0000186{
Kevin Wolf68485422011-06-30 10:05:46 +0200187 if (bdrv->bdrv_co_readv) {
188 /* Emulate AIO by coroutines, and sync by AIO */
189 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
190 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
191 bdrv->bdrv_read = bdrv_read_em;
192 bdrv->bdrv_write = bdrv_write_em;
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200193 } else {
194 bdrv->bdrv_co_readv = bdrv_co_readv_em;
195 bdrv->bdrv_co_writev = bdrv_co_writev_em;
196
197 if (!bdrv->bdrv_aio_readv) {
198 /* add AIO emulation layer */
199 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
200 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
201 } else if (!bdrv->bdrv_read) {
202 /* add synchronous IO emulation layer */
203 bdrv->bdrv_read = bdrv_read_em;
204 bdrv->bdrv_write = bdrv_write_em;
205 }
bellard83f64092006-08-01 16:21:11 +0000206 }
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +0200207
208 if (!bdrv->bdrv_aio_flush)
209 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
210
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100211 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000212}
bellardb3380822004-03-14 21:38:54 +0000213
214/* create a new block device (by default it is empty) */
215BlockDriverState *bdrv_new(const char *device_name)
bellardfc01f7e2003-06-30 10:03:06 +0000216{
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100217 BlockDriverState *bs;
bellardb3380822004-03-14 21:38:54 +0000218
Anthony Liguori7267c092011-08-20 22:09:37 -0500219 bs = g_malloc0(sizeof(BlockDriverState));
bellardb3380822004-03-14 21:38:54 +0000220 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellardea2384d2004-08-01 21:59:26 +0000221 if (device_name[0] != '\0') {
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100222 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellardea2384d2004-08-01 21:59:26 +0000223 }
bellardb3380822004-03-14 21:38:54 +0000224 return bs;
225}
226
bellardea2384d2004-08-01 21:59:26 +0000227BlockDriver *bdrv_find_format(const char *format_name)
228{
229 BlockDriver *drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100230 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
231 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000232 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100233 }
bellardea2384d2004-08-01 21:59:26 +0000234 }
235 return NULL;
236}
237
Markus Armbrustereb852012009-10-27 18:41:44 +0100238static int bdrv_is_whitelisted(BlockDriver *drv)
239{
240 static const char *whitelist[] = {
241 CONFIG_BDRV_WHITELIST
242 };
243 const char **p;
244
245 if (!whitelist[0])
246 return 1; /* no whitelist, anything goes */
247
248 for (p = whitelist; *p; p++) {
249 if (!strcmp(drv->format_name, *p)) {
250 return 1;
251 }
252 }
253 return 0;
254}
255
256BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
257{
258 BlockDriver *drv = bdrv_find_format(format_name);
259 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
260}
261
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200262int bdrv_create(BlockDriver *drv, const char* filename,
263 QEMUOptionParameter *options)
bellardea2384d2004-08-01 21:59:26 +0000264{
265 if (!drv->bdrv_create)
266 return -ENOTSUP;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200267
268 return drv->bdrv_create(filename, options);
bellardea2384d2004-08-01 21:59:26 +0000269}
270
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200271int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
272{
273 BlockDriver *drv;
274
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900275 drv = bdrv_find_protocol(filename);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200276 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000277 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200278 }
279
280 return bdrv_create(drv, filename, options);
281}
282
bellardd5249392004-08-03 21:14:23 +0000283#ifdef _WIN32
bellard95389c82005-12-18 18:28:15 +0000284void get_tmp_filename(char *filename, int size)
bellardd5249392004-08-03 21:14:23 +0000285{
bellard3b9f94e2007-01-07 17:27:07 +0000286 char temp_dir[MAX_PATH];
ths3b46e622007-09-17 08:09:54 +0000287
bellard3b9f94e2007-01-07 17:27:07 +0000288 GetTempPath(MAX_PATH, temp_dir);
289 GetTempFileName(temp_dir, "qem", 0, filename);
bellardd5249392004-08-03 21:14:23 +0000290}
291#else
bellard95389c82005-12-18 18:28:15 +0000292void get_tmp_filename(char *filename, int size)
bellardea2384d2004-08-01 21:59:26 +0000293{
294 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000295 const char *tmpdir;
bellardd5249392004-08-03 21:14:23 +0000296 /* XXX: race condition possible */
aurel320badc1e2008-03-10 00:05:34 +0000297 tmpdir = getenv("TMPDIR");
298 if (!tmpdir)
299 tmpdir = "/tmp";
300 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
bellardea2384d2004-08-01 21:59:26 +0000301 fd = mkstemp(filename);
302 close(fd);
303}
bellardd5249392004-08-03 21:14:23 +0000304#endif
bellardea2384d2004-08-01 21:59:26 +0000305
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200306/*
307 * Detect host devices. By convention, /dev/cdrom[N] is always
308 * recognized as a host CDROM.
309 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200310static BlockDriver *find_hdev_driver(const char *filename)
311{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200312 int score_max = 0, score;
313 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200314
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100315 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200316 if (d->bdrv_probe_device) {
317 score = d->bdrv_probe_device(filename);
318 if (score > score_max) {
319 score_max = score;
320 drv = d;
321 }
322 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200323 }
324
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200325 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200326}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200327
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900328BlockDriver *bdrv_find_protocol(const char *filename)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200329{
330 BlockDriver *drv1;
331 char protocol[128];
332 int len;
333 const char *p;
334
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200335 /* TODO Drivers without bdrv_file_open must be specified explicitly */
336
Christoph Hellwig39508e72010-06-23 12:25:17 +0200337 /*
338 * XXX(hch): we really should not let host device detection
339 * override an explicit protocol specification, but moving this
340 * later breaks access to device names with colons in them.
341 * Thanks to the brain-dead persistent naming schemes on udev-
342 * based Linux systems those actually are quite common.
343 */
344 drv1 = find_hdev_driver(filename);
345 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200346 return drv1;
347 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200348
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000349 if (!path_has_protocol(filename)) {
Christoph Hellwig39508e72010-06-23 12:25:17 +0200350 return bdrv_find_format("file");
351 }
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000352 p = strchr(filename, ':');
353 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200354 len = p - filename;
355 if (len > sizeof(protocol) - 1)
356 len = sizeof(protocol) - 1;
357 memcpy(protocol, filename, len);
358 protocol[len] = '\0';
359 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
360 if (drv1->protocol_name &&
361 !strcmp(drv1->protocol_name, protocol)) {
362 return drv1;
363 }
364 }
365 return NULL;
366}
367
Stefan Weilc98ac352010-07-21 21:51:51 +0200368static int find_image_format(const char *filename, BlockDriver **pdrv)
bellardea2384d2004-08-01 21:59:26 +0000369{
bellard83f64092006-08-01 16:21:11 +0000370 int ret, score, score_max;
bellardea2384d2004-08-01 21:59:26 +0000371 BlockDriver *drv1, *drv;
bellard83f64092006-08-01 16:21:11 +0000372 uint8_t buf[2048];
373 BlockDriverState *bs;
ths3b46e622007-09-17 08:09:54 +0000374
Naphtali Spreif5edb012010-01-17 16:48:13 +0200375 ret = bdrv_file_open(&bs, filename, 0);
Stefan Weilc98ac352010-07-21 21:51:51 +0200376 if (ret < 0) {
377 *pdrv = NULL;
378 return ret;
379 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700380
Kevin Wolf08a00552010-06-01 18:37:31 +0200381 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382 if (bs->sg || !bdrv_is_inserted(bs)) {
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700383 bdrv_delete(bs);
Stefan Weilc98ac352010-07-21 21:51:51 +0200384 drv = bdrv_find_format("raw");
385 if (!drv) {
386 ret = -ENOENT;
387 }
388 *pdrv = drv;
389 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700390 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700391
bellard83f64092006-08-01 16:21:11 +0000392 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
393 bdrv_delete(bs);
394 if (ret < 0) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200395 *pdrv = NULL;
396 return ret;
bellard83f64092006-08-01 16:21:11 +0000397 }
398
bellardea2384d2004-08-01 21:59:26 +0000399 score_max = 0;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200400 drv = NULL;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100401 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard83f64092006-08-01 16:21:11 +0000402 if (drv1->bdrv_probe) {
403 score = drv1->bdrv_probe(buf, ret, filename);
404 if (score > score_max) {
405 score_max = score;
406 drv = drv1;
407 }
bellardea2384d2004-08-01 21:59:26 +0000408 }
409 }
Stefan Weilc98ac352010-07-21 21:51:51 +0200410 if (!drv) {
411 ret = -ENOENT;
412 }
413 *pdrv = drv;
414 return ret;
bellardea2384d2004-08-01 21:59:26 +0000415}
416
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100417/**
418 * Set the current 'total_sectors' value
419 */
420static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
421{
422 BlockDriver *drv = bs->drv;
423
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700424 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
425 if (bs->sg)
426 return 0;
427
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100428 /* query actual device if possible, otherwise just trust the hint */
429 if (drv->bdrv_getlength) {
430 int64_t length = drv->bdrv_getlength(bs);
431 if (length < 0) {
432 return length;
433 }
434 hint = length >> BDRV_SECTOR_BITS;
435 }
436
437 bs->total_sectors = hint;
438 return 0;
439}
440
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100441/**
442 * Set open flags for a given cache mode
443 *
444 * Return 0 on success, -1 if the cache mode was invalid.
445 */
446int bdrv_parse_cache_flags(const char *mode, int *flags)
447{
448 *flags &= ~BDRV_O_CACHE_MASK;
449
450 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
451 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100452 } else if (!strcmp(mode, "directsync")) {
453 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100454 } else if (!strcmp(mode, "writeback")) {
455 *flags |= BDRV_O_CACHE_WB;
456 } else if (!strcmp(mode, "unsafe")) {
457 *flags |= BDRV_O_CACHE_WB;
458 *flags |= BDRV_O_NO_FLUSH;
459 } else if (!strcmp(mode, "writethrough")) {
460 /* this is the default */
461 } else {
462 return -1;
463 }
464
465 return 0;
466}
467
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200468/*
Kevin Wolf57915332010-04-14 15:24:50 +0200469 * Common part for opening disk images and files
470 */
471static int bdrv_open_common(BlockDriverState *bs, const char *filename,
472 int flags, BlockDriver *drv)
473{
474 int ret, open_flags;
475
476 assert(drv != NULL);
477
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200478 bs->file = NULL;
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100479 bs->total_sectors = 0;
Kevin Wolf57915332010-04-14 15:24:50 +0200480 bs->encrypted = 0;
481 bs->valid_key = 0;
482 bs->open_flags = flags;
483 /* buffer_alignment defaulted to 512, drivers can change this value */
484 bs->buffer_alignment = 512;
485
486 pstrcpy(bs->filename, sizeof(bs->filename), filename);
487
488 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
489 return -ENOTSUP;
490 }
491
492 bs->drv = drv;
Anthony Liguori7267c092011-08-20 22:09:37 -0500493 bs->opaque = g_malloc0(drv->instance_size);
Kevin Wolf57915332010-04-14 15:24:50 +0200494
Christoph Hellwiga6599792011-05-17 18:04:06 +0200495 if (flags & BDRV_O_CACHE_WB)
Kevin Wolf57915332010-04-14 15:24:50 +0200496 bs->enable_write_cache = 1;
497
498 /*
499 * Clear flags that are internal to the block layer before opening the
500 * image.
501 */
502 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
503
504 /*
Stefan Weilebabb672011-04-26 10:29:36 +0200505 * Snapshots should be writable.
Kevin Wolf57915332010-04-14 15:24:50 +0200506 */
507 if (bs->is_temporary) {
508 open_flags |= BDRV_O_RDWR;
509 }
510
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200511 /* Open the image, either directly or using a protocol */
512 if (drv->bdrv_file_open) {
513 ret = drv->bdrv_file_open(bs, filename, open_flags);
514 } else {
515 ret = bdrv_file_open(&bs->file, filename, open_flags);
516 if (ret >= 0) {
517 ret = drv->bdrv_open(bs, open_flags);
518 }
519 }
520
Kevin Wolf57915332010-04-14 15:24:50 +0200521 if (ret < 0) {
522 goto free_and_fail;
523 }
524
525 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100526
527 ret = refresh_total_sectors(bs, bs->total_sectors);
528 if (ret < 0) {
529 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200530 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100531
Kevin Wolf57915332010-04-14 15:24:50 +0200532#ifndef _WIN32
533 if (bs->is_temporary) {
534 unlink(filename);
535 }
536#endif
537 return 0;
538
539free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200540 if (bs->file) {
541 bdrv_delete(bs->file);
542 bs->file = NULL;
543 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500544 g_free(bs->opaque);
Kevin Wolf57915332010-04-14 15:24:50 +0200545 bs->opaque = NULL;
546 bs->drv = NULL;
547 return ret;
548}
549
550/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200551 * Opens a file using a protocol (file, host_device, nbd, ...)
552 */
bellard83f64092006-08-01 16:21:11 +0000553int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000554{
bellard83f64092006-08-01 16:21:11 +0000555 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200556 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000557 int ret;
558
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900559 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200560 if (!drv) {
561 return -ENOENT;
562 }
563
bellard83f64092006-08-01 16:21:11 +0000564 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200565 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000566 if (ret < 0) {
567 bdrv_delete(bs);
568 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000569 }
aliguori71d07702009-03-03 17:37:16 +0000570 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000571 *pbs = bs;
572 return 0;
bellardea2384d2004-08-01 21:59:26 +0000573}
bellardfc01f7e2003-06-30 10:03:06 +0000574
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200575/*
576 * Opens a disk image (raw, qcow2, vmdk, ...)
577 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200578int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
579 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000580{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200581 int ret;
bellard712e7872005-04-28 21:09:32 +0000582
bellard83f64092006-08-01 16:21:11 +0000583 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000584 BlockDriverState *bs1;
585 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000586 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200587 BlockDriver *bdrv_qcow2;
588 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200589 char tmp_filename[PATH_MAX];
590 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000591
bellardea2384d2004-08-01 21:59:26 +0000592 /* if snapshot, we create a temporary backing file and open it
593 instead of opening 'filename' directly */
594
595 /* if there is a backing file, use it */
596 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200597 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000598 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000599 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000600 return ret;
bellardea2384d2004-08-01 21:59:26 +0000601 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200602 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000603
604 if (bs1->drv && bs1->drv->protocol_name)
605 is_protocol = 1;
606
bellardea2384d2004-08-01 21:59:26 +0000607 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000608
bellardea2384d2004-08-01 21:59:26 +0000609 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
aliguori7c96d462008-09-12 17:54:13 +0000610
611 /* Real path is meaningless for protocols */
612 if (is_protocol)
613 snprintf(backing_filename, sizeof(backing_filename),
614 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000615 else if (!realpath(filename, backing_filename))
616 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000617
Kevin Wolf91a073a2009-05-27 14:48:06 +0200618 bdrv_qcow2 = bdrv_find_format("qcow2");
619 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
620
Jes Sorensen3e829902010-05-27 16:20:30 +0200621 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200622 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
623 if (drv) {
624 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
625 drv->format_name);
626 }
627
628 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200629 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000630 if (ret < 0) {
631 return ret;
bellardea2384d2004-08-01 21:59:26 +0000632 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200633
bellardea2384d2004-08-01 21:59:26 +0000634 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200635 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000636 bs->is_temporary = 1;
637 }
bellard712e7872005-04-28 21:09:32 +0000638
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200639 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200640 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200641 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000642 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100643
aliguori51d7c002009-03-05 23:00:29 +0000644 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000645 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000646 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200647
648 /* Open the image */
649 ret = bdrv_open_common(bs, filename, flags, drv);
650 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100651 goto unlink_and_fail;
652 }
653
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200654 /* If there is a backing file, use it */
655 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
656 char backing_filename[PATH_MAX];
657 int back_flags;
658 BlockDriver *back_drv = NULL;
659
660 bs->backing_hd = bdrv_new("");
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000661
662 if (path_has_protocol(bs->backing_file)) {
663 pstrcpy(backing_filename, sizeof(backing_filename),
664 bs->backing_file);
665 } else {
666 path_combine(backing_filename, sizeof(backing_filename),
667 filename, bs->backing_file);
668 }
669
670 if (bs->backing_format[0] != '\0') {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200671 back_drv = bdrv_find_format(bs->backing_format);
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000672 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200673
674 /* backing files always opened read-only */
675 back_flags =
676 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
677
678 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
679 if (ret < 0) {
680 bdrv_close(bs);
681 return ret;
682 }
683 if (bs->is_temporary) {
684 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
685 } else {
686 /* base image inherits from "parent" */
687 bs->backing_hd->keep_read_only = bs->keep_read_only;
688 }
689 }
690
691 if (!bdrv_key_required(bs)) {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200692 bs->media_changed = 1;
Markus Armbruster0e49de52011-08-03 15:07:41 +0200693 bdrv_dev_change_cb(bs, CHANGE_MEDIA);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200694 }
695
696 return 0;
697
698unlink_and_fail:
699 if (bs->is_temporary) {
700 unlink(filename);
701 }
702 return ret;
703}
704
bellardfc01f7e2003-06-30 10:03:06 +0000705void bdrv_close(BlockDriverState *bs)
706{
bellard19cb3732006-08-19 11:45:59 +0000707 if (bs->drv) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200708 if (bs == bs_snapshots) {
709 bs_snapshots = NULL;
710 }
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100711 if (bs->backing_hd) {
bellardea2384d2004-08-01 21:59:26 +0000712 bdrv_delete(bs->backing_hd);
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100713 bs->backing_hd = NULL;
714 }
bellardea2384d2004-08-01 21:59:26 +0000715 bs->drv->bdrv_close(bs);
Anthony Liguori7267c092011-08-20 22:09:37 -0500716 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +0000717#ifdef _WIN32
718 if (bs->is_temporary) {
719 unlink(bs->filename);
720 }
bellard67b915a2004-03-31 23:37:16 +0000721#endif
bellardea2384d2004-08-01 21:59:26 +0000722 bs->opaque = NULL;
723 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +0000724
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200725 if (bs->file != NULL) {
726 bdrv_close(bs->file);
727 }
728
bellard19cb3732006-08-19 11:45:59 +0000729 bs->media_changed = 1;
Markus Armbruster0e49de52011-08-03 15:07:41 +0200730 bdrv_dev_change_cb(bs, CHANGE_MEDIA);
bellardb3380822004-03-14 21:38:54 +0000731 }
732}
733
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +0900734void bdrv_close_all(void)
735{
736 BlockDriverState *bs;
737
738 QTAILQ_FOREACH(bs, &bdrv_states, list) {
739 bdrv_close(bs);
740 }
741}
742
Ryan Harperd22b2f42011-03-29 20:51:47 -0500743/* make a BlockDriverState anonymous by removing from bdrv_state list.
744 Also, NULL terminate the device_name to prevent double remove */
745void bdrv_make_anon(BlockDriverState *bs)
746{
747 if (bs->device_name[0] != '\0') {
748 QTAILQ_REMOVE(&bdrv_states, bs, list);
749 }
750 bs->device_name[0] = '\0';
751}
752
bellardb3380822004-03-14 21:38:54 +0000753void bdrv_delete(BlockDriverState *bs)
754{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200755 assert(!bs->dev);
Markus Armbruster18846de2010-06-29 16:58:30 +0200756
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100757 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -0500758 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +0000759
bellardb3380822004-03-14 21:38:54 +0000760 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200761 if (bs->file != NULL) {
762 bdrv_delete(bs->file);
763 }
764
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200765 assert(bs != bs_snapshots);
Anthony Liguori7267c092011-08-20 22:09:37 -0500766 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +0000767}
768
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200769int bdrv_attach_dev(BlockDriverState *bs, void *dev)
770/* TODO change to DeviceState *dev when all users are qdevified */
Markus Armbruster18846de2010-06-29 16:58:30 +0200771{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200772 if (bs->dev) {
Markus Armbruster18846de2010-06-29 16:58:30 +0200773 return -EBUSY;
774 }
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200775 bs->dev = dev;
Markus Armbruster18846de2010-06-29 16:58:30 +0200776 return 0;
777}
778
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200779/* TODO qdevified devices don't use this, remove when devices are qdevified */
780void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
Markus Armbruster18846de2010-06-29 16:58:30 +0200781{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200782 if (bdrv_attach_dev(bs, dev) < 0) {
783 abort();
784 }
785}
786
787void bdrv_detach_dev(BlockDriverState *bs, void *dev)
788/* TODO change to DeviceState *dev when all users are qdevified */
789{
790 assert(bs->dev == dev);
791 bs->dev = NULL;
Markus Armbruster0e49de52011-08-03 15:07:41 +0200792 bs->dev_ops = NULL;
793 bs->dev_opaque = NULL;
Markus Armbruster18846de2010-06-29 16:58:30 +0200794}
795
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200796/* TODO change to return DeviceState * when all users are qdevified */
797void *bdrv_get_attached_dev(BlockDriverState *bs)
Markus Armbruster18846de2010-06-29 16:58:30 +0200798{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200799 return bs->dev;
Markus Armbruster18846de2010-06-29 16:58:30 +0200800}
801
Markus Armbruster0e49de52011-08-03 15:07:41 +0200802void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
803 void *opaque)
804{
805 bs->dev_ops = ops;
806 bs->dev_opaque = opaque;
807}
808
809static void bdrv_dev_change_cb(BlockDriverState *bs, int reason)
810{
811 if (bs->dev_ops && bs->dev_ops->change_cb) {
812 bs->dev_ops->change_cb(bs->dev_opaque, reason);
813 }
814}
815
aliguorie97fc192009-04-21 23:11:50 +0000816/*
817 * Run consistency checks on an image
818 *
Kevin Wolfe076f332010-06-29 11:43:13 +0200819 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +0200820 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +0200821 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +0000822 */
Kevin Wolfe076f332010-06-29 11:43:13 +0200823int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
aliguorie97fc192009-04-21 23:11:50 +0000824{
825 if (bs->drv->bdrv_check == NULL) {
826 return -ENOTSUP;
827 }
828
Kevin Wolfe076f332010-06-29 11:43:13 +0200829 memset(res, 0, sizeof(*res));
Kevin Wolf9ac228e2010-06-29 12:37:54 +0200830 return bs->drv->bdrv_check(bs, res);
aliguorie97fc192009-04-21 23:11:50 +0000831}
832
Kevin Wolf8a426612010-07-16 17:17:01 +0200833#define COMMIT_BUF_SECTORS 2048
834
bellard33e39632003-07-06 17:15:21 +0000835/* commit COW file into the raw image */
836int bdrv_commit(BlockDriverState *bs)
837{
bellard19cb3732006-08-19 11:45:59 +0000838 BlockDriver *drv = bs->drv;
Kevin Wolfee181192010-08-05 13:05:22 +0200839 BlockDriver *backing_drv;
Kevin Wolf8a426612010-07-16 17:17:01 +0200840 int64_t sector, total_sectors;
841 int n, ro, open_flags;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200842 int ret = 0, rw_ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +0200843 uint8_t *buf;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200844 char filename[1024];
845 BlockDriverState *bs_rw, *bs_ro;
bellard33e39632003-07-06 17:15:21 +0000846
bellard19cb3732006-08-19 11:45:59 +0000847 if (!drv)
848 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200849
850 if (!bs->backing_hd) {
851 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +0000852 }
853
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200854 if (bs->backing_hd->keep_read_only) {
855 return -EACCES;
856 }
Kevin Wolfee181192010-08-05 13:05:22 +0200857
858 backing_drv = bs->backing_hd->drv;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200859 ro = bs->backing_hd->read_only;
860 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
861 open_flags = bs->backing_hd->open_flags;
862
863 if (ro) {
864 /* re-open as RW */
865 bdrv_delete(bs->backing_hd);
866 bs->backing_hd = NULL;
867 bs_rw = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200868 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
869 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200870 if (rw_ret < 0) {
871 bdrv_delete(bs_rw);
872 /* try to re-open read-only */
873 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200874 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
875 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200876 if (ret < 0) {
877 bdrv_delete(bs_ro);
878 /* drive not functional anymore */
879 bs->drv = NULL;
880 return ret;
881 }
882 bs->backing_hd = bs_ro;
883 return rw_ret;
884 }
885 bs->backing_hd = bs_rw;
bellard33e39632003-07-06 17:15:21 +0000886 }
bellardea2384d2004-08-01 21:59:26 +0000887
Jan Kiszka6ea44302009-11-30 18:21:19 +0100888 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Anthony Liguori7267c092011-08-20 22:09:37 -0500889 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +0000890
Kevin Wolf8a426612010-07-16 17:17:01 +0200891 for (sector = 0; sector < total_sectors; sector += n) {
892 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
893
894 if (bdrv_read(bs, sector, buf, n) != 0) {
895 ret = -EIO;
896 goto ro_cleanup;
897 }
898
899 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
900 ret = -EIO;
901 goto ro_cleanup;
902 }
bellardea2384d2004-08-01 21:59:26 +0000903 }
904 }
bellard95389c82005-12-18 18:28:15 +0000905
Christoph Hellwig1d449522010-01-17 12:32:30 +0100906 if (drv->bdrv_make_empty) {
907 ret = drv->bdrv_make_empty(bs);
908 bdrv_flush(bs);
909 }
bellard95389c82005-12-18 18:28:15 +0000910
Christoph Hellwig3f5075a2010-01-12 13:49:23 +0100911 /*
912 * Make sure all data we wrote to the backing device is actually
913 * stable on disk.
914 */
915 if (bs->backing_hd)
916 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200917
918ro_cleanup:
Anthony Liguori7267c092011-08-20 22:09:37 -0500919 g_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200920
921 if (ro) {
922 /* re-open as RO */
923 bdrv_delete(bs->backing_hd);
924 bs->backing_hd = NULL;
925 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200926 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
927 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200928 if (ret < 0) {
929 bdrv_delete(bs_ro);
930 /* drive not functional anymore */
931 bs->drv = NULL;
932 return ret;
933 }
934 bs->backing_hd = bs_ro;
935 bs->backing_hd->keep_read_only = 0;
936 }
937
Christoph Hellwig1d449522010-01-17 12:32:30 +0100938 return ret;
bellard33e39632003-07-06 17:15:21 +0000939}
940
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +0200941void bdrv_commit_all(void)
942{
943 BlockDriverState *bs;
944
945 QTAILQ_FOREACH(bs, &bdrv_states, list) {
946 bdrv_commit(bs);
947 }
948}
949
Kevin Wolf756e6732010-01-12 12:55:17 +0100950/*
951 * Return values:
952 * 0 - success
953 * -EINVAL - backing format specified, but no file
954 * -ENOSPC - can't update the backing file because no space is left in the
955 * image file header
956 * -ENOTSUP - format driver doesn't support changing the backing file
957 */
958int bdrv_change_backing_file(BlockDriverState *bs,
959 const char *backing_file, const char *backing_fmt)
960{
961 BlockDriver *drv = bs->drv;
962
963 if (drv->bdrv_change_backing_file != NULL) {
964 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
965 } else {
966 return -ENOTSUP;
967 }
968}
969
aliguori71d07702009-03-03 17:37:16 +0000970static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
971 size_t size)
972{
973 int64_t len;
974
975 if (!bdrv_is_inserted(bs))
976 return -ENOMEDIUM;
977
978 if (bs->growable)
979 return 0;
980
981 len = bdrv_getlength(bs);
982
Kevin Wolffbb7b4e2009-05-08 14:47:24 +0200983 if (offset < 0)
984 return -EIO;
985
986 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +0000987 return -EIO;
988
989 return 0;
990}
991
992static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
993 int nb_sectors)
994{
Jes Sorenseneb5a3162010-05-27 16:20:31 +0200995 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
996 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +0000997}
998
Kevin Wolfe7a8a782011-07-15 16:05:00 +0200999static inline bool bdrv_has_async_rw(BlockDriver *drv)
1000{
1001 return drv->bdrv_co_readv != bdrv_co_readv_em
1002 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1003}
1004
1005static inline bool bdrv_has_async_flush(BlockDriver *drv)
1006{
1007 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1008}
1009
bellard19cb3732006-08-19 11:45:59 +00001010/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +00001011int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001012 uint8_t *buf, int nb_sectors)
1013{
bellardea2384d2004-08-01 21:59:26 +00001014 BlockDriver *drv = bs->drv;
1015
bellard19cb3732006-08-19 11:45:59 +00001016 if (!drv)
1017 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001018
1019 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1020 QEMUIOVector qiov;
1021 struct iovec iov = {
1022 .iov_base = (void *)buf,
1023 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1024 };
1025
1026 qemu_iovec_init_external(&qiov, &iov, 1);
1027 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1028 }
1029
aliguori71d07702009-03-03 17:37:16 +00001030 if (bdrv_check_request(bs, sector_num, nb_sectors))
1031 return -EIO;
bellardb3380822004-03-14 21:38:54 +00001032
aliguorieda578e2009-03-12 19:57:16 +00001033 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
bellardfc01f7e2003-06-30 10:03:06 +00001034}
1035
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001036static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001037 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001038{
1039 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001040 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001041
Jan Kiszka6ea44302009-11-30 18:21:19 +01001042 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001043 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001044
1045 for (; start <= end; start++) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01001046 idx = start / (sizeof(unsigned long) * 8);
1047 bit = start % (sizeof(unsigned long) * 8);
1048 val = bs->dirty_bitmap[idx];
1049 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001050 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001051 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001052 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +02001053 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001054 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001055 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001056 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001057 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +02001058 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001059 }
1060 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001061 }
1062}
1063
ths5fafdf22007-09-16 21:08:06 +00001064/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +00001065 -EIO generic I/O error (may happen for all errors)
1066 -ENOMEDIUM No media inserted.
1067 -EINVAL Invalid sector number or nb_sectors
1068 -EACCES Trying to write a read-only device
1069*/
ths5fafdf22007-09-16 21:08:06 +00001070int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001071 const uint8_t *buf, int nb_sectors)
1072{
bellard83f64092006-08-01 16:21:11 +00001073 BlockDriver *drv = bs->drv;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001074
bellard19cb3732006-08-19 11:45:59 +00001075 if (!bs->drv)
1076 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001077
1078 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1079 QEMUIOVector qiov;
1080 struct iovec iov = {
1081 .iov_base = (void *)buf,
1082 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1083 };
1084
1085 qemu_iovec_init_external(&qiov, &iov, 1);
1086 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1087 }
1088
bellard0849bf02003-06-30 23:17:31 +00001089 if (bs->read_only)
bellard19cb3732006-08-19 11:45:59 +00001090 return -EACCES;
aliguori71d07702009-03-03 17:37:16 +00001091 if (bdrv_check_request(bs, sector_num, nb_sectors))
1092 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001093
Jan Kiszkac6d22832009-11-30 18:21:20 +01001094 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001095 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1096 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001097
Kevin Wolf294cc352010-04-28 14:34:01 +02001098 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1099 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1100 }
1101
aliguori42fb2802009-01-15 20:43:39 +00001102 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
bellard83f64092006-08-01 16:21:11 +00001103}
1104
aliguorieda578e2009-03-12 19:57:16 +00001105int bdrv_pread(BlockDriverState *bs, int64_t offset,
1106 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001107{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001108 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001109 int len, nb_sectors, count;
1110 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001111 int ret;
bellard83f64092006-08-01 16:21:11 +00001112
1113 count = count1;
1114 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001115 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001116 if (len > count)
1117 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001118 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001119 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001120 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1121 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001122 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00001123 count -= len;
1124 if (count == 0)
1125 return count1;
1126 sector_num++;
1127 buf += len;
1128 }
1129
1130 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001131 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001132 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001133 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1134 return ret;
bellard83f64092006-08-01 16:21:11 +00001135 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001136 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001137 buf += len;
1138 count -= len;
1139 }
1140
1141 /* add data from the last sector */
1142 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001143 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1144 return ret;
bellard83f64092006-08-01 16:21:11 +00001145 memcpy(buf, tmp_buf, count);
1146 }
1147 return count1;
1148}
1149
aliguorieda578e2009-03-12 19:57:16 +00001150int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1151 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001152{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001153 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001154 int len, nb_sectors, count;
1155 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001156 int ret;
bellard83f64092006-08-01 16:21:11 +00001157
1158 count = count1;
1159 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001160 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001161 if (len > count)
1162 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001163 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001164 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001165 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1166 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001167 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001168 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1169 return ret;
bellard83f64092006-08-01 16:21:11 +00001170 count -= len;
1171 if (count == 0)
1172 return count1;
1173 sector_num++;
1174 buf += len;
1175 }
1176
1177 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001178 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001179 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001180 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1181 return ret;
bellard83f64092006-08-01 16:21:11 +00001182 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001183 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001184 buf += len;
1185 count -= len;
1186 }
1187
1188 /* add data from the last sector */
1189 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001190 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1191 return ret;
bellard83f64092006-08-01 16:21:11 +00001192 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001193 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1194 return ret;
bellard83f64092006-08-01 16:21:11 +00001195 }
1196 return count1;
1197}
bellard83f64092006-08-01 16:21:11 +00001198
Kevin Wolff08145f2010-06-16 16:38:15 +02001199/*
1200 * Writes to the file and ensures that no writes are reordered across this
1201 * request (acts as a barrier)
1202 *
1203 * Returns 0 on success, -errno in error cases.
1204 */
1205int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1206 const void *buf, int count)
1207{
1208 int ret;
1209
1210 ret = bdrv_pwrite(bs, offset, buf, count);
1211 if (ret < 0) {
1212 return ret;
1213 }
1214
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001215 /* No flush needed for cache modes that use O_DSYNC */
1216 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
Kevin Wolff08145f2010-06-16 16:38:15 +02001217 bdrv_flush(bs);
1218 }
1219
1220 return 0;
1221}
1222
Kevin Wolfda1fa912011-07-14 17:27:13 +02001223int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1224 int nb_sectors, QEMUIOVector *qiov)
1225{
1226 BlockDriver *drv = bs->drv;
1227
1228 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1229
1230 if (!drv) {
1231 return -ENOMEDIUM;
1232 }
1233 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1234 return -EIO;
1235 }
1236
1237 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1238}
1239
1240int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1241 int nb_sectors, QEMUIOVector *qiov)
1242{
1243 BlockDriver *drv = bs->drv;
1244
1245 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1246
1247 if (!bs->drv) {
1248 return -ENOMEDIUM;
1249 }
1250 if (bs->read_only) {
1251 return -EACCES;
1252 }
1253 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1254 return -EIO;
1255 }
1256
1257 if (bs->dirty_bitmap) {
1258 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1259 }
1260
1261 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1262 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1263 }
1264
1265 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1266}
1267
bellard83f64092006-08-01 16:21:11 +00001268/**
bellard83f64092006-08-01 16:21:11 +00001269 * Truncate file to 'offset' bytes (needed only for file protocols)
1270 */
1271int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1272{
1273 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001274 int ret;
bellard83f64092006-08-01 16:21:11 +00001275 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001276 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00001277 if (!drv->bdrv_truncate)
1278 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02001279 if (bs->read_only)
1280 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02001281 if (bdrv_in_use(bs))
1282 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001283 ret = drv->bdrv_truncate(bs, offset);
1284 if (ret == 0) {
1285 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Markus Armbruster0e49de52011-08-03 15:07:41 +02001286 bdrv_dev_change_cb(bs, CHANGE_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001287 }
1288 return ret;
bellard83f64092006-08-01 16:21:11 +00001289}
1290
1291/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08001292 * Length of a allocated file in bytes. Sparse files are counted by actual
1293 * allocated space. Return < 0 if error or unknown.
1294 */
1295int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1296{
1297 BlockDriver *drv = bs->drv;
1298 if (!drv) {
1299 return -ENOMEDIUM;
1300 }
1301 if (drv->bdrv_get_allocated_file_size) {
1302 return drv->bdrv_get_allocated_file_size(bs);
1303 }
1304 if (bs->file) {
1305 return bdrv_get_allocated_file_size(bs->file);
1306 }
1307 return -ENOTSUP;
1308}
1309
1310/**
bellard83f64092006-08-01 16:21:11 +00001311 * Length of a file in bytes. Return < 0 if error or unknown.
1312 */
1313int64_t bdrv_getlength(BlockDriverState *bs)
1314{
1315 BlockDriver *drv = bs->drv;
1316 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001317 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001318
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001319 if (bs->growable || bs->removable) {
1320 if (drv->bdrv_getlength) {
1321 return drv->bdrv_getlength(bs);
1322 }
bellard83f64092006-08-01 16:21:11 +00001323 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001324 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00001325}
1326
bellard19cb3732006-08-19 11:45:59 +00001327/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00001328void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00001329{
bellard19cb3732006-08-19 11:45:59 +00001330 int64_t length;
1331 length = bdrv_getlength(bs);
1332 if (length < 0)
1333 length = 0;
1334 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01001335 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00001336 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00001337}
bellardcf989512004-02-16 21:56:36 +00001338
aliguorif3d54fc2008-11-25 21:50:24 +00001339struct partition {
1340 uint8_t boot_ind; /* 0x80 - active */
1341 uint8_t head; /* starting head */
1342 uint8_t sector; /* starting sector */
1343 uint8_t cyl; /* starting cylinder */
1344 uint8_t sys_ind; /* What partition type */
1345 uint8_t end_head; /* end head */
1346 uint8_t end_sector; /* end sector */
1347 uint8_t end_cyl; /* end cylinder */
1348 uint32_t start_sect; /* starting sector counting from 0 */
1349 uint32_t nr_sects; /* nr of sectors in partition */
Stefan Weil541dc0d2011-08-31 12:38:01 +02001350} QEMU_PACKED;
aliguorif3d54fc2008-11-25 21:50:24 +00001351
1352/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1353static int guess_disk_lchs(BlockDriverState *bs,
1354 int *pcylinders, int *pheads, int *psectors)
1355{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001356 uint8_t buf[BDRV_SECTOR_SIZE];
aliguorif3d54fc2008-11-25 21:50:24 +00001357 int ret, i, heads, sectors, cylinders;
1358 struct partition *p;
1359 uint32_t nr_sects;
blueswir1a38131b2008-12-05 17:56:40 +00001360 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001361
1362 bdrv_get_geometry(bs, &nb_sectors);
1363
1364 ret = bdrv_read(bs, 0, buf, 1);
1365 if (ret < 0)
1366 return -1;
1367 /* test msdos magic */
1368 if (buf[510] != 0x55 || buf[511] != 0xaa)
1369 return -1;
1370 for(i = 0; i < 4; i++) {
1371 p = ((struct partition *)(buf + 0x1be)) + i;
1372 nr_sects = le32_to_cpu(p->nr_sects);
1373 if (nr_sects && p->end_head) {
1374 /* We make the assumption that the partition terminates on
1375 a cylinder boundary */
1376 heads = p->end_head + 1;
1377 sectors = p->end_sector & 63;
1378 if (sectors == 0)
1379 continue;
1380 cylinders = nb_sectors / (heads * sectors);
1381 if (cylinders < 1 || cylinders > 16383)
1382 continue;
1383 *pheads = heads;
1384 *psectors = sectors;
1385 *pcylinders = cylinders;
1386#if 0
1387 printf("guessed geometry: LCHS=%d %d %d\n",
1388 cylinders, heads, sectors);
1389#endif
1390 return 0;
1391 }
1392 }
1393 return -1;
1394}
1395
1396void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1397{
1398 int translation, lba_detected = 0;
1399 int cylinders, heads, secs;
blueswir1a38131b2008-12-05 17:56:40 +00001400 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001401
1402 /* if a geometry hint is available, use it */
1403 bdrv_get_geometry(bs, &nb_sectors);
1404 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1405 translation = bdrv_get_translation_hint(bs);
1406 if (cylinders != 0) {
1407 *pcyls = cylinders;
1408 *pheads = heads;
1409 *psecs = secs;
1410 } else {
1411 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1412 if (heads > 16) {
1413 /* if heads > 16, it means that a BIOS LBA
1414 translation was active, so the default
1415 hardware geometry is OK */
1416 lba_detected = 1;
1417 goto default_geometry;
1418 } else {
1419 *pcyls = cylinders;
1420 *pheads = heads;
1421 *psecs = secs;
1422 /* disable any translation to be in sync with
1423 the logical geometry */
1424 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1425 bdrv_set_translation_hint(bs,
1426 BIOS_ATA_TRANSLATION_NONE);
1427 }
1428 }
1429 } else {
1430 default_geometry:
1431 /* if no geometry, use a standard physical disk geometry */
1432 cylinders = nb_sectors / (16 * 63);
1433
1434 if (cylinders > 16383)
1435 cylinders = 16383;
1436 else if (cylinders < 2)
1437 cylinders = 2;
1438 *pcyls = cylinders;
1439 *pheads = 16;
1440 *psecs = 63;
1441 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1442 if ((*pcyls * *pheads) <= 131072) {
1443 bdrv_set_translation_hint(bs,
1444 BIOS_ATA_TRANSLATION_LARGE);
1445 } else {
1446 bdrv_set_translation_hint(bs,
1447 BIOS_ATA_TRANSLATION_LBA);
1448 }
1449 }
1450 }
1451 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1452 }
1453}
1454
ths5fafdf22007-09-16 21:08:06 +00001455void bdrv_set_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001456 int cyls, int heads, int secs)
1457{
1458 bs->cyls = cyls;
1459 bs->heads = heads;
1460 bs->secs = secs;
1461}
1462
bellard46d47672004-11-16 01:45:27 +00001463void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1464{
1465 bs->translation = translation;
1466}
1467
ths5fafdf22007-09-16 21:08:06 +00001468void bdrv_get_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001469 int *pcyls, int *pheads, int *psecs)
1470{
1471 *pcyls = bs->cyls;
1472 *pheads = bs->heads;
1473 *psecs = bs->secs;
1474}
1475
Blue Swirl5bbdbb42011-02-12 20:43:32 +00001476/* Recognize floppy formats */
1477typedef struct FDFormat {
1478 FDriveType drive;
1479 uint8_t last_sect;
1480 uint8_t max_track;
1481 uint8_t max_head;
1482} FDFormat;
1483
1484static const FDFormat fd_formats[] = {
1485 /* First entry is default format */
1486 /* 1.44 MB 3"1/2 floppy disks */
1487 { FDRIVE_DRV_144, 18, 80, 1, },
1488 { FDRIVE_DRV_144, 20, 80, 1, },
1489 { FDRIVE_DRV_144, 21, 80, 1, },
1490 { FDRIVE_DRV_144, 21, 82, 1, },
1491 { FDRIVE_DRV_144, 21, 83, 1, },
1492 { FDRIVE_DRV_144, 22, 80, 1, },
1493 { FDRIVE_DRV_144, 23, 80, 1, },
1494 { FDRIVE_DRV_144, 24, 80, 1, },
1495 /* 2.88 MB 3"1/2 floppy disks */
1496 { FDRIVE_DRV_288, 36, 80, 1, },
1497 { FDRIVE_DRV_288, 39, 80, 1, },
1498 { FDRIVE_DRV_288, 40, 80, 1, },
1499 { FDRIVE_DRV_288, 44, 80, 1, },
1500 { FDRIVE_DRV_288, 48, 80, 1, },
1501 /* 720 kB 3"1/2 floppy disks */
1502 { FDRIVE_DRV_144, 9, 80, 1, },
1503 { FDRIVE_DRV_144, 10, 80, 1, },
1504 { FDRIVE_DRV_144, 10, 82, 1, },
1505 { FDRIVE_DRV_144, 10, 83, 1, },
1506 { FDRIVE_DRV_144, 13, 80, 1, },
1507 { FDRIVE_DRV_144, 14, 80, 1, },
1508 /* 1.2 MB 5"1/4 floppy disks */
1509 { FDRIVE_DRV_120, 15, 80, 1, },
1510 { FDRIVE_DRV_120, 18, 80, 1, },
1511 { FDRIVE_DRV_120, 18, 82, 1, },
1512 { FDRIVE_DRV_120, 18, 83, 1, },
1513 { FDRIVE_DRV_120, 20, 80, 1, },
1514 /* 720 kB 5"1/4 floppy disks */
1515 { FDRIVE_DRV_120, 9, 80, 1, },
1516 { FDRIVE_DRV_120, 11, 80, 1, },
1517 /* 360 kB 5"1/4 floppy disks */
1518 { FDRIVE_DRV_120, 9, 40, 1, },
1519 { FDRIVE_DRV_120, 9, 40, 0, },
1520 { FDRIVE_DRV_120, 10, 41, 1, },
1521 { FDRIVE_DRV_120, 10, 42, 1, },
1522 /* 320 kB 5"1/4 floppy disks */
1523 { FDRIVE_DRV_120, 8, 40, 1, },
1524 { FDRIVE_DRV_120, 8, 40, 0, },
1525 /* 360 kB must match 5"1/4 better than 3"1/2... */
1526 { FDRIVE_DRV_144, 9, 80, 0, },
1527 /* end */
1528 { FDRIVE_DRV_NONE, -1, -1, 0, },
1529};
1530
1531void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1532 int *max_track, int *last_sect,
1533 FDriveType drive_in, FDriveType *drive)
1534{
1535 const FDFormat *parse;
1536 uint64_t nb_sectors, size;
1537 int i, first_match, match;
1538
1539 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1540 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1541 /* User defined disk */
1542 } else {
1543 bdrv_get_geometry(bs, &nb_sectors);
1544 match = -1;
1545 first_match = -1;
1546 for (i = 0; ; i++) {
1547 parse = &fd_formats[i];
1548 if (parse->drive == FDRIVE_DRV_NONE) {
1549 break;
1550 }
1551 if (drive_in == parse->drive ||
1552 drive_in == FDRIVE_DRV_NONE) {
1553 size = (parse->max_head + 1) * parse->max_track *
1554 parse->last_sect;
1555 if (nb_sectors == size) {
1556 match = i;
1557 break;
1558 }
1559 if (first_match == -1) {
1560 first_match = i;
1561 }
1562 }
1563 }
1564 if (match == -1) {
1565 if (first_match == -1) {
1566 match = 1;
1567 } else {
1568 match = first_match;
1569 }
1570 parse = &fd_formats[match];
1571 }
1572 *nb_heads = parse->max_head + 1;
1573 *max_track = parse->max_track;
1574 *last_sect = parse->last_sect;
1575 *drive = parse->drive;
1576 }
1577}
1578
bellard46d47672004-11-16 01:45:27 +00001579int bdrv_get_translation_hint(BlockDriverState *bs)
1580{
1581 return bs->translation;
1582}
1583
Markus Armbrusterabd7f682010-06-02 18:55:17 +02001584void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1585 BlockErrorAction on_write_error)
1586{
1587 bs->on_read_error = on_read_error;
1588 bs->on_write_error = on_write_error;
1589}
1590
1591BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1592{
1593 return is_read ? bs->on_read_error : bs->on_write_error;
1594}
1595
Markus Armbruster7d0d6952010-06-25 13:42:14 +02001596void bdrv_set_removable(BlockDriverState *bs, int removable)
1597{
1598 bs->removable = removable;
1599 if (removable && bs == bs_snapshots) {
1600 bs_snapshots = NULL;
1601 }
1602}
1603
bellardb3380822004-03-14 21:38:54 +00001604int bdrv_is_removable(BlockDriverState *bs)
1605{
1606 return bs->removable;
1607}
1608
1609int bdrv_is_read_only(BlockDriverState *bs)
1610{
1611 return bs->read_only;
1612}
1613
ths985a03b2007-12-24 16:10:43 +00001614int bdrv_is_sg(BlockDriverState *bs)
1615{
1616 return bs->sg;
1617}
1618
Christoph Hellwige900a7b2009-09-04 19:01:15 +02001619int bdrv_enable_write_cache(BlockDriverState *bs)
1620{
1621 return bs->enable_write_cache;
1622}
1623
bellardea2384d2004-08-01 21:59:26 +00001624int bdrv_is_encrypted(BlockDriverState *bs)
1625{
1626 if (bs->backing_hd && bs->backing_hd->encrypted)
1627 return 1;
1628 return bs->encrypted;
1629}
1630
aliguoric0f4ce72009-03-05 23:01:01 +00001631int bdrv_key_required(BlockDriverState *bs)
1632{
1633 BlockDriverState *backing_hd = bs->backing_hd;
1634
1635 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1636 return 1;
1637 return (bs->encrypted && !bs->valid_key);
1638}
1639
bellardea2384d2004-08-01 21:59:26 +00001640int bdrv_set_key(BlockDriverState *bs, const char *key)
1641{
1642 int ret;
1643 if (bs->backing_hd && bs->backing_hd->encrypted) {
1644 ret = bdrv_set_key(bs->backing_hd, key);
1645 if (ret < 0)
1646 return ret;
1647 if (!bs->encrypted)
1648 return 0;
1649 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02001650 if (!bs->encrypted) {
1651 return -EINVAL;
1652 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1653 return -ENOMEDIUM;
1654 }
aliguoric0f4ce72009-03-05 23:01:01 +00001655 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00001656 if (ret < 0) {
1657 bs->valid_key = 0;
1658 } else if (!bs->valid_key) {
1659 bs->valid_key = 1;
1660 /* call the change callback now, we skipped it on open */
1661 bs->media_changed = 1;
Markus Armbruster0e49de52011-08-03 15:07:41 +02001662 bdrv_dev_change_cb(bs, CHANGE_MEDIA);
aliguoribb5fc202009-03-05 23:01:15 +00001663 }
aliguoric0f4ce72009-03-05 23:01:01 +00001664 return ret;
bellardea2384d2004-08-01 21:59:26 +00001665}
1666
1667void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1668{
bellard19cb3732006-08-19 11:45:59 +00001669 if (!bs->drv) {
bellardea2384d2004-08-01 21:59:26 +00001670 buf[0] = '\0';
1671 } else {
1672 pstrcpy(buf, buf_size, bs->drv->format_name);
1673 }
1674}
1675
ths5fafdf22007-09-16 21:08:06 +00001676void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00001677 void *opaque)
1678{
1679 BlockDriver *drv;
1680
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01001681 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00001682 it(opaque, drv->format_name);
1683 }
1684}
1685
bellardb3380822004-03-14 21:38:54 +00001686BlockDriverState *bdrv_find(const char *name)
1687{
1688 BlockDriverState *bs;
1689
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001690 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1691 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00001692 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001693 }
bellardb3380822004-03-14 21:38:54 +00001694 }
1695 return NULL;
1696}
1697
Markus Armbruster2f399b02010-06-02 18:55:20 +02001698BlockDriverState *bdrv_next(BlockDriverState *bs)
1699{
1700 if (!bs) {
1701 return QTAILQ_FIRST(&bdrv_states);
1702 }
1703 return QTAILQ_NEXT(bs, list);
1704}
1705
aliguori51de9762009-03-05 23:00:43 +00001706void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00001707{
1708 BlockDriverState *bs;
1709
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001710 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00001711 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00001712 }
1713}
1714
bellardea2384d2004-08-01 21:59:26 +00001715const char *bdrv_get_device_name(BlockDriverState *bs)
1716{
1717 return bs->device_name;
1718}
1719
Kevin Wolf205ef792010-10-21 16:43:43 +02001720int bdrv_flush(BlockDriverState *bs)
pbrook7a6cba62006-06-04 11:39:07 +00001721{
Alexander Graf016f5cf2010-05-26 17:51:49 +02001722 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolf205ef792010-10-21 16:43:43 +02001723 return 0;
Alexander Graf016f5cf2010-05-26 17:51:49 +02001724 }
1725
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001726 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1727 return bdrv_co_flush_em(bs);
1728 }
1729
Kevin Wolf205ef792010-10-21 16:43:43 +02001730 if (bs->drv && bs->drv->bdrv_flush) {
1731 return bs->drv->bdrv_flush(bs);
1732 }
1733
1734 /*
1735 * Some block drivers always operate in either writethrough or unsafe mode
1736 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1737 * the server works (because the behaviour is hardcoded or depends on
1738 * server-side configuration), so we can't ensure that everything is safe
1739 * on disk. Returning an error doesn't work because that would break guests
1740 * even if the server operates in writethrough mode.
1741 *
1742 * Let's hope the user knows what he's doing.
1743 */
1744 return 0;
pbrook7a6cba62006-06-04 11:39:07 +00001745}
1746
aliguoric6ca28d2008-10-06 13:55:43 +00001747void bdrv_flush_all(void)
1748{
1749 BlockDriverState *bs;
1750
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001751 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1752 if (bs->drv && !bdrv_is_read_only(bs) &&
1753 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
aliguoric6ca28d2008-10-06 13:55:43 +00001754 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001755 }
1756 }
aliguoric6ca28d2008-10-06 13:55:43 +00001757}
1758
Kevin Wolff2feebb2010-04-14 17:30:35 +02001759int bdrv_has_zero_init(BlockDriverState *bs)
1760{
1761 assert(bs->drv);
1762
Kevin Wolf336c1c12010-07-28 11:26:29 +02001763 if (bs->drv->bdrv_has_zero_init) {
1764 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02001765 }
1766
1767 return 1;
1768}
1769
Christoph Hellwigbb8bf762010-12-16 19:36:31 +01001770int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1771{
1772 if (!bs->drv) {
1773 return -ENOMEDIUM;
1774 }
1775 if (!bs->drv->bdrv_discard) {
1776 return 0;
1777 }
1778 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1779}
1780
thsf58c7b32008-06-05 21:53:49 +00001781/*
1782 * Returns true iff the specified sector is present in the disk image. Drivers
1783 * not implementing the functionality are assumed to not support backing files,
1784 * hence all their sectors are reported as allocated.
1785 *
1786 * 'pnum' is set to the number of sectors (including and immediately following
1787 * the specified sector) that are known to be in the same
1788 * allocated/unallocated state.
1789 *
1790 * 'nb_sectors' is the max value 'pnum' should be set to.
1791 */
1792int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1793 int *pnum)
1794{
1795 int64_t n;
1796 if (!bs->drv->bdrv_is_allocated) {
1797 if (sector_num >= bs->total_sectors) {
1798 *pnum = 0;
1799 return 0;
1800 }
1801 n = bs->total_sectors - sector_num;
1802 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1803 return 1;
1804 }
1805 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1806}
1807
Luiz Capitulino2582bfe2010-02-03 12:41:01 -02001808void bdrv_mon_event(const BlockDriverState *bdrv,
1809 BlockMonEventAction action, int is_read)
1810{
1811 QObject *data;
1812 const char *action_str;
1813
1814 switch (action) {
1815 case BDRV_ACTION_REPORT:
1816 action_str = "report";
1817 break;
1818 case BDRV_ACTION_IGNORE:
1819 action_str = "ignore";
1820 break;
1821 case BDRV_ACTION_STOP:
1822 action_str = "stop";
1823 break;
1824 default:
1825 abort();
1826 }
1827
1828 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1829 bdrv->device_name,
1830 action_str,
1831 is_read ? "read" : "write");
1832 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1833
1834 qobject_decref(data);
1835}
1836
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001837static void bdrv_print_dict(QObject *obj, void *opaque)
bellardb3380822004-03-14 21:38:54 +00001838{
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001839 QDict *bs_dict;
1840 Monitor *mon = opaque;
1841
1842 bs_dict = qobject_to_qdict(obj);
1843
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001844 monitor_printf(mon, "%s: removable=%d",
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001845 qdict_get_str(bs_dict, "device"),
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001846 qdict_get_bool(bs_dict, "removable"));
1847
1848 if (qdict_get_bool(bs_dict, "removable")) {
1849 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1850 }
1851
1852 if (qdict_haskey(bs_dict, "inserted")) {
1853 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1854
1855 monitor_printf(mon, " file=");
1856 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1857 if (qdict_haskey(qdict, "backing_file")) {
1858 monitor_printf(mon, " backing_file=");
1859 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1860 }
1861 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1862 qdict_get_bool(qdict, "ro"),
1863 qdict_get_str(qdict, "drv"),
1864 qdict_get_bool(qdict, "encrypted"));
1865 } else {
1866 monitor_printf(mon, " [not inserted]");
1867 }
1868
1869 monitor_printf(mon, "\n");
1870}
1871
1872void bdrv_info_print(Monitor *mon, const QObject *data)
1873{
1874 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1875}
1876
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001877void bdrv_info(Monitor *mon, QObject **ret_data)
1878{
1879 QList *bs_list;
bellardb3380822004-03-14 21:38:54 +00001880 BlockDriverState *bs;
1881
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001882 bs_list = qlist_new();
1883
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001884 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001885 QObject *bs_obj;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001886
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001887 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001888 "'removable': %i, 'locked': %i }",
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001889 bs->device_name, bs->removable,
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001890 bs->locked);
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001891
bellard19cb3732006-08-19 11:45:59 +00001892 if (bs->drv) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001893 QObject *obj;
1894 QDict *bs_dict = qobject_to_qdict(bs_obj);
1895
1896 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1897 "'encrypted': %i }",
1898 bs->filename, bs->read_only,
1899 bs->drv->format_name,
1900 bdrv_is_encrypted(bs));
thsfef30742006-12-22 14:11:32 +00001901 if (bs->backing_file[0] != '\0') {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001902 QDict *qdict = qobject_to_qdict(obj);
1903 qdict_put(qdict, "backing_file",
1904 qstring_from_str(bs->backing_file));
aliguori376253e2009-03-05 23:01:23 +00001905 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001906
1907 qdict_put_obj(bs_dict, "inserted", obj);
bellardb3380822004-03-14 21:38:54 +00001908 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001909 qlist_append_obj(bs_list, bs_obj);
bellardb3380822004-03-14 21:38:54 +00001910 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001911
1912 *ret_data = QOBJECT(bs_list);
bellardb3380822004-03-14 21:38:54 +00001913}
thsa36e69d2007-12-02 05:18:19 +00001914
Luiz Capitulino218a5362009-12-10 17:16:07 -02001915static void bdrv_stats_iter(QObject *data, void *opaque)
thsa36e69d2007-12-02 05:18:19 +00001916{
Luiz Capitulino218a5362009-12-10 17:16:07 -02001917 QDict *qdict;
1918 Monitor *mon = opaque;
1919
1920 qdict = qobject_to_qdict(data);
1921 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1922
1923 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1924 monitor_printf(mon, " rd_bytes=%" PRId64
1925 " wr_bytes=%" PRId64
1926 " rd_operations=%" PRId64
1927 " wr_operations=%" PRId64
Christoph Hellwige8045d62011-08-22 00:25:58 +02001928 " flush_operations=%" PRId64
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001929 " wr_total_time_ns=%" PRId64
1930 " rd_total_time_ns=%" PRId64
1931 " flush_total_time_ns=%" PRId64
Luiz Capitulino218a5362009-12-10 17:16:07 -02001932 "\n",
1933 qdict_get_int(qdict, "rd_bytes"),
1934 qdict_get_int(qdict, "wr_bytes"),
1935 qdict_get_int(qdict, "rd_operations"),
Christoph Hellwige8045d62011-08-22 00:25:58 +02001936 qdict_get_int(qdict, "wr_operations"),
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001937 qdict_get_int(qdict, "flush_operations"),
1938 qdict_get_int(qdict, "wr_total_time_ns"),
1939 qdict_get_int(qdict, "rd_total_time_ns"),
1940 qdict_get_int(qdict, "flush_total_time_ns"));
Luiz Capitulino218a5362009-12-10 17:16:07 -02001941}
1942
1943void bdrv_stats_print(Monitor *mon, const QObject *data)
1944{
1945 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1946}
1947
Kevin Wolf294cc352010-04-28 14:34:01 +02001948static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1949{
1950 QObject *res;
1951 QDict *dict;
1952
1953 res = qobject_from_jsonf("{ 'stats': {"
1954 "'rd_bytes': %" PRId64 ","
1955 "'wr_bytes': %" PRId64 ","
1956 "'rd_operations': %" PRId64 ","
1957 "'wr_operations': %" PRId64 ","
Christoph Hellwige8045d62011-08-22 00:25:58 +02001958 "'wr_highest_offset': %" PRId64 ","
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001959 "'flush_operations': %" PRId64 ","
1960 "'wr_total_time_ns': %" PRId64 ","
1961 "'rd_total_time_ns': %" PRId64 ","
1962 "'flush_total_time_ns': %" PRId64
Kevin Wolf294cc352010-04-28 14:34:01 +02001963 "} }",
Christoph Hellwiga597e792011-08-25 08:26:01 +02001964 bs->nr_bytes[BDRV_ACCT_READ],
1965 bs->nr_bytes[BDRV_ACCT_WRITE],
1966 bs->nr_ops[BDRV_ACCT_READ],
1967 bs->nr_ops[BDRV_ACCT_WRITE],
Blue Swirl5ffbbc62010-06-14 18:55:33 +00001968 bs->wr_highest_sector *
Christoph Hellwige8045d62011-08-22 00:25:58 +02001969 (uint64_t)BDRV_SECTOR_SIZE,
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001970 bs->nr_ops[BDRV_ACCT_FLUSH],
1971 bs->total_time_ns[BDRV_ACCT_WRITE],
1972 bs->total_time_ns[BDRV_ACCT_READ],
1973 bs->total_time_ns[BDRV_ACCT_FLUSH]);
Kevin Wolf294cc352010-04-28 14:34:01 +02001974 dict = qobject_to_qdict(res);
1975
1976 if (*bs->device_name) {
1977 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1978 }
1979
1980 if (bs->file) {
1981 QObject *parent = bdrv_info_stats_bs(bs->file);
1982 qdict_put_obj(dict, "parent", parent);
1983 }
1984
1985 return res;
1986}
1987
Luiz Capitulino218a5362009-12-10 17:16:07 -02001988void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1989{
1990 QObject *obj;
1991 QList *devices;
thsa36e69d2007-12-02 05:18:19 +00001992 BlockDriverState *bs;
1993
Luiz Capitulino218a5362009-12-10 17:16:07 -02001994 devices = qlist_new();
1995
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001996 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Kevin Wolf294cc352010-04-28 14:34:01 +02001997 obj = bdrv_info_stats_bs(bs);
Luiz Capitulino218a5362009-12-10 17:16:07 -02001998 qlist_append_obj(devices, obj);
thsa36e69d2007-12-02 05:18:19 +00001999 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02002000
2001 *ret_data = QOBJECT(devices);
thsa36e69d2007-12-02 05:18:19 +00002002}
bellardea2384d2004-08-01 21:59:26 +00002003
aliguori045df332009-03-05 23:00:48 +00002004const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2005{
2006 if (bs->backing_hd && bs->backing_hd->encrypted)
2007 return bs->backing_file;
2008 else if (bs->encrypted)
2009 return bs->filename;
2010 else
2011 return NULL;
2012}
2013
ths5fafdf22007-09-16 21:08:06 +00002014void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00002015 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00002016{
Kevin Wolfb783e402010-01-12 12:55:16 +01002017 if (!bs->backing_file) {
bellard83f64092006-08-01 16:21:11 +00002018 pstrcpy(filename, filename_size, "");
2019 } else {
2020 pstrcpy(filename, filename_size, bs->backing_file);
2021 }
bellardea2384d2004-08-01 21:59:26 +00002022}
2023
ths5fafdf22007-09-16 21:08:06 +00002024int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00002025 const uint8_t *buf, int nb_sectors)
2026{
2027 BlockDriver *drv = bs->drv;
2028 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002029 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002030 if (!drv->bdrv_write_compressed)
2031 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02002032 if (bdrv_check_request(bs, sector_num, nb_sectors))
2033 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002034
Jan Kiszkac6d22832009-11-30 18:21:20 +01002035 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002036 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2037 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002038
bellardfaea38e2006-08-05 21:31:00 +00002039 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2040}
ths3b46e622007-09-17 08:09:54 +00002041
bellardfaea38e2006-08-05 21:31:00 +00002042int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2043{
2044 BlockDriver *drv = bs->drv;
2045 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002046 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002047 if (!drv->bdrv_get_info)
2048 return -ENOTSUP;
2049 memset(bdi, 0, sizeof(*bdi));
2050 return drv->bdrv_get_info(bs, bdi);
2051}
2052
Christoph Hellwig45566e92009-07-10 23:11:57 +02002053int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2054 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002055{
2056 BlockDriver *drv = bs->drv;
2057 if (!drv)
2058 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002059 if (drv->bdrv_save_vmstate)
2060 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2061 if (bs->file)
2062 return bdrv_save_vmstate(bs->file, buf, pos, size);
2063 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002064}
2065
Christoph Hellwig45566e92009-07-10 23:11:57 +02002066int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2067 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002068{
2069 BlockDriver *drv = bs->drv;
2070 if (!drv)
2071 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002072 if (drv->bdrv_load_vmstate)
2073 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2074 if (bs->file)
2075 return bdrv_load_vmstate(bs->file, buf, pos, size);
2076 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002077}
2078
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01002079void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2080{
2081 BlockDriver *drv = bs->drv;
2082
2083 if (!drv || !drv->bdrv_debug_event) {
2084 return;
2085 }
2086
2087 return drv->bdrv_debug_event(bs, event);
2088
2089}
2090
bellardfaea38e2006-08-05 21:31:00 +00002091/**************************************************************/
2092/* handling of snapshots */
2093
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002094int bdrv_can_snapshot(BlockDriverState *bs)
2095{
2096 BlockDriver *drv = bs->drv;
2097 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
2098 return 0;
2099 }
2100
2101 if (!drv->bdrv_snapshot_create) {
2102 if (bs->file != NULL) {
2103 return bdrv_can_snapshot(bs->file);
2104 }
2105 return 0;
2106 }
2107
2108 return 1;
2109}
2110
Blue Swirl199630b2010-07-25 20:49:34 +00002111int bdrv_is_snapshot(BlockDriverState *bs)
2112{
2113 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2114}
2115
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002116BlockDriverState *bdrv_snapshots(void)
2117{
2118 BlockDriverState *bs;
2119
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002120 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002121 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002122 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002123
2124 bs = NULL;
2125 while ((bs = bdrv_next(bs))) {
2126 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002127 bs_snapshots = bs;
2128 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002129 }
2130 }
2131 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002132}
2133
ths5fafdf22007-09-16 21:08:06 +00002134int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002135 QEMUSnapshotInfo *sn_info)
2136{
2137 BlockDriver *drv = bs->drv;
2138 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002139 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002140 if (drv->bdrv_snapshot_create)
2141 return drv->bdrv_snapshot_create(bs, sn_info);
2142 if (bs->file)
2143 return bdrv_snapshot_create(bs->file, sn_info);
2144 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002145}
2146
ths5fafdf22007-09-16 21:08:06 +00002147int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002148 const char *snapshot_id)
2149{
2150 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002151 int ret, open_ret;
2152
bellardfaea38e2006-08-05 21:31:00 +00002153 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002154 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002155 if (drv->bdrv_snapshot_goto)
2156 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2157
2158 if (bs->file) {
2159 drv->bdrv_close(bs);
2160 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2161 open_ret = drv->bdrv_open(bs, bs->open_flags);
2162 if (open_ret < 0) {
2163 bdrv_delete(bs->file);
2164 bs->drv = NULL;
2165 return open_ret;
2166 }
2167 return ret;
2168 }
2169
2170 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002171}
2172
2173int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2174{
2175 BlockDriver *drv = bs->drv;
2176 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002177 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002178 if (drv->bdrv_snapshot_delete)
2179 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2180 if (bs->file)
2181 return bdrv_snapshot_delete(bs->file, snapshot_id);
2182 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002183}
2184
ths5fafdf22007-09-16 21:08:06 +00002185int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002186 QEMUSnapshotInfo **psn_info)
2187{
2188 BlockDriver *drv = bs->drv;
2189 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002190 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002191 if (drv->bdrv_snapshot_list)
2192 return drv->bdrv_snapshot_list(bs, psn_info);
2193 if (bs->file)
2194 return bdrv_snapshot_list(bs->file, psn_info);
2195 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002196}
2197
edison51ef6722010-09-21 19:58:41 -07002198int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2199 const char *snapshot_name)
2200{
2201 BlockDriver *drv = bs->drv;
2202 if (!drv) {
2203 return -ENOMEDIUM;
2204 }
2205 if (!bs->read_only) {
2206 return -EINVAL;
2207 }
2208 if (drv->bdrv_snapshot_load_tmp) {
2209 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2210 }
2211 return -ENOTSUP;
2212}
2213
bellardfaea38e2006-08-05 21:31:00 +00002214#define NB_SUFFIXES 4
2215
2216char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2217{
2218 static const char suffixes[NB_SUFFIXES] = "KMGT";
2219 int64_t base;
2220 int i;
2221
2222 if (size <= 999) {
2223 snprintf(buf, buf_size, "%" PRId64, size);
2224 } else {
2225 base = 1024;
2226 for(i = 0; i < NB_SUFFIXES; i++) {
2227 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00002228 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00002229 (double)size / base,
2230 suffixes[i]);
2231 break;
2232 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00002233 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00002234 ((size + (base >> 1)) / base),
2235 suffixes[i]);
2236 break;
2237 }
2238 base = base * 1024;
2239 }
2240 }
2241 return buf;
2242}
2243
2244char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2245{
2246 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00002247#ifdef _WIN32
2248 struct tm *ptm;
2249#else
bellardfaea38e2006-08-05 21:31:00 +00002250 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00002251#endif
bellardfaea38e2006-08-05 21:31:00 +00002252 time_t ti;
2253 int64_t secs;
2254
2255 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00002256 snprintf(buf, buf_size,
2257 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002258 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2259 } else {
2260 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00002261#ifdef _WIN32
2262 ptm = localtime(&ti);
2263 strftime(date_buf, sizeof(date_buf),
2264 "%Y-%m-%d %H:%M:%S", ptm);
2265#else
bellardfaea38e2006-08-05 21:31:00 +00002266 localtime_r(&ti, &tm);
2267 strftime(date_buf, sizeof(date_buf),
2268 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00002269#endif
bellardfaea38e2006-08-05 21:31:00 +00002270 secs = sn->vm_clock_nsec / 1000000000;
2271 snprintf(clock_buf, sizeof(clock_buf),
2272 "%02d:%02d:%02d.%03d",
2273 (int)(secs / 3600),
2274 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00002275 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00002276 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2277 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00002278 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002279 sn->id_str, sn->name,
2280 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2281 date_buf,
2282 clock_buf);
2283 }
2284 return buf;
2285}
2286
bellard83f64092006-08-01 16:21:11 +00002287/**************************************************************/
2288/* async I/Os */
2289
aliguori3b69e4b2009-01-22 16:59:24 +00002290BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00002291 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00002292 BlockDriverCompletionFunc *cb, void *opaque)
2293{
bellard83f64092006-08-01 16:21:11 +00002294 BlockDriver *drv = bs->drv;
bellard83f64092006-08-01 16:21:11 +00002295
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002296 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2297
bellard19cb3732006-08-19 11:45:59 +00002298 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002299 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002300 if (bdrv_check_request(bs, sector_num, nb_sectors))
2301 return NULL;
ths3b46e622007-09-17 08:09:54 +00002302
Christoph Hellwiga597e792011-08-25 08:26:01 +02002303 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2304 cb, opaque);
bellard83f64092006-08-01 16:21:11 +00002305}
2306
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002307typedef struct BlockCompleteData {
2308 BlockDriverCompletionFunc *cb;
2309 void *opaque;
2310 BlockDriverState *bs;
2311 int64_t sector_num;
2312 int nb_sectors;
2313} BlockCompleteData;
2314
2315static void block_complete_cb(void *opaque, int ret)
2316{
2317 BlockCompleteData *b = opaque;
2318
2319 if (b->bs->dirty_bitmap) {
2320 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2321 }
2322 b->cb(b->opaque, ret);
Anthony Liguori7267c092011-08-20 22:09:37 -05002323 g_free(b);
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002324}
2325
2326static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2327 int64_t sector_num,
2328 int nb_sectors,
2329 BlockDriverCompletionFunc *cb,
2330 void *opaque)
2331{
Anthony Liguori7267c092011-08-20 22:09:37 -05002332 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002333
2334 blkdata->bs = bs;
2335 blkdata->cb = cb;
2336 blkdata->opaque = opaque;
2337 blkdata->sector_num = sector_num;
2338 blkdata->nb_sectors = nb_sectors;
2339
2340 return blkdata;
2341}
2342
aliguorif141eaf2009-04-07 18:43:24 +00002343BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2344 QEMUIOVector *qiov, int nb_sectors,
2345 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002346{
bellard83f64092006-08-01 16:21:11 +00002347 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002348 BlockDriverAIOCB *ret;
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002349 BlockCompleteData *blk_cb_data;
bellard83f64092006-08-01 16:21:11 +00002350
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002351 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2352
bellard19cb3732006-08-19 11:45:59 +00002353 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002354 return NULL;
bellard83f64092006-08-01 16:21:11 +00002355 if (bs->read_only)
pbrookce1a14d2006-08-07 02:38:06 +00002356 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002357 if (bdrv_check_request(bs, sector_num, nb_sectors))
2358 return NULL;
bellard83f64092006-08-01 16:21:11 +00002359
Jan Kiszkac6d22832009-11-30 18:21:20 +01002360 if (bs->dirty_bitmap) {
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002361 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2362 opaque);
2363 cb = &block_complete_cb;
2364 opaque = blk_cb_data;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002365 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002366
aliguorif141eaf2009-04-07 18:43:24 +00002367 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2368 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002369
2370 if (ret) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002371 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2372 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2373 }
thsa36e69d2007-12-02 05:18:19 +00002374 }
2375
2376 return ret;
bellard83f64092006-08-01 16:21:11 +00002377}
2378
Kevin Wolf40b4f532009-09-09 17:53:37 +02002379
2380typedef struct MultiwriteCB {
2381 int error;
2382 int num_requests;
2383 int num_callbacks;
2384 struct {
2385 BlockDriverCompletionFunc *cb;
2386 void *opaque;
2387 QEMUIOVector *free_qiov;
2388 void *free_buf;
2389 } callbacks[];
2390} MultiwriteCB;
2391
2392static void multiwrite_user_cb(MultiwriteCB *mcb)
2393{
2394 int i;
2395
2396 for (i = 0; i < mcb->num_callbacks; i++) {
2397 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01002398 if (mcb->callbacks[i].free_qiov) {
2399 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2400 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002401 g_free(mcb->callbacks[i].free_qiov);
Herve Poussineauf8a83242010-01-24 21:23:56 +00002402 qemu_vfree(mcb->callbacks[i].free_buf);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002403 }
2404}
2405
2406static void multiwrite_cb(void *opaque, int ret)
2407{
2408 MultiwriteCB *mcb = opaque;
2409
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002410 trace_multiwrite_cb(mcb, ret);
2411
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02002412 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02002413 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002414 }
2415
2416 mcb->num_requests--;
2417 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02002418 multiwrite_user_cb(mcb);
Anthony Liguori7267c092011-08-20 22:09:37 -05002419 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002420 }
2421}
2422
2423static int multiwrite_req_compare(const void *a, const void *b)
2424{
Christoph Hellwig77be4362010-05-19 20:53:10 +02002425 const BlockRequest *req1 = a, *req2 = b;
2426
2427 /*
2428 * Note that we can't simply subtract req2->sector from req1->sector
2429 * here as that could overflow the return value.
2430 */
2431 if (req1->sector > req2->sector) {
2432 return 1;
2433 } else if (req1->sector < req2->sector) {
2434 return -1;
2435 } else {
2436 return 0;
2437 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002438}
2439
2440/*
2441 * Takes a bunch of requests and tries to merge them. Returns the number of
2442 * requests that remain after merging.
2443 */
2444static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2445 int num_reqs, MultiwriteCB *mcb)
2446{
2447 int i, outidx;
2448
2449 // Sort requests by start sector
2450 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2451
2452 // Check if adjacent requests touch the same clusters. If so, combine them,
2453 // filling up gaps with zero sectors.
2454 outidx = 0;
2455 for (i = 1; i < num_reqs; i++) {
2456 int merge = 0;
2457 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2458
2459 // This handles the cases that are valid for all block drivers, namely
2460 // exactly sequential writes and overlapping writes.
2461 if (reqs[i].sector <= oldreq_last) {
2462 merge = 1;
2463 }
2464
2465 // The block driver may decide that it makes sense to combine requests
2466 // even if there is a gap of some sectors between them. In this case,
2467 // the gap is filled with zeros (therefore only applicable for yet
2468 // unused space in format like qcow2).
2469 if (!merge && bs->drv->bdrv_merge_requests) {
2470 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2471 }
2472
Christoph Hellwige2a305f2010-01-26 14:49:08 +01002473 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2474 merge = 0;
2475 }
2476
Kevin Wolf40b4f532009-09-09 17:53:37 +02002477 if (merge) {
2478 size_t size;
Anthony Liguori7267c092011-08-20 22:09:37 -05002479 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002480 qemu_iovec_init(qiov,
2481 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2482
2483 // Add the first request to the merged one. If the requests are
2484 // overlapping, drop the last sectors of the first request.
2485 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2486 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2487
2488 // We might need to add some zeros between the two requests
2489 if (reqs[i].sector > oldreq_last) {
2490 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2491 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2492 memset(buf, 0, zero_bytes);
2493 qemu_iovec_add(qiov, buf, zero_bytes);
2494 mcb->callbacks[i].free_buf = buf;
2495 }
2496
2497 // Add the second request
2498 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2499
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02002500 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002501 reqs[outidx].qiov = qiov;
2502
2503 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2504 } else {
2505 outidx++;
2506 reqs[outidx].sector = reqs[i].sector;
2507 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2508 reqs[outidx].qiov = reqs[i].qiov;
2509 }
2510 }
2511
2512 return outidx + 1;
2513}
2514
2515/*
2516 * Submit multiple AIO write requests at once.
2517 *
2518 * On success, the function returns 0 and all requests in the reqs array have
2519 * been submitted. In error case this function returns -1, and any of the
2520 * requests may or may not be submitted yet. In particular, this means that the
2521 * callback will be called for some of the requests, for others it won't. The
2522 * caller must check the error field of the BlockRequest to wait for the right
2523 * callbacks (if error != 0, no callback will be called).
2524 *
2525 * The implementation may modify the contents of the reqs array, e.g. to merge
2526 * requests. However, the fields opaque and error are left unmodified as they
2527 * are used to signal failure for a single request to the caller.
2528 */
2529int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2530{
2531 BlockDriverAIOCB *acb;
2532 MultiwriteCB *mcb;
2533 int i;
2534
Ryan Harper301db7c2011-03-07 10:01:04 -06002535 /* don't submit writes if we don't have a medium */
2536 if (bs->drv == NULL) {
2537 for (i = 0; i < num_reqs; i++) {
2538 reqs[i].error = -ENOMEDIUM;
2539 }
2540 return -1;
2541 }
2542
Kevin Wolf40b4f532009-09-09 17:53:37 +02002543 if (num_reqs == 0) {
2544 return 0;
2545 }
2546
2547 // Create MultiwriteCB structure
Anthony Liguori7267c092011-08-20 22:09:37 -05002548 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002549 mcb->num_requests = 0;
2550 mcb->num_callbacks = num_reqs;
2551
2552 for (i = 0; i < num_reqs; i++) {
2553 mcb->callbacks[i].cb = reqs[i].cb;
2554 mcb->callbacks[i].opaque = reqs[i].opaque;
2555 }
2556
2557 // Check for mergable requests
2558 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2559
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002560 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2561
Kevin Wolf453f9a12010-07-02 14:01:21 +02002562 /*
2563 * Run the aio requests. As soon as one request can't be submitted
2564 * successfully, fail all requests that are not yet submitted (we must
2565 * return failure for all requests anyway)
2566 *
2567 * num_requests cannot be set to the right value immediately: If
2568 * bdrv_aio_writev fails for some request, num_requests would be too high
2569 * and therefore multiwrite_cb() would never recognize the multiwrite
2570 * request as completed. We also cannot use the loop variable i to set it
2571 * when the first request fails because the callback may already have been
2572 * called for previously submitted requests. Thus, num_requests must be
2573 * incremented for each request that is submitted.
2574 *
2575 * The problem that callbacks may be called early also means that we need
2576 * to take care that num_requests doesn't become 0 before all requests are
2577 * submitted - multiwrite_cb() would consider the multiwrite request
2578 * completed. A dummy request that is "completed" by a manual call to
2579 * multiwrite_cb() takes care of this.
2580 */
2581 mcb->num_requests = 1;
2582
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002583 // Run the aio requests
Kevin Wolf40b4f532009-09-09 17:53:37 +02002584 for (i = 0; i < num_reqs; i++) {
Kevin Wolf453f9a12010-07-02 14:01:21 +02002585 mcb->num_requests++;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002586 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2587 reqs[i].nb_sectors, multiwrite_cb, mcb);
2588
2589 if (acb == NULL) {
2590 // We can only fail the whole thing if no request has been
2591 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2592 // complete and report the error in the callback.
Kevin Wolf453f9a12010-07-02 14:01:21 +02002593 if (i == 0) {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002594 trace_bdrv_aio_multiwrite_earlyfail(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002595 goto fail;
2596 } else {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002597 trace_bdrv_aio_multiwrite_latefail(mcb, i);
Kevin Wolf7eb58a62010-04-06 18:24:07 +02002598 multiwrite_cb(mcb, -EIO);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002599 break;
2600 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002601 }
2602 }
2603
Kevin Wolf453f9a12010-07-02 14:01:21 +02002604 /* Complete the dummy request */
2605 multiwrite_cb(mcb, 0);
2606
Kevin Wolf40b4f532009-09-09 17:53:37 +02002607 return 0;
2608
2609fail:
Kevin Wolf453f9a12010-07-02 14:01:21 +02002610 for (i = 0; i < mcb->num_callbacks; i++) {
2611 reqs[i].error = -EIO;
2612 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002613 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002614 return -1;
2615}
2616
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002617BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2618 BlockDriverCompletionFunc *cb, void *opaque)
2619{
2620 BlockDriver *drv = bs->drv;
2621
Stefan Hajnoczia13aac02011-03-07 07:58:04 +00002622 trace_bdrv_aio_flush(bs, opaque);
2623
Alexander Graf016f5cf2010-05-26 17:51:49 +02002624 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2625 return bdrv_aio_noop_em(bs, cb, opaque);
2626 }
2627
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002628 if (!drv)
2629 return NULL;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002630 return drv->bdrv_aio_flush(bs, cb, opaque);
2631}
2632
bellard83f64092006-08-01 16:21:11 +00002633void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00002634{
aliguori6bbff9a2009-03-20 18:25:59 +00002635 acb->pool->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00002636}
2637
pbrookce1a14d2006-08-07 02:38:06 +00002638
bellard83f64092006-08-01 16:21:11 +00002639/**************************************************************/
2640/* async block device emulation */
2641
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002642typedef struct BlockDriverAIOCBSync {
2643 BlockDriverAIOCB common;
2644 QEMUBH *bh;
2645 int ret;
2646 /* vector translation state */
2647 QEMUIOVector *qiov;
2648 uint8_t *bounce;
2649 int is_write;
2650} BlockDriverAIOCBSync;
2651
2652static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2653{
Kevin Wolfb666d232010-05-05 11:44:39 +02002654 BlockDriverAIOCBSync *acb =
2655 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03002656 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002657 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002658 qemu_aio_release(acb);
2659}
2660
2661static AIOPool bdrv_em_aio_pool = {
2662 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2663 .cancel = bdrv_aio_cancel_em,
2664};
2665
bellard83f64092006-08-01 16:21:11 +00002666static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00002667{
pbrookce1a14d2006-08-07 02:38:06 +00002668 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00002669
aliguorif141eaf2009-04-07 18:43:24 +00002670 if (!acb->is_write)
2671 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00002672 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00002673 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03002674 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002675 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00002676 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00002677}
bellardbeac80c2006-06-26 20:08:57 +00002678
aliguorif141eaf2009-04-07 18:43:24 +00002679static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2680 int64_t sector_num,
2681 QEMUIOVector *qiov,
2682 int nb_sectors,
2683 BlockDriverCompletionFunc *cb,
2684 void *opaque,
2685 int is_write)
2686
bellardea2384d2004-08-01 21:59:26 +00002687{
pbrookce1a14d2006-08-07 02:38:06 +00002688 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00002689
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002690 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00002691 acb->is_write = is_write;
2692 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00002693 acb->bounce = qemu_blockalign(bs, qiov->size);
aliguorif141eaf2009-04-07 18:43:24 +00002694
pbrookce1a14d2006-08-07 02:38:06 +00002695 if (!acb->bh)
2696 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00002697
2698 if (is_write) {
2699 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2700 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2701 } else {
2702 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2703 }
2704
pbrookce1a14d2006-08-07 02:38:06 +00002705 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00002706
pbrookce1a14d2006-08-07 02:38:06 +00002707 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00002708}
2709
aliguorif141eaf2009-04-07 18:43:24 +00002710static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2711 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00002712 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002713{
aliguorif141eaf2009-04-07 18:43:24 +00002714 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00002715}
2716
aliguorif141eaf2009-04-07 18:43:24 +00002717static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2718 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2719 BlockDriverCompletionFunc *cb, void *opaque)
2720{
2721 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2722}
2723
Kevin Wolf68485422011-06-30 10:05:46 +02002724
2725typedef struct BlockDriverAIOCBCoroutine {
2726 BlockDriverAIOCB common;
2727 BlockRequest req;
2728 bool is_write;
2729 QEMUBH* bh;
2730} BlockDriverAIOCBCoroutine;
2731
2732static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2733{
2734 qemu_aio_flush();
2735}
2736
2737static AIOPool bdrv_em_co_aio_pool = {
2738 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2739 .cancel = bdrv_aio_co_cancel_em,
2740};
2741
2742static void bdrv_co_rw_bh(void *opaque)
2743{
2744 BlockDriverAIOCBCoroutine *acb = opaque;
2745
2746 acb->common.cb(acb->common.opaque, acb->req.error);
2747 qemu_bh_delete(acb->bh);
2748 qemu_aio_release(acb);
2749}
2750
2751static void coroutine_fn bdrv_co_rw(void *opaque)
2752{
2753 BlockDriverAIOCBCoroutine *acb = opaque;
2754 BlockDriverState *bs = acb->common.bs;
2755
2756 if (!acb->is_write) {
2757 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2758 acb->req.nb_sectors, acb->req.qiov);
2759 } else {
2760 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2761 acb->req.nb_sectors, acb->req.qiov);
2762 }
2763
2764 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2765 qemu_bh_schedule(acb->bh);
2766}
2767
2768static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2769 int64_t sector_num,
2770 QEMUIOVector *qiov,
2771 int nb_sectors,
2772 BlockDriverCompletionFunc *cb,
2773 void *opaque,
2774 bool is_write)
2775{
2776 Coroutine *co;
2777 BlockDriverAIOCBCoroutine *acb;
2778
2779 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2780 acb->req.sector = sector_num;
2781 acb->req.nb_sectors = nb_sectors;
2782 acb->req.qiov = qiov;
2783 acb->is_write = is_write;
2784
2785 co = qemu_coroutine_create(bdrv_co_rw);
2786 qemu_coroutine_enter(co, acb);
2787
2788 return &acb->common;
2789}
2790
2791static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2792 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2793 BlockDriverCompletionFunc *cb, void *opaque)
2794{
2795 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2796 false);
2797}
2798
2799static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2800 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2801 BlockDriverCompletionFunc *cb, void *opaque)
2802{
2803 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2804 true);
2805}
2806
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002807static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2808 BlockDriverCompletionFunc *cb, void *opaque)
2809{
2810 BlockDriverAIOCBSync *acb;
2811
2812 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2813 acb->is_write = 1; /* don't bounce in the completion hadler */
2814 acb->qiov = NULL;
2815 acb->bounce = NULL;
2816 acb->ret = 0;
2817
2818 if (!acb->bh)
2819 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2820
2821 bdrv_flush(bs);
2822 qemu_bh_schedule(acb->bh);
2823 return &acb->common;
2824}
2825
Alexander Graf016f5cf2010-05-26 17:51:49 +02002826static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2827 BlockDriverCompletionFunc *cb, void *opaque)
2828{
2829 BlockDriverAIOCBSync *acb;
2830
2831 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2832 acb->is_write = 1; /* don't bounce in the completion handler */
2833 acb->qiov = NULL;
2834 acb->bounce = NULL;
2835 acb->ret = 0;
2836
2837 if (!acb->bh) {
2838 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2839 }
2840
2841 qemu_bh_schedule(acb->bh);
2842 return &acb->common;
2843}
2844
bellard83f64092006-08-01 16:21:11 +00002845/**************************************************************/
2846/* sync block device emulation */
2847
2848static void bdrv_rw_em_cb(void *opaque, int ret)
2849{
2850 *(int *)opaque = ret;
2851}
2852
2853#define NOT_DONE 0x7fffffff
2854
ths5fafdf22007-09-16 21:08:06 +00002855static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +00002856 uint8_t *buf, int nb_sectors)
2857{
pbrookce1a14d2006-08-07 02:38:06 +00002858 int async_ret;
2859 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002860 struct iovec iov;
2861 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002862
bellard83f64092006-08-01 16:21:11 +00002863 async_ret = NOT_DONE;
blueswir13f4cb3d2009-04-13 16:31:01 +00002864 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002865 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002866 qemu_iovec_init_external(&qiov, &iov, 1);
2867 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2868 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002869 if (acb == NULL) {
2870 async_ret = -1;
2871 goto fail;
2872 }
aliguoribaf35cb2008-09-10 15:45:19 +00002873
bellard83f64092006-08-01 16:21:11 +00002874 while (async_ret == NOT_DONE) {
2875 qemu_aio_wait();
2876 }
aliguoribaf35cb2008-09-10 15:45:19 +00002877
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002878
2879fail:
bellard83f64092006-08-01 16:21:11 +00002880 return async_ret;
2881}
2882
2883static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2884 const uint8_t *buf, int nb_sectors)
2885{
pbrookce1a14d2006-08-07 02:38:06 +00002886 int async_ret;
2887 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002888 struct iovec iov;
2889 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002890
bellard83f64092006-08-01 16:21:11 +00002891 async_ret = NOT_DONE;
aliguorif141eaf2009-04-07 18:43:24 +00002892 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002893 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002894 qemu_iovec_init_external(&qiov, &iov, 1);
2895 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2896 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002897 if (acb == NULL) {
2898 async_ret = -1;
2899 goto fail;
2900 }
bellard83f64092006-08-01 16:21:11 +00002901 while (async_ret == NOT_DONE) {
2902 qemu_aio_wait();
2903 }
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002904
2905fail:
bellard83f64092006-08-01 16:21:11 +00002906 return async_ret;
2907}
bellardea2384d2004-08-01 21:59:26 +00002908
2909void bdrv_init(void)
2910{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05002911 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00002912}
pbrookce1a14d2006-08-07 02:38:06 +00002913
Markus Armbrustereb852012009-10-27 18:41:44 +01002914void bdrv_init_with_whitelist(void)
2915{
2916 use_bdrv_whitelist = 1;
2917 bdrv_init();
2918}
2919
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002920void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2921 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00002922{
pbrookce1a14d2006-08-07 02:38:06 +00002923 BlockDriverAIOCB *acb;
2924
aliguori6bbff9a2009-03-20 18:25:59 +00002925 if (pool->free_aiocb) {
2926 acb = pool->free_aiocb;
2927 pool->free_aiocb = acb->next;
pbrookce1a14d2006-08-07 02:38:06 +00002928 } else {
Anthony Liguori7267c092011-08-20 22:09:37 -05002929 acb = g_malloc0(pool->aiocb_size);
aliguori6bbff9a2009-03-20 18:25:59 +00002930 acb->pool = pool;
pbrookce1a14d2006-08-07 02:38:06 +00002931 }
2932 acb->bs = bs;
2933 acb->cb = cb;
2934 acb->opaque = opaque;
2935 return acb;
2936}
2937
2938void qemu_aio_release(void *p)
2939{
aliguori6bbff9a2009-03-20 18:25:59 +00002940 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2941 AIOPool *pool = acb->pool;
2942 acb->next = pool->free_aiocb;
2943 pool->free_aiocb = acb;
pbrookce1a14d2006-08-07 02:38:06 +00002944}
bellard19cb3732006-08-19 11:45:59 +00002945
2946/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02002947/* Coroutine block device emulation */
2948
2949typedef struct CoroutineIOCompletion {
2950 Coroutine *coroutine;
2951 int ret;
2952} CoroutineIOCompletion;
2953
2954static void bdrv_co_io_em_complete(void *opaque, int ret)
2955{
2956 CoroutineIOCompletion *co = opaque;
2957
2958 co->ret = ret;
2959 qemu_coroutine_enter(co->coroutine, NULL);
2960}
2961
2962static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2963 int nb_sectors, QEMUIOVector *iov,
2964 bool is_write)
2965{
2966 CoroutineIOCompletion co = {
2967 .coroutine = qemu_coroutine_self(),
2968 };
2969 BlockDriverAIOCB *acb;
2970
2971 if (is_write) {
2972 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2973 bdrv_co_io_em_complete, &co);
2974 } else {
2975 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2976 bdrv_co_io_em_complete, &co);
2977 }
2978
2979 trace_bdrv_co_io(is_write, acb);
2980 if (!acb) {
2981 return -EIO;
2982 }
2983 qemu_coroutine_yield();
2984
2985 return co.ret;
2986}
2987
2988static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2989 int64_t sector_num, int nb_sectors,
2990 QEMUIOVector *iov)
2991{
2992 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2993}
2994
2995static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2996 int64_t sector_num, int nb_sectors,
2997 QEMUIOVector *iov)
2998{
2999 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3000}
3001
Kevin Wolfe7a8a782011-07-15 16:05:00 +02003002static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3003{
3004 CoroutineIOCompletion co = {
3005 .coroutine = qemu_coroutine_self(),
3006 };
3007 BlockDriverAIOCB *acb;
3008
3009 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3010 if (!acb) {
3011 return -EIO;
3012 }
3013 qemu_coroutine_yield();
3014 return co.ret;
3015}
3016
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003017/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00003018/* removable device support */
3019
3020/**
3021 * Return TRUE if the media is present
3022 */
3023int bdrv_is_inserted(BlockDriverState *bs)
3024{
3025 BlockDriver *drv = bs->drv;
3026 int ret;
3027 if (!drv)
3028 return 0;
3029 if (!drv->bdrv_is_inserted)
Markus Armbruster4be97622010-07-27 14:02:01 +02003030 return !bs->tray_open;
bellard19cb3732006-08-19 11:45:59 +00003031 ret = drv->bdrv_is_inserted(bs);
3032 return ret;
3033}
3034
3035/**
3036 * Return TRUE if the media changed since the last call to this
ths5fafdf22007-09-16 21:08:06 +00003037 * function. It is currently only used for floppy disks
bellard19cb3732006-08-19 11:45:59 +00003038 */
3039int bdrv_media_changed(BlockDriverState *bs)
3040{
3041 BlockDriver *drv = bs->drv;
3042 int ret;
3043
3044 if (!drv || !drv->bdrv_media_changed)
3045 ret = -ENOTSUP;
3046 else
3047 ret = drv->bdrv_media_changed(bs);
3048 if (ret == -ENOTSUP)
3049 ret = bs->media_changed;
3050 bs->media_changed = 0;
3051 return ret;
3052}
3053
3054/**
3055 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3056 */
Mark McLoughlinaea2a332009-05-27 10:06:11 +01003057int bdrv_eject(BlockDriverState *bs, int eject_flag)
bellard19cb3732006-08-19 11:45:59 +00003058{
3059 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003060
Markus Armbruster49aa46b2011-07-20 18:23:43 +02003061 if (eject_flag && bs->locked) {
Mark McLoughlinaea2a332009-05-27 10:06:11 +01003062 return -EBUSY;
3063 }
3064
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003065 if (drv && drv->bdrv_eject) {
3066 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00003067 }
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003068 bs->tray_open = eject_flag;
3069 return 0;
bellard19cb3732006-08-19 11:45:59 +00003070}
3071
3072int bdrv_is_locked(BlockDriverState *bs)
3073{
3074 return bs->locked;
3075}
3076
3077/**
3078 * Lock or unlock the media (if it is locked, the user won't be able
3079 * to eject it manually).
3080 */
3081void bdrv_set_locked(BlockDriverState *bs, int locked)
3082{
3083 BlockDriver *drv = bs->drv;
3084
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01003085 trace_bdrv_set_locked(bs, locked);
3086
bellard19cb3732006-08-19 11:45:59 +00003087 bs->locked = locked;
3088 if (drv && drv->bdrv_set_locked) {
3089 drv->bdrv_set_locked(bs, locked);
3090 }
3091}
ths985a03b2007-12-24 16:10:43 +00003092
3093/* needed for generic scsi interface */
3094
3095int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3096{
3097 BlockDriver *drv = bs->drv;
3098
3099 if (drv && drv->bdrv_ioctl)
3100 return drv->bdrv_ioctl(bs, req, buf);
3101 return -ENOTSUP;
3102}
aliguori7d780662009-03-12 19:57:08 +00003103
aliguori221f7152009-03-28 17:28:41 +00003104BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3105 unsigned long int req, void *buf,
3106 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00003107{
aliguori221f7152009-03-28 17:28:41 +00003108 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00003109
aliguori221f7152009-03-28 17:28:41 +00003110 if (drv && drv->bdrv_aio_ioctl)
3111 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3112 return NULL;
aliguori7d780662009-03-12 19:57:08 +00003113}
aliguorie268ca52009-04-22 20:20:00 +00003114
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003115
3116
aliguorie268ca52009-04-22 20:20:00 +00003117void *qemu_blockalign(BlockDriverState *bs, size_t size)
3118{
3119 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3120}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003121
3122void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3123{
3124 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003125
Liran Schouraaa0eb72010-01-26 10:31:48 +02003126 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003127 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003128 if (!bs->dirty_bitmap) {
3129 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3130 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3131 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003132
Anthony Liguori7267c092011-08-20 22:09:37 -05003133 bs->dirty_bitmap = g_malloc0(bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003134 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003135 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003136 if (bs->dirty_bitmap) {
Anthony Liguori7267c092011-08-20 22:09:37 -05003137 g_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01003138 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003139 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003140 }
3141}
3142
3143int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3144{
Jan Kiszka6ea44302009-11-30 18:21:19 +01003145 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003146
Jan Kiszkac6d22832009-11-30 18:21:20 +01003147 if (bs->dirty_bitmap &&
3148 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02003149 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3150 (1UL << (chunk % (sizeof(unsigned long) * 8))));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003151 } else {
3152 return 0;
3153 }
3154}
3155
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003156void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3157 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003158{
3159 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3160}
Liran Schouraaa0eb72010-01-26 10:31:48 +02003161
3162int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3163{
3164 return bs->dirty_count;
3165}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003166
Marcelo Tosattidb593f22011-01-26 12:12:34 -02003167void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3168{
3169 assert(bs->in_use != in_use);
3170 bs->in_use = in_use;
3171}
3172
3173int bdrv_in_use(BlockDriverState *bs)
3174{
3175 return bs->in_use;
3176}
3177
Christoph Hellwiga597e792011-08-25 08:26:01 +02003178void
3179bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3180 enum BlockAcctType type)
3181{
3182 assert(type < BDRV_MAX_IOTYPE);
3183
3184 cookie->bytes = bytes;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003185 cookie->start_time_ns = get_clock();
Christoph Hellwiga597e792011-08-25 08:26:01 +02003186 cookie->type = type;
3187}
3188
3189void
3190bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3191{
3192 assert(cookie->type < BDRV_MAX_IOTYPE);
3193
3194 bs->nr_bytes[cookie->type] += cookie->bytes;
3195 bs->nr_ops[cookie->type]++;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003196 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
Christoph Hellwiga597e792011-08-25 08:26:01 +02003197}
3198
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003199int bdrv_img_create(const char *filename, const char *fmt,
3200 const char *base_filename, const char *base_fmt,
3201 char *options, uint64_t img_size, int flags)
3202{
3203 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02003204 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003205 BlockDriverState *bs = NULL;
3206 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003207 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003208 int ret = 0;
3209
3210 /* Find driver and parse its options */
3211 drv = bdrv_find_format(fmt);
3212 if (!drv) {
3213 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003214 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003215 goto out;
3216 }
3217
3218 proto_drv = bdrv_find_protocol(filename);
3219 if (!proto_drv) {
3220 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003221 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003222 goto out;
3223 }
3224
3225 create_options = append_option_parameters(create_options,
3226 drv->create_options);
3227 create_options = append_option_parameters(create_options,
3228 proto_drv->create_options);
3229
3230 /* Create parameter list with default values */
3231 param = parse_option_parameters("", create_options, param);
3232
3233 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3234
3235 /* Parse -o options */
3236 if (options) {
3237 param = parse_option_parameters(options, create_options, param);
3238 if (param == NULL) {
3239 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003240 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003241 goto out;
3242 }
3243 }
3244
3245 if (base_filename) {
3246 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3247 base_filename)) {
3248 error_report("Backing file not supported for file format '%s'",
3249 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003250 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003251 goto out;
3252 }
3253 }
3254
3255 if (base_fmt) {
3256 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3257 error_report("Backing file format not supported for file "
3258 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003259 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003260 goto out;
3261 }
3262 }
3263
Jes Sorensen792da932010-12-16 13:52:17 +01003264 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3265 if (backing_file && backing_file->value.s) {
3266 if (!strcmp(filename, backing_file->value.s)) {
3267 error_report("Error: Trying to create an image with the "
3268 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003269 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01003270 goto out;
3271 }
3272 }
3273
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003274 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3275 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003276 backing_drv = bdrv_find_format(backing_fmt->value.s);
3277 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003278 error_report("Unknown backing file format '%s'",
3279 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003280 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003281 goto out;
3282 }
3283 }
3284
3285 // The size for the image must always be specified, with one exception:
3286 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02003287 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3288 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003289 if (backing_file && backing_file->value.s) {
3290 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003291 char buf[32];
3292
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003293 bs = bdrv_new("");
3294
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003295 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003296 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003297 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003298 goto out;
3299 }
3300 bdrv_get_geometry(bs, &size);
3301 size *= 512;
3302
3303 snprintf(buf, sizeof(buf), "%" PRId64, size);
3304 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3305 } else {
3306 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003307 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003308 goto out;
3309 }
3310 }
3311
3312 printf("Formatting '%s', fmt=%s ", filename, fmt);
3313 print_option_parameters(param);
3314 puts("");
3315
3316 ret = bdrv_create(drv, filename, param);
3317
3318 if (ret < 0) {
3319 if (ret == -ENOTSUP) {
3320 error_report("Formatting or formatting option not supported for "
3321 "file format '%s'", fmt);
3322 } else if (ret == -EFBIG) {
3323 error_report("The image size is too large for file format '%s'",
3324 fmt);
3325 } else {
3326 error_report("%s: error while creating %s: %s", filename, fmt,
3327 strerror(-ret));
3328 }
3329 }
3330
3331out:
3332 free_option_parameters(create_options);
3333 free_option_parameters(param);
3334
3335 if (bs) {
3336 bdrv_delete(bs);
3337 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01003338
3339 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003340}