blob: 1ae22d5d2a08381779229a783edae111de662461 [file] [log] [blame]
bellardfc01f7e2003-06-30 10:03:06 +00001/*
2 * QEMU System Emulator block driver
ths5fafdf22007-09-16 21:08:06 +00003 *
bellardfc01f7e2003-06-30 10:03:06 +00004 * Copyright (c) 2003 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardfc01f7e2003-06-30 10:03:06 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
blueswir13990d092008-12-05 17:53:21 +000024#include "config-host.h"
pbrookfaf07962007-11-11 02:51:17 +000025#include "qemu-common.h"
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +010026#include "trace.h"
aliguori376253e2009-03-05 23:01:23 +000027#include "monitor.h"
bellardea2384d2004-08-01 21:59:26 +000028#include "block_int.h"
Anthony Liguori5efa9d52009-05-09 17:03:42 -050029#include "module.h"
Luiz Capitulinod15e5462009-12-10 17:16:06 -020030#include "qemu-objects.h"
Kevin Wolf68485422011-06-30 10:05:46 +020031#include "qemu-coroutine.h"
bellardfc01f7e2003-06-30 10:03:06 +000032
Juan Quintela71e72a12009-07-27 16:12:56 +020033#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000034#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000037#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000038#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000039#include <sys/disk.h>
40#endif
blueswir1c5e97232009-03-07 20:06:23 +000041#endif
bellard7674e7b2005-04-26 21:59:26 +000042
aliguori49dc7682009-03-08 16:26:59 +000043#ifdef _WIN32
44#include <windows.h>
45#endif
46
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +020047static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
aliguorif141eaf2009-04-07 18:43:24 +000048static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
aliguoric87c0672009-04-07 18:43:20 +000050 BlockDriverCompletionFunc *cb, void *opaque);
aliguorif141eaf2009-04-07 18:43:24 +000051static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +000053 BlockDriverCompletionFunc *cb, void *opaque);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +020054static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55 BlockDriverCompletionFunc *cb, void *opaque);
Alexander Graf016f5cf2010-05-26 17:51:49 +020056static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57 BlockDriverCompletionFunc *cb, void *opaque);
ths5fafdf22007-09-16 21:08:06 +000058static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +000059 uint8_t *buf, int nb_sectors);
60static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61 const uint8_t *buf, int nb_sectors);
Kevin Wolf68485422011-06-30 10:05:46 +020062static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64 BlockDriverCompletionFunc *cb, void *opaque);
65static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67 BlockDriverCompletionFunc *cb, void *opaque);
Kevin Wolff9f05dc2011-07-15 13:50:26 +020068static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69 int64_t sector_num, int nb_sectors,
70 QEMUIOVector *iov);
71static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72 int64_t sector_num, int nb_sectors,
73 QEMUIOVector *iov);
Kevin Wolfe7a8a782011-07-15 16:05:00 +020074static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
bellardec530c82006-04-25 22:36:06 +000075
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +010076static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(bdrv_states);
blueswir17ee930d2008-09-17 19:04:14 +000078
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010079static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000081
Markus Armbrusterf9092b12010-06-25 10:33:39 +020082/* The device to use for VM snapshots */
83static BlockDriverState *bs_snapshots;
84
Markus Armbrustereb852012009-10-27 18:41:44 +010085/* If non-zero, use only whitelisted block drivers */
86static int use_bdrv_whitelist;
87
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000088#ifdef _WIN32
89static int is_windows_drive_prefix(const char *filename)
90{
91 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
93 filename[1] == ':');
94}
95
96int is_windows_drive(const char *filename)
97{
98 if (is_windows_drive_prefix(filename) &&
99 filename[2] == '\0')
100 return 1;
101 if (strstart(filename, "\\\\.\\", NULL) ||
102 strstart(filename, "//./", NULL))
103 return 1;
104 return 0;
105}
106#endif
107
108/* check if the path starts with "<protocol>:" */
109static int path_has_protocol(const char *path)
110{
111#ifdef _WIN32
112 if (is_windows_drive(path) ||
113 is_windows_drive_prefix(path)) {
114 return 0;
115 }
116#endif
117
118 return strchr(path, ':') != NULL;
119}
120
bellard83f64092006-08-01 16:21:11 +0000121int path_is_absolute(const char *path)
122{
123 const char *p;
bellard21664422007-01-07 18:22:37 +0000124#ifdef _WIN32
125 /* specific case for names like: "\\.\d:" */
126 if (*path == '/' || *path == '\\')
127 return 1;
128#endif
bellard83f64092006-08-01 16:21:11 +0000129 p = strchr(path, ':');
130 if (p)
131 p++;
132 else
133 p = path;
bellard3b9f94e2007-01-07 17:27:07 +0000134#ifdef _WIN32
135 return (*p == '/' || *p == '\\');
136#else
137 return (*p == '/');
138#endif
bellard83f64092006-08-01 16:21:11 +0000139}
140
141/* if filename is absolute, just copy it to dest. Otherwise, build a
142 path to it by considering it is relative to base_path. URL are
143 supported. */
144void path_combine(char *dest, int dest_size,
145 const char *base_path,
146 const char *filename)
147{
148 const char *p, *p1;
149 int len;
150
151 if (dest_size <= 0)
152 return;
153 if (path_is_absolute(filename)) {
154 pstrcpy(dest, dest_size, filename);
155 } else {
156 p = strchr(base_path, ':');
157 if (p)
158 p++;
159 else
160 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000161 p1 = strrchr(base_path, '/');
162#ifdef _WIN32
163 {
164 const char *p2;
165 p2 = strrchr(base_path, '\\');
166 if (!p1 || p2 > p1)
167 p1 = p2;
168 }
169#endif
bellard83f64092006-08-01 16:21:11 +0000170 if (p1)
171 p1++;
172 else
173 p1 = base_path;
174 if (p1 > p)
175 p = p1;
176 len = p - base_path;
177 if (len > dest_size - 1)
178 len = dest_size - 1;
179 memcpy(dest, base_path, len);
180 dest[len] = '\0';
181 pstrcat(dest, dest_size, filename);
182 }
183}
184
Anthony Liguori5efa9d52009-05-09 17:03:42 -0500185void bdrv_register(BlockDriver *bdrv)
bellardea2384d2004-08-01 21:59:26 +0000186{
Kevin Wolf68485422011-06-30 10:05:46 +0200187 if (bdrv->bdrv_co_readv) {
188 /* Emulate AIO by coroutines, and sync by AIO */
189 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
190 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
191 bdrv->bdrv_read = bdrv_read_em;
192 bdrv->bdrv_write = bdrv_write_em;
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200193 } else {
194 bdrv->bdrv_co_readv = bdrv_co_readv_em;
195 bdrv->bdrv_co_writev = bdrv_co_writev_em;
196
197 if (!bdrv->bdrv_aio_readv) {
198 /* add AIO emulation layer */
199 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
200 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
201 } else if (!bdrv->bdrv_read) {
202 /* add synchronous IO emulation layer */
203 bdrv->bdrv_read = bdrv_read_em;
204 bdrv->bdrv_write = bdrv_write_em;
205 }
bellard83f64092006-08-01 16:21:11 +0000206 }
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +0200207
208 if (!bdrv->bdrv_aio_flush)
209 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
210
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100211 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000212}
bellardb3380822004-03-14 21:38:54 +0000213
214/* create a new block device (by default it is empty) */
215BlockDriverState *bdrv_new(const char *device_name)
bellardfc01f7e2003-06-30 10:03:06 +0000216{
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100217 BlockDriverState *bs;
bellardb3380822004-03-14 21:38:54 +0000218
Anthony Liguori7267c092011-08-20 22:09:37 -0500219 bs = g_malloc0(sizeof(BlockDriverState));
bellardb3380822004-03-14 21:38:54 +0000220 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellardea2384d2004-08-01 21:59:26 +0000221 if (device_name[0] != '\0') {
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100222 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellardea2384d2004-08-01 21:59:26 +0000223 }
bellardb3380822004-03-14 21:38:54 +0000224 return bs;
225}
226
bellardea2384d2004-08-01 21:59:26 +0000227BlockDriver *bdrv_find_format(const char *format_name)
228{
229 BlockDriver *drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100230 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
231 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000232 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100233 }
bellardea2384d2004-08-01 21:59:26 +0000234 }
235 return NULL;
236}
237
Markus Armbrustereb852012009-10-27 18:41:44 +0100238static int bdrv_is_whitelisted(BlockDriver *drv)
239{
240 static const char *whitelist[] = {
241 CONFIG_BDRV_WHITELIST
242 };
243 const char **p;
244
245 if (!whitelist[0])
246 return 1; /* no whitelist, anything goes */
247
248 for (p = whitelist; *p; p++) {
249 if (!strcmp(drv->format_name, *p)) {
250 return 1;
251 }
252 }
253 return 0;
254}
255
256BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
257{
258 BlockDriver *drv = bdrv_find_format(format_name);
259 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
260}
261
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200262int bdrv_create(BlockDriver *drv, const char* filename,
263 QEMUOptionParameter *options)
bellardea2384d2004-08-01 21:59:26 +0000264{
265 if (!drv->bdrv_create)
266 return -ENOTSUP;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200267
268 return drv->bdrv_create(filename, options);
bellardea2384d2004-08-01 21:59:26 +0000269}
270
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200271int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
272{
273 BlockDriver *drv;
274
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900275 drv = bdrv_find_protocol(filename);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200276 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000277 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200278 }
279
280 return bdrv_create(drv, filename, options);
281}
282
bellardd5249392004-08-03 21:14:23 +0000283#ifdef _WIN32
bellard95389c82005-12-18 18:28:15 +0000284void get_tmp_filename(char *filename, int size)
bellardd5249392004-08-03 21:14:23 +0000285{
bellard3b9f94e2007-01-07 17:27:07 +0000286 char temp_dir[MAX_PATH];
ths3b46e622007-09-17 08:09:54 +0000287
bellard3b9f94e2007-01-07 17:27:07 +0000288 GetTempPath(MAX_PATH, temp_dir);
289 GetTempFileName(temp_dir, "qem", 0, filename);
bellardd5249392004-08-03 21:14:23 +0000290}
291#else
bellard95389c82005-12-18 18:28:15 +0000292void get_tmp_filename(char *filename, int size)
bellardea2384d2004-08-01 21:59:26 +0000293{
294 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000295 const char *tmpdir;
bellardd5249392004-08-03 21:14:23 +0000296 /* XXX: race condition possible */
aurel320badc1e2008-03-10 00:05:34 +0000297 tmpdir = getenv("TMPDIR");
298 if (!tmpdir)
299 tmpdir = "/tmp";
300 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
bellardea2384d2004-08-01 21:59:26 +0000301 fd = mkstemp(filename);
302 close(fd);
303}
bellardd5249392004-08-03 21:14:23 +0000304#endif
bellardea2384d2004-08-01 21:59:26 +0000305
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200306/*
307 * Detect host devices. By convention, /dev/cdrom[N] is always
308 * recognized as a host CDROM.
309 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200310static BlockDriver *find_hdev_driver(const char *filename)
311{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200312 int score_max = 0, score;
313 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200314
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100315 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200316 if (d->bdrv_probe_device) {
317 score = d->bdrv_probe_device(filename);
318 if (score > score_max) {
319 score_max = score;
320 drv = d;
321 }
322 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200323 }
324
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200325 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200326}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200327
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900328BlockDriver *bdrv_find_protocol(const char *filename)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200329{
330 BlockDriver *drv1;
331 char protocol[128];
332 int len;
333 const char *p;
334
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200335 /* TODO Drivers without bdrv_file_open must be specified explicitly */
336
Christoph Hellwig39508e72010-06-23 12:25:17 +0200337 /*
338 * XXX(hch): we really should not let host device detection
339 * override an explicit protocol specification, but moving this
340 * later breaks access to device names with colons in them.
341 * Thanks to the brain-dead persistent naming schemes on udev-
342 * based Linux systems those actually are quite common.
343 */
344 drv1 = find_hdev_driver(filename);
345 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200346 return drv1;
347 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200348
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000349 if (!path_has_protocol(filename)) {
Christoph Hellwig39508e72010-06-23 12:25:17 +0200350 return bdrv_find_format("file");
351 }
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000352 p = strchr(filename, ':');
353 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200354 len = p - filename;
355 if (len > sizeof(protocol) - 1)
356 len = sizeof(protocol) - 1;
357 memcpy(protocol, filename, len);
358 protocol[len] = '\0';
359 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
360 if (drv1->protocol_name &&
361 !strcmp(drv1->protocol_name, protocol)) {
362 return drv1;
363 }
364 }
365 return NULL;
366}
367
Stefan Weilc98ac352010-07-21 21:51:51 +0200368static int find_image_format(const char *filename, BlockDriver **pdrv)
bellardea2384d2004-08-01 21:59:26 +0000369{
bellard83f64092006-08-01 16:21:11 +0000370 int ret, score, score_max;
bellardea2384d2004-08-01 21:59:26 +0000371 BlockDriver *drv1, *drv;
bellard83f64092006-08-01 16:21:11 +0000372 uint8_t buf[2048];
373 BlockDriverState *bs;
ths3b46e622007-09-17 08:09:54 +0000374
Naphtali Spreif5edb012010-01-17 16:48:13 +0200375 ret = bdrv_file_open(&bs, filename, 0);
Stefan Weilc98ac352010-07-21 21:51:51 +0200376 if (ret < 0) {
377 *pdrv = NULL;
378 return ret;
379 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700380
Kevin Wolf08a00552010-06-01 18:37:31 +0200381 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382 if (bs->sg || !bdrv_is_inserted(bs)) {
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700383 bdrv_delete(bs);
Stefan Weilc98ac352010-07-21 21:51:51 +0200384 drv = bdrv_find_format("raw");
385 if (!drv) {
386 ret = -ENOENT;
387 }
388 *pdrv = drv;
389 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700390 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700391
bellard83f64092006-08-01 16:21:11 +0000392 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
393 bdrv_delete(bs);
394 if (ret < 0) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200395 *pdrv = NULL;
396 return ret;
bellard83f64092006-08-01 16:21:11 +0000397 }
398
bellardea2384d2004-08-01 21:59:26 +0000399 score_max = 0;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200400 drv = NULL;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100401 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard83f64092006-08-01 16:21:11 +0000402 if (drv1->bdrv_probe) {
403 score = drv1->bdrv_probe(buf, ret, filename);
404 if (score > score_max) {
405 score_max = score;
406 drv = drv1;
407 }
bellardea2384d2004-08-01 21:59:26 +0000408 }
409 }
Stefan Weilc98ac352010-07-21 21:51:51 +0200410 if (!drv) {
411 ret = -ENOENT;
412 }
413 *pdrv = drv;
414 return ret;
bellardea2384d2004-08-01 21:59:26 +0000415}
416
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100417/**
418 * Set the current 'total_sectors' value
419 */
420static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
421{
422 BlockDriver *drv = bs->drv;
423
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700424 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
425 if (bs->sg)
426 return 0;
427
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100428 /* query actual device if possible, otherwise just trust the hint */
429 if (drv->bdrv_getlength) {
430 int64_t length = drv->bdrv_getlength(bs);
431 if (length < 0) {
432 return length;
433 }
434 hint = length >> BDRV_SECTOR_BITS;
435 }
436
437 bs->total_sectors = hint;
438 return 0;
439}
440
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100441/**
442 * Set open flags for a given cache mode
443 *
444 * Return 0 on success, -1 if the cache mode was invalid.
445 */
446int bdrv_parse_cache_flags(const char *mode, int *flags)
447{
448 *flags &= ~BDRV_O_CACHE_MASK;
449
450 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
451 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100452 } else if (!strcmp(mode, "directsync")) {
453 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100454 } else if (!strcmp(mode, "writeback")) {
455 *flags |= BDRV_O_CACHE_WB;
456 } else if (!strcmp(mode, "unsafe")) {
457 *flags |= BDRV_O_CACHE_WB;
458 *flags |= BDRV_O_NO_FLUSH;
459 } else if (!strcmp(mode, "writethrough")) {
460 /* this is the default */
461 } else {
462 return -1;
463 }
464
465 return 0;
466}
467
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200468/*
Kevin Wolf57915332010-04-14 15:24:50 +0200469 * Common part for opening disk images and files
470 */
471static int bdrv_open_common(BlockDriverState *bs, const char *filename,
472 int flags, BlockDriver *drv)
473{
474 int ret, open_flags;
475
476 assert(drv != NULL);
477
Stefan Hajnoczi28dcee12011-09-22 20:14:12 +0100478 trace_bdrv_open_common(bs, filename, flags, drv->format_name);
479
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200480 bs->file = NULL;
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100481 bs->total_sectors = 0;
Kevin Wolf57915332010-04-14 15:24:50 +0200482 bs->encrypted = 0;
483 bs->valid_key = 0;
484 bs->open_flags = flags;
Kevin Wolf57915332010-04-14 15:24:50 +0200485 bs->buffer_alignment = 512;
486
487 pstrcpy(bs->filename, sizeof(bs->filename), filename);
488
489 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
490 return -ENOTSUP;
491 }
492
493 bs->drv = drv;
Anthony Liguori7267c092011-08-20 22:09:37 -0500494 bs->opaque = g_malloc0(drv->instance_size);
Kevin Wolf57915332010-04-14 15:24:50 +0200495
Christoph Hellwiga6599792011-05-17 18:04:06 +0200496 if (flags & BDRV_O_CACHE_WB)
Kevin Wolf57915332010-04-14 15:24:50 +0200497 bs->enable_write_cache = 1;
498
499 /*
500 * Clear flags that are internal to the block layer before opening the
501 * image.
502 */
503 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
504
505 /*
Stefan Weilebabb672011-04-26 10:29:36 +0200506 * Snapshots should be writable.
Kevin Wolf57915332010-04-14 15:24:50 +0200507 */
508 if (bs->is_temporary) {
509 open_flags |= BDRV_O_RDWR;
510 }
511
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200512 /* Open the image, either directly or using a protocol */
513 if (drv->bdrv_file_open) {
514 ret = drv->bdrv_file_open(bs, filename, open_flags);
515 } else {
516 ret = bdrv_file_open(&bs->file, filename, open_flags);
517 if (ret >= 0) {
518 ret = drv->bdrv_open(bs, open_flags);
519 }
520 }
521
Kevin Wolf57915332010-04-14 15:24:50 +0200522 if (ret < 0) {
523 goto free_and_fail;
524 }
525
526 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100527
528 ret = refresh_total_sectors(bs, bs->total_sectors);
529 if (ret < 0) {
530 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200531 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100532
Kevin Wolf57915332010-04-14 15:24:50 +0200533#ifndef _WIN32
534 if (bs->is_temporary) {
535 unlink(filename);
536 }
537#endif
538 return 0;
539
540free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200541 if (bs->file) {
542 bdrv_delete(bs->file);
543 bs->file = NULL;
544 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500545 g_free(bs->opaque);
Kevin Wolf57915332010-04-14 15:24:50 +0200546 bs->opaque = NULL;
547 bs->drv = NULL;
548 return ret;
549}
550
551/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200552 * Opens a file using a protocol (file, host_device, nbd, ...)
553 */
bellard83f64092006-08-01 16:21:11 +0000554int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000555{
bellard83f64092006-08-01 16:21:11 +0000556 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200557 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000558 int ret;
559
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900560 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200561 if (!drv) {
562 return -ENOENT;
563 }
564
bellard83f64092006-08-01 16:21:11 +0000565 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200566 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000567 if (ret < 0) {
568 bdrv_delete(bs);
569 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000570 }
aliguori71d07702009-03-03 17:37:16 +0000571 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000572 *pbs = bs;
573 return 0;
bellardea2384d2004-08-01 21:59:26 +0000574}
bellardfc01f7e2003-06-30 10:03:06 +0000575
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200576/*
577 * Opens a disk image (raw, qcow2, vmdk, ...)
578 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200579int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
580 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000581{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200582 int ret;
bellard712e7872005-04-28 21:09:32 +0000583
bellard83f64092006-08-01 16:21:11 +0000584 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000585 BlockDriverState *bs1;
586 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000587 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200588 BlockDriver *bdrv_qcow2;
589 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200590 char tmp_filename[PATH_MAX];
591 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000592
bellardea2384d2004-08-01 21:59:26 +0000593 /* if snapshot, we create a temporary backing file and open it
594 instead of opening 'filename' directly */
595
596 /* if there is a backing file, use it */
597 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200598 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000599 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000600 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000601 return ret;
bellardea2384d2004-08-01 21:59:26 +0000602 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200603 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000604
605 if (bs1->drv && bs1->drv->protocol_name)
606 is_protocol = 1;
607
bellardea2384d2004-08-01 21:59:26 +0000608 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000609
bellardea2384d2004-08-01 21:59:26 +0000610 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
aliguori7c96d462008-09-12 17:54:13 +0000611
612 /* Real path is meaningless for protocols */
613 if (is_protocol)
614 snprintf(backing_filename, sizeof(backing_filename),
615 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000616 else if (!realpath(filename, backing_filename))
617 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000618
Kevin Wolf91a073a2009-05-27 14:48:06 +0200619 bdrv_qcow2 = bdrv_find_format("qcow2");
620 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
621
Jes Sorensen3e829902010-05-27 16:20:30 +0200622 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200623 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
624 if (drv) {
625 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
626 drv->format_name);
627 }
628
629 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200630 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000631 if (ret < 0) {
632 return ret;
bellardea2384d2004-08-01 21:59:26 +0000633 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200634
bellardea2384d2004-08-01 21:59:26 +0000635 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200636 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000637 bs->is_temporary = 1;
638 }
bellard712e7872005-04-28 21:09:32 +0000639
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200640 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200641 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200642 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000643 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100644
aliguori51d7c002009-03-05 23:00:29 +0000645 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000646 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000647 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200648
649 /* Open the image */
650 ret = bdrv_open_common(bs, filename, flags, drv);
651 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100652 goto unlink_and_fail;
653 }
654
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200655 /* If there is a backing file, use it */
656 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
657 char backing_filename[PATH_MAX];
658 int back_flags;
659 BlockDriver *back_drv = NULL;
660
661 bs->backing_hd = bdrv_new("");
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000662
663 if (path_has_protocol(bs->backing_file)) {
664 pstrcpy(backing_filename, sizeof(backing_filename),
665 bs->backing_file);
666 } else {
667 path_combine(backing_filename, sizeof(backing_filename),
668 filename, bs->backing_file);
669 }
670
671 if (bs->backing_format[0] != '\0') {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200672 back_drv = bdrv_find_format(bs->backing_format);
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000673 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200674
675 /* backing files always opened read-only */
676 back_flags =
677 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
678
679 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
680 if (ret < 0) {
681 bdrv_close(bs);
682 return ret;
683 }
684 if (bs->is_temporary) {
685 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
686 } else {
687 /* base image inherits from "parent" */
688 bs->backing_hd->keep_read_only = bs->keep_read_only;
689 }
690 }
691
692 if (!bdrv_key_required(bs)) {
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200693 bdrv_dev_change_media_cb(bs, true);
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
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200729 bdrv_dev_change_media_cb(bs, false);
bellardb3380822004-03-14 21:38:54 +0000730 }
731}
732
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +0900733void bdrv_close_all(void)
734{
735 BlockDriverState *bs;
736
737 QTAILQ_FOREACH(bs, &bdrv_states, list) {
738 bdrv_close(bs);
739 }
740}
741
Ryan Harperd22b2f42011-03-29 20:51:47 -0500742/* make a BlockDriverState anonymous by removing from bdrv_state list.
743 Also, NULL terminate the device_name to prevent double remove */
744void bdrv_make_anon(BlockDriverState *bs)
745{
746 if (bs->device_name[0] != '\0') {
747 QTAILQ_REMOVE(&bdrv_states, bs, list);
748 }
749 bs->device_name[0] = '\0';
750}
751
bellardb3380822004-03-14 21:38:54 +0000752void bdrv_delete(BlockDriverState *bs)
753{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200754 assert(!bs->dev);
Markus Armbruster18846de2010-06-29 16:58:30 +0200755
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100756 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -0500757 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +0000758
bellardb3380822004-03-14 21:38:54 +0000759 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200760 if (bs->file != NULL) {
761 bdrv_delete(bs->file);
762 }
763
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200764 assert(bs != bs_snapshots);
Anthony Liguori7267c092011-08-20 22:09:37 -0500765 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +0000766}
767
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200768int bdrv_attach_dev(BlockDriverState *bs, void *dev)
769/* TODO change to DeviceState *dev when all users are qdevified */
Markus Armbruster18846de2010-06-29 16:58:30 +0200770{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200771 if (bs->dev) {
Markus Armbruster18846de2010-06-29 16:58:30 +0200772 return -EBUSY;
773 }
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200774 bs->dev = dev;
Markus Armbruster18846de2010-06-29 16:58:30 +0200775 return 0;
776}
777
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200778/* TODO qdevified devices don't use this, remove when devices are qdevified */
779void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
Markus Armbruster18846de2010-06-29 16:58:30 +0200780{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200781 if (bdrv_attach_dev(bs, dev) < 0) {
782 abort();
783 }
784}
785
786void bdrv_detach_dev(BlockDriverState *bs, void *dev)
787/* TODO change to DeviceState *dev when all users are qdevified */
788{
789 assert(bs->dev == dev);
790 bs->dev = NULL;
Markus Armbruster0e49de52011-08-03 15:07:41 +0200791 bs->dev_ops = NULL;
792 bs->dev_opaque = NULL;
Markus Armbruster29e05f22011-09-06 18:58:57 +0200793 bs->buffer_alignment = 512;
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;
Markus Armbruster2c6942f2011-09-06 18:58:51 +0200807 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
808 bs_snapshots = NULL;
809 }
Markus Armbruster0e49de52011-08-03 15:07:41 +0200810}
811
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200812static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
Markus Armbruster0e49de52011-08-03 15:07:41 +0200813{
Markus Armbruster145feb12011-08-03 15:07:42 +0200814 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200815 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
Markus Armbruster145feb12011-08-03 15:07:42 +0200816 }
817}
818
Markus Armbruster2c6942f2011-09-06 18:58:51 +0200819bool bdrv_dev_has_removable_media(BlockDriverState *bs)
820{
821 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
822}
823
Markus Armbrustere4def802011-09-06 18:58:53 +0200824bool bdrv_dev_is_tray_open(BlockDriverState *bs)
825{
826 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
827 return bs->dev_ops->is_tray_open(bs->dev_opaque);
828 }
829 return false;
830}
831
Markus Armbruster145feb12011-08-03 15:07:42 +0200832static void bdrv_dev_resize_cb(BlockDriverState *bs)
833{
834 if (bs->dev_ops && bs->dev_ops->resize_cb) {
835 bs->dev_ops->resize_cb(bs->dev_opaque);
Markus Armbruster0e49de52011-08-03 15:07:41 +0200836 }
837}
838
Markus Armbrusterf1076392011-09-06 18:58:46 +0200839bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
840{
841 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
842 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
843 }
844 return false;
845}
846
aliguorie97fc192009-04-21 23:11:50 +0000847/*
848 * Run consistency checks on an image
849 *
Kevin Wolfe076f332010-06-29 11:43:13 +0200850 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +0200851 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +0200852 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +0000853 */
Kevin Wolfe076f332010-06-29 11:43:13 +0200854int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
aliguorie97fc192009-04-21 23:11:50 +0000855{
856 if (bs->drv->bdrv_check == NULL) {
857 return -ENOTSUP;
858 }
859
Kevin Wolfe076f332010-06-29 11:43:13 +0200860 memset(res, 0, sizeof(*res));
Kevin Wolf9ac228e2010-06-29 12:37:54 +0200861 return bs->drv->bdrv_check(bs, res);
aliguorie97fc192009-04-21 23:11:50 +0000862}
863
Kevin Wolf8a426612010-07-16 17:17:01 +0200864#define COMMIT_BUF_SECTORS 2048
865
bellard33e39632003-07-06 17:15:21 +0000866/* commit COW file into the raw image */
867int bdrv_commit(BlockDriverState *bs)
868{
bellard19cb3732006-08-19 11:45:59 +0000869 BlockDriver *drv = bs->drv;
Kevin Wolfee181192010-08-05 13:05:22 +0200870 BlockDriver *backing_drv;
Kevin Wolf8a426612010-07-16 17:17:01 +0200871 int64_t sector, total_sectors;
872 int n, ro, open_flags;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200873 int ret = 0, rw_ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +0200874 uint8_t *buf;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200875 char filename[1024];
876 BlockDriverState *bs_rw, *bs_ro;
bellard33e39632003-07-06 17:15:21 +0000877
bellard19cb3732006-08-19 11:45:59 +0000878 if (!drv)
879 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200880
881 if (!bs->backing_hd) {
882 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +0000883 }
884
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200885 if (bs->backing_hd->keep_read_only) {
886 return -EACCES;
887 }
Kevin Wolfee181192010-08-05 13:05:22 +0200888
889 backing_drv = bs->backing_hd->drv;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200890 ro = bs->backing_hd->read_only;
891 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
892 open_flags = bs->backing_hd->open_flags;
893
894 if (ro) {
895 /* re-open as RW */
896 bdrv_delete(bs->backing_hd);
897 bs->backing_hd = NULL;
898 bs_rw = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200899 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
900 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200901 if (rw_ret < 0) {
902 bdrv_delete(bs_rw);
903 /* try to re-open read-only */
904 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200905 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
906 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200907 if (ret < 0) {
908 bdrv_delete(bs_ro);
909 /* drive not functional anymore */
910 bs->drv = NULL;
911 return ret;
912 }
913 bs->backing_hd = bs_ro;
914 return rw_ret;
915 }
916 bs->backing_hd = bs_rw;
bellard33e39632003-07-06 17:15:21 +0000917 }
bellardea2384d2004-08-01 21:59:26 +0000918
Jan Kiszka6ea44302009-11-30 18:21:19 +0100919 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Anthony Liguori7267c092011-08-20 22:09:37 -0500920 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +0000921
Kevin Wolf8a426612010-07-16 17:17:01 +0200922 for (sector = 0; sector < total_sectors; sector += n) {
923 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
924
925 if (bdrv_read(bs, sector, buf, n) != 0) {
926 ret = -EIO;
927 goto ro_cleanup;
928 }
929
930 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
931 ret = -EIO;
932 goto ro_cleanup;
933 }
bellardea2384d2004-08-01 21:59:26 +0000934 }
935 }
bellard95389c82005-12-18 18:28:15 +0000936
Christoph Hellwig1d449522010-01-17 12:32:30 +0100937 if (drv->bdrv_make_empty) {
938 ret = drv->bdrv_make_empty(bs);
939 bdrv_flush(bs);
940 }
bellard95389c82005-12-18 18:28:15 +0000941
Christoph Hellwig3f5075a2010-01-12 13:49:23 +0100942 /*
943 * Make sure all data we wrote to the backing device is actually
944 * stable on disk.
945 */
946 if (bs->backing_hd)
947 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200948
949ro_cleanup:
Anthony Liguori7267c092011-08-20 22:09:37 -0500950 g_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200951
952 if (ro) {
953 /* re-open as RO */
954 bdrv_delete(bs->backing_hd);
955 bs->backing_hd = NULL;
956 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200957 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
958 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200959 if (ret < 0) {
960 bdrv_delete(bs_ro);
961 /* drive not functional anymore */
962 bs->drv = NULL;
963 return ret;
964 }
965 bs->backing_hd = bs_ro;
966 bs->backing_hd->keep_read_only = 0;
967 }
968
Christoph Hellwig1d449522010-01-17 12:32:30 +0100969 return ret;
bellard33e39632003-07-06 17:15:21 +0000970}
971
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +0200972void bdrv_commit_all(void)
973{
974 BlockDriverState *bs;
975
976 QTAILQ_FOREACH(bs, &bdrv_states, list) {
977 bdrv_commit(bs);
978 }
979}
980
Kevin Wolf756e6732010-01-12 12:55:17 +0100981/*
982 * Return values:
983 * 0 - success
984 * -EINVAL - backing format specified, but no file
985 * -ENOSPC - can't update the backing file because no space is left in the
986 * image file header
987 * -ENOTSUP - format driver doesn't support changing the backing file
988 */
989int bdrv_change_backing_file(BlockDriverState *bs,
990 const char *backing_file, const char *backing_fmt)
991{
992 BlockDriver *drv = bs->drv;
993
994 if (drv->bdrv_change_backing_file != NULL) {
995 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
996 } else {
997 return -ENOTSUP;
998 }
999}
1000
aliguori71d07702009-03-03 17:37:16 +00001001static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1002 size_t size)
1003{
1004 int64_t len;
1005
1006 if (!bdrv_is_inserted(bs))
1007 return -ENOMEDIUM;
1008
1009 if (bs->growable)
1010 return 0;
1011
1012 len = bdrv_getlength(bs);
1013
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02001014 if (offset < 0)
1015 return -EIO;
1016
1017 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +00001018 return -EIO;
1019
1020 return 0;
1021}
1022
1023static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1024 int nb_sectors)
1025{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001026 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1027 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +00001028}
1029
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001030static inline bool bdrv_has_async_rw(BlockDriver *drv)
1031{
1032 return drv->bdrv_co_readv != bdrv_co_readv_em
1033 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1034}
1035
1036static inline bool bdrv_has_async_flush(BlockDriver *drv)
1037{
1038 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1039}
1040
bellard19cb3732006-08-19 11:45:59 +00001041/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +00001042int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001043 uint8_t *buf, int nb_sectors)
1044{
bellardea2384d2004-08-01 21:59:26 +00001045 BlockDriver *drv = bs->drv;
1046
bellard19cb3732006-08-19 11:45:59 +00001047 if (!drv)
1048 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001049
1050 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1051 QEMUIOVector qiov;
1052 struct iovec iov = {
1053 .iov_base = (void *)buf,
1054 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1055 };
1056
1057 qemu_iovec_init_external(&qiov, &iov, 1);
1058 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1059 }
1060
aliguori71d07702009-03-03 17:37:16 +00001061 if (bdrv_check_request(bs, sector_num, nb_sectors))
1062 return -EIO;
bellardb3380822004-03-14 21:38:54 +00001063
aliguorieda578e2009-03-12 19:57:16 +00001064 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
bellardfc01f7e2003-06-30 10:03:06 +00001065}
1066
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001067static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001068 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001069{
1070 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001071 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001072
Jan Kiszka6ea44302009-11-30 18:21:19 +01001073 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001074 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001075
1076 for (; start <= end; start++) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01001077 idx = start / (sizeof(unsigned long) * 8);
1078 bit = start % (sizeof(unsigned long) * 8);
1079 val = bs->dirty_bitmap[idx];
1080 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001081 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001082 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001083 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +02001084 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001085 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001086 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001087 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001088 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +02001089 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001090 }
1091 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001092 }
1093}
1094
ths5fafdf22007-09-16 21:08:06 +00001095/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +00001096 -EIO generic I/O error (may happen for all errors)
1097 -ENOMEDIUM No media inserted.
1098 -EINVAL Invalid sector number or nb_sectors
1099 -EACCES Trying to write a read-only device
1100*/
ths5fafdf22007-09-16 21:08:06 +00001101int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001102 const uint8_t *buf, int nb_sectors)
1103{
bellard83f64092006-08-01 16:21:11 +00001104 BlockDriver *drv = bs->drv;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001105
bellard19cb3732006-08-19 11:45:59 +00001106 if (!bs->drv)
1107 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001108
1109 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1110 QEMUIOVector qiov;
1111 struct iovec iov = {
1112 .iov_base = (void *)buf,
1113 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1114 };
1115
1116 qemu_iovec_init_external(&qiov, &iov, 1);
1117 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1118 }
1119
bellard0849bf02003-06-30 23:17:31 +00001120 if (bs->read_only)
bellard19cb3732006-08-19 11:45:59 +00001121 return -EACCES;
aliguori71d07702009-03-03 17:37:16 +00001122 if (bdrv_check_request(bs, sector_num, nb_sectors))
1123 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001124
Jan Kiszkac6d22832009-11-30 18:21:20 +01001125 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001126 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1127 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001128
Kevin Wolf294cc352010-04-28 14:34:01 +02001129 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1130 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1131 }
1132
aliguori42fb2802009-01-15 20:43:39 +00001133 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
bellard83f64092006-08-01 16:21:11 +00001134}
1135
aliguorieda578e2009-03-12 19:57:16 +00001136int bdrv_pread(BlockDriverState *bs, int64_t offset,
1137 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001138{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001139 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001140 int len, nb_sectors, count;
1141 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001142 int ret;
bellard83f64092006-08-01 16:21:11 +00001143
1144 count = count1;
1145 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001146 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001147 if (len > count)
1148 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001149 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001150 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001151 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1152 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001153 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00001154 count -= len;
1155 if (count == 0)
1156 return count1;
1157 sector_num++;
1158 buf += len;
1159 }
1160
1161 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001162 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001163 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001164 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1165 return ret;
bellard83f64092006-08-01 16:21:11 +00001166 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001167 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001168 buf += len;
1169 count -= len;
1170 }
1171
1172 /* add data from the last sector */
1173 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001174 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1175 return ret;
bellard83f64092006-08-01 16:21:11 +00001176 memcpy(buf, tmp_buf, count);
1177 }
1178 return count1;
1179}
1180
aliguorieda578e2009-03-12 19:57:16 +00001181int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1182 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001183{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001184 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001185 int len, nb_sectors, count;
1186 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001187 int ret;
bellard83f64092006-08-01 16:21:11 +00001188
1189 count = count1;
1190 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001191 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001192 if (len > count)
1193 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001194 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001195 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001196 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1197 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001198 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001199 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1200 return ret;
bellard83f64092006-08-01 16:21:11 +00001201 count -= len;
1202 if (count == 0)
1203 return count1;
1204 sector_num++;
1205 buf += len;
1206 }
1207
1208 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001209 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001210 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001211 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1212 return ret;
bellard83f64092006-08-01 16:21:11 +00001213 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001214 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001215 buf += len;
1216 count -= len;
1217 }
1218
1219 /* add data from the last sector */
1220 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001221 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1222 return ret;
bellard83f64092006-08-01 16:21:11 +00001223 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001224 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1225 return ret;
bellard83f64092006-08-01 16:21:11 +00001226 }
1227 return count1;
1228}
bellard83f64092006-08-01 16:21:11 +00001229
Kevin Wolff08145f2010-06-16 16:38:15 +02001230/*
1231 * Writes to the file and ensures that no writes are reordered across this
1232 * request (acts as a barrier)
1233 *
1234 * Returns 0 on success, -errno in error cases.
1235 */
1236int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1237 const void *buf, int count)
1238{
1239 int ret;
1240
1241 ret = bdrv_pwrite(bs, offset, buf, count);
1242 if (ret < 0) {
1243 return ret;
1244 }
1245
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001246 /* No flush needed for cache modes that use O_DSYNC */
1247 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
Kevin Wolff08145f2010-06-16 16:38:15 +02001248 bdrv_flush(bs);
1249 }
1250
1251 return 0;
1252}
1253
Kevin Wolfda1fa912011-07-14 17:27:13 +02001254int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1255 int nb_sectors, QEMUIOVector *qiov)
1256{
1257 BlockDriver *drv = bs->drv;
1258
1259 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1260
1261 if (!drv) {
1262 return -ENOMEDIUM;
1263 }
1264 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1265 return -EIO;
1266 }
1267
1268 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1269}
1270
1271int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1272 int nb_sectors, QEMUIOVector *qiov)
1273{
1274 BlockDriver *drv = bs->drv;
1275
1276 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1277
1278 if (!bs->drv) {
1279 return -ENOMEDIUM;
1280 }
1281 if (bs->read_only) {
1282 return -EACCES;
1283 }
1284 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1285 return -EIO;
1286 }
1287
1288 if (bs->dirty_bitmap) {
1289 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1290 }
1291
1292 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1293 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1294 }
1295
1296 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1297}
1298
bellard83f64092006-08-01 16:21:11 +00001299/**
bellard83f64092006-08-01 16:21:11 +00001300 * Truncate file to 'offset' bytes (needed only for file protocols)
1301 */
1302int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1303{
1304 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001305 int ret;
bellard83f64092006-08-01 16:21:11 +00001306 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001307 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00001308 if (!drv->bdrv_truncate)
1309 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02001310 if (bs->read_only)
1311 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02001312 if (bdrv_in_use(bs))
1313 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001314 ret = drv->bdrv_truncate(bs, offset);
1315 if (ret == 0) {
1316 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Markus Armbruster145feb12011-08-03 15:07:42 +02001317 bdrv_dev_resize_cb(bs);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001318 }
1319 return ret;
bellard83f64092006-08-01 16:21:11 +00001320}
1321
1322/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08001323 * Length of a allocated file in bytes. Sparse files are counted by actual
1324 * allocated space. Return < 0 if error or unknown.
1325 */
1326int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1327{
1328 BlockDriver *drv = bs->drv;
1329 if (!drv) {
1330 return -ENOMEDIUM;
1331 }
1332 if (drv->bdrv_get_allocated_file_size) {
1333 return drv->bdrv_get_allocated_file_size(bs);
1334 }
1335 if (bs->file) {
1336 return bdrv_get_allocated_file_size(bs->file);
1337 }
1338 return -ENOTSUP;
1339}
1340
1341/**
bellard83f64092006-08-01 16:21:11 +00001342 * Length of a file in bytes. Return < 0 if error or unknown.
1343 */
1344int64_t bdrv_getlength(BlockDriverState *bs)
1345{
1346 BlockDriver *drv = bs->drv;
1347 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001348 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001349
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001350 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001351 if (drv->bdrv_getlength) {
1352 return drv->bdrv_getlength(bs);
1353 }
bellard83f64092006-08-01 16:21:11 +00001354 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001355 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00001356}
1357
bellard19cb3732006-08-19 11:45:59 +00001358/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00001359void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00001360{
bellard19cb3732006-08-19 11:45:59 +00001361 int64_t length;
1362 length = bdrv_getlength(bs);
1363 if (length < 0)
1364 length = 0;
1365 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01001366 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00001367 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00001368}
bellardcf989512004-02-16 21:56:36 +00001369
aliguorif3d54fc2008-11-25 21:50:24 +00001370struct partition {
1371 uint8_t boot_ind; /* 0x80 - active */
1372 uint8_t head; /* starting head */
1373 uint8_t sector; /* starting sector */
1374 uint8_t cyl; /* starting cylinder */
1375 uint8_t sys_ind; /* What partition type */
1376 uint8_t end_head; /* end head */
1377 uint8_t end_sector; /* end sector */
1378 uint8_t end_cyl; /* end cylinder */
1379 uint32_t start_sect; /* starting sector counting from 0 */
1380 uint32_t nr_sects; /* nr of sectors in partition */
Stefan Weil541dc0d2011-08-31 12:38:01 +02001381} QEMU_PACKED;
aliguorif3d54fc2008-11-25 21:50:24 +00001382
1383/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1384static int guess_disk_lchs(BlockDriverState *bs,
1385 int *pcylinders, int *pheads, int *psectors)
1386{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001387 uint8_t buf[BDRV_SECTOR_SIZE];
aliguorif3d54fc2008-11-25 21:50:24 +00001388 int ret, i, heads, sectors, cylinders;
1389 struct partition *p;
1390 uint32_t nr_sects;
blueswir1a38131b2008-12-05 17:56:40 +00001391 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001392
1393 bdrv_get_geometry(bs, &nb_sectors);
1394
1395 ret = bdrv_read(bs, 0, buf, 1);
1396 if (ret < 0)
1397 return -1;
1398 /* test msdos magic */
1399 if (buf[510] != 0x55 || buf[511] != 0xaa)
1400 return -1;
1401 for(i = 0; i < 4; i++) {
1402 p = ((struct partition *)(buf + 0x1be)) + i;
1403 nr_sects = le32_to_cpu(p->nr_sects);
1404 if (nr_sects && p->end_head) {
1405 /* We make the assumption that the partition terminates on
1406 a cylinder boundary */
1407 heads = p->end_head + 1;
1408 sectors = p->end_sector & 63;
1409 if (sectors == 0)
1410 continue;
1411 cylinders = nb_sectors / (heads * sectors);
1412 if (cylinders < 1 || cylinders > 16383)
1413 continue;
1414 *pheads = heads;
1415 *psectors = sectors;
1416 *pcylinders = cylinders;
1417#if 0
1418 printf("guessed geometry: LCHS=%d %d %d\n",
1419 cylinders, heads, sectors);
1420#endif
1421 return 0;
1422 }
1423 }
1424 return -1;
1425}
1426
1427void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1428{
1429 int translation, lba_detected = 0;
1430 int cylinders, heads, secs;
blueswir1a38131b2008-12-05 17:56:40 +00001431 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001432
1433 /* if a geometry hint is available, use it */
1434 bdrv_get_geometry(bs, &nb_sectors);
1435 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1436 translation = bdrv_get_translation_hint(bs);
1437 if (cylinders != 0) {
1438 *pcyls = cylinders;
1439 *pheads = heads;
1440 *psecs = secs;
1441 } else {
1442 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1443 if (heads > 16) {
1444 /* if heads > 16, it means that a BIOS LBA
1445 translation was active, so the default
1446 hardware geometry is OK */
1447 lba_detected = 1;
1448 goto default_geometry;
1449 } else {
1450 *pcyls = cylinders;
1451 *pheads = heads;
1452 *psecs = secs;
1453 /* disable any translation to be in sync with
1454 the logical geometry */
1455 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1456 bdrv_set_translation_hint(bs,
1457 BIOS_ATA_TRANSLATION_NONE);
1458 }
1459 }
1460 } else {
1461 default_geometry:
1462 /* if no geometry, use a standard physical disk geometry */
1463 cylinders = nb_sectors / (16 * 63);
1464
1465 if (cylinders > 16383)
1466 cylinders = 16383;
1467 else if (cylinders < 2)
1468 cylinders = 2;
1469 *pcyls = cylinders;
1470 *pheads = 16;
1471 *psecs = 63;
1472 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1473 if ((*pcyls * *pheads) <= 131072) {
1474 bdrv_set_translation_hint(bs,
1475 BIOS_ATA_TRANSLATION_LARGE);
1476 } else {
1477 bdrv_set_translation_hint(bs,
1478 BIOS_ATA_TRANSLATION_LBA);
1479 }
1480 }
1481 }
1482 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1483 }
1484}
1485
ths5fafdf22007-09-16 21:08:06 +00001486void bdrv_set_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001487 int cyls, int heads, int secs)
1488{
1489 bs->cyls = cyls;
1490 bs->heads = heads;
1491 bs->secs = secs;
1492}
1493
bellard46d47672004-11-16 01:45:27 +00001494void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1495{
1496 bs->translation = translation;
1497}
1498
ths5fafdf22007-09-16 21:08:06 +00001499void bdrv_get_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001500 int *pcyls, int *pheads, int *psecs)
1501{
1502 *pcyls = bs->cyls;
1503 *pheads = bs->heads;
1504 *psecs = bs->secs;
1505}
1506
Blue Swirl5bbdbb42011-02-12 20:43:32 +00001507/* Recognize floppy formats */
1508typedef struct FDFormat {
1509 FDriveType drive;
1510 uint8_t last_sect;
1511 uint8_t max_track;
1512 uint8_t max_head;
1513} FDFormat;
1514
1515static const FDFormat fd_formats[] = {
1516 /* First entry is default format */
1517 /* 1.44 MB 3"1/2 floppy disks */
1518 { FDRIVE_DRV_144, 18, 80, 1, },
1519 { FDRIVE_DRV_144, 20, 80, 1, },
1520 { FDRIVE_DRV_144, 21, 80, 1, },
1521 { FDRIVE_DRV_144, 21, 82, 1, },
1522 { FDRIVE_DRV_144, 21, 83, 1, },
1523 { FDRIVE_DRV_144, 22, 80, 1, },
1524 { FDRIVE_DRV_144, 23, 80, 1, },
1525 { FDRIVE_DRV_144, 24, 80, 1, },
1526 /* 2.88 MB 3"1/2 floppy disks */
1527 { FDRIVE_DRV_288, 36, 80, 1, },
1528 { FDRIVE_DRV_288, 39, 80, 1, },
1529 { FDRIVE_DRV_288, 40, 80, 1, },
1530 { FDRIVE_DRV_288, 44, 80, 1, },
1531 { FDRIVE_DRV_288, 48, 80, 1, },
1532 /* 720 kB 3"1/2 floppy disks */
1533 { FDRIVE_DRV_144, 9, 80, 1, },
1534 { FDRIVE_DRV_144, 10, 80, 1, },
1535 { FDRIVE_DRV_144, 10, 82, 1, },
1536 { FDRIVE_DRV_144, 10, 83, 1, },
1537 { FDRIVE_DRV_144, 13, 80, 1, },
1538 { FDRIVE_DRV_144, 14, 80, 1, },
1539 /* 1.2 MB 5"1/4 floppy disks */
1540 { FDRIVE_DRV_120, 15, 80, 1, },
1541 { FDRIVE_DRV_120, 18, 80, 1, },
1542 { FDRIVE_DRV_120, 18, 82, 1, },
1543 { FDRIVE_DRV_120, 18, 83, 1, },
1544 { FDRIVE_DRV_120, 20, 80, 1, },
1545 /* 720 kB 5"1/4 floppy disks */
1546 { FDRIVE_DRV_120, 9, 80, 1, },
1547 { FDRIVE_DRV_120, 11, 80, 1, },
1548 /* 360 kB 5"1/4 floppy disks */
1549 { FDRIVE_DRV_120, 9, 40, 1, },
1550 { FDRIVE_DRV_120, 9, 40, 0, },
1551 { FDRIVE_DRV_120, 10, 41, 1, },
1552 { FDRIVE_DRV_120, 10, 42, 1, },
1553 /* 320 kB 5"1/4 floppy disks */
1554 { FDRIVE_DRV_120, 8, 40, 1, },
1555 { FDRIVE_DRV_120, 8, 40, 0, },
1556 /* 360 kB must match 5"1/4 better than 3"1/2... */
1557 { FDRIVE_DRV_144, 9, 80, 0, },
1558 /* end */
1559 { FDRIVE_DRV_NONE, -1, -1, 0, },
1560};
1561
1562void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1563 int *max_track, int *last_sect,
1564 FDriveType drive_in, FDriveType *drive)
1565{
1566 const FDFormat *parse;
1567 uint64_t nb_sectors, size;
1568 int i, first_match, match;
1569
1570 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1571 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1572 /* User defined disk */
1573 } else {
1574 bdrv_get_geometry(bs, &nb_sectors);
1575 match = -1;
1576 first_match = -1;
1577 for (i = 0; ; i++) {
1578 parse = &fd_formats[i];
1579 if (parse->drive == FDRIVE_DRV_NONE) {
1580 break;
1581 }
1582 if (drive_in == parse->drive ||
1583 drive_in == FDRIVE_DRV_NONE) {
1584 size = (parse->max_head + 1) * parse->max_track *
1585 parse->last_sect;
1586 if (nb_sectors == size) {
1587 match = i;
1588 break;
1589 }
1590 if (first_match == -1) {
1591 first_match = i;
1592 }
1593 }
1594 }
1595 if (match == -1) {
1596 if (first_match == -1) {
1597 match = 1;
1598 } else {
1599 match = first_match;
1600 }
1601 parse = &fd_formats[match];
1602 }
1603 *nb_heads = parse->max_head + 1;
1604 *max_track = parse->max_track;
1605 *last_sect = parse->last_sect;
1606 *drive = parse->drive;
1607 }
1608}
1609
bellard46d47672004-11-16 01:45:27 +00001610int bdrv_get_translation_hint(BlockDriverState *bs)
1611{
1612 return bs->translation;
1613}
1614
Markus Armbrusterabd7f682010-06-02 18:55:17 +02001615void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1616 BlockErrorAction on_write_error)
1617{
1618 bs->on_read_error = on_read_error;
1619 bs->on_write_error = on_write_error;
1620}
1621
1622BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1623{
1624 return is_read ? bs->on_read_error : bs->on_write_error;
1625}
1626
bellardb3380822004-03-14 21:38:54 +00001627int bdrv_is_read_only(BlockDriverState *bs)
1628{
1629 return bs->read_only;
1630}
1631
ths985a03b2007-12-24 16:10:43 +00001632int bdrv_is_sg(BlockDriverState *bs)
1633{
1634 return bs->sg;
1635}
1636
Christoph Hellwige900a7b2009-09-04 19:01:15 +02001637int bdrv_enable_write_cache(BlockDriverState *bs)
1638{
1639 return bs->enable_write_cache;
1640}
1641
bellardea2384d2004-08-01 21:59:26 +00001642int bdrv_is_encrypted(BlockDriverState *bs)
1643{
1644 if (bs->backing_hd && bs->backing_hd->encrypted)
1645 return 1;
1646 return bs->encrypted;
1647}
1648
aliguoric0f4ce72009-03-05 23:01:01 +00001649int bdrv_key_required(BlockDriverState *bs)
1650{
1651 BlockDriverState *backing_hd = bs->backing_hd;
1652
1653 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1654 return 1;
1655 return (bs->encrypted && !bs->valid_key);
1656}
1657
bellardea2384d2004-08-01 21:59:26 +00001658int bdrv_set_key(BlockDriverState *bs, const char *key)
1659{
1660 int ret;
1661 if (bs->backing_hd && bs->backing_hd->encrypted) {
1662 ret = bdrv_set_key(bs->backing_hd, key);
1663 if (ret < 0)
1664 return ret;
1665 if (!bs->encrypted)
1666 return 0;
1667 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02001668 if (!bs->encrypted) {
1669 return -EINVAL;
1670 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1671 return -ENOMEDIUM;
1672 }
aliguoric0f4ce72009-03-05 23:01:01 +00001673 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00001674 if (ret < 0) {
1675 bs->valid_key = 0;
1676 } else if (!bs->valid_key) {
1677 bs->valid_key = 1;
1678 /* call the change callback now, we skipped it on open */
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +02001679 bdrv_dev_change_media_cb(bs, true);
aliguoribb5fc202009-03-05 23:01:15 +00001680 }
aliguoric0f4ce72009-03-05 23:01:01 +00001681 return ret;
bellardea2384d2004-08-01 21:59:26 +00001682}
1683
1684void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1685{
bellard19cb3732006-08-19 11:45:59 +00001686 if (!bs->drv) {
bellardea2384d2004-08-01 21:59:26 +00001687 buf[0] = '\0';
1688 } else {
1689 pstrcpy(buf, buf_size, bs->drv->format_name);
1690 }
1691}
1692
ths5fafdf22007-09-16 21:08:06 +00001693void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00001694 void *opaque)
1695{
1696 BlockDriver *drv;
1697
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01001698 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00001699 it(opaque, drv->format_name);
1700 }
1701}
1702
bellardb3380822004-03-14 21:38:54 +00001703BlockDriverState *bdrv_find(const char *name)
1704{
1705 BlockDriverState *bs;
1706
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001707 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1708 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00001709 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001710 }
bellardb3380822004-03-14 21:38:54 +00001711 }
1712 return NULL;
1713}
1714
Markus Armbruster2f399b02010-06-02 18:55:20 +02001715BlockDriverState *bdrv_next(BlockDriverState *bs)
1716{
1717 if (!bs) {
1718 return QTAILQ_FIRST(&bdrv_states);
1719 }
1720 return QTAILQ_NEXT(bs, list);
1721}
1722
aliguori51de9762009-03-05 23:00:43 +00001723void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00001724{
1725 BlockDriverState *bs;
1726
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001727 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00001728 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00001729 }
1730}
1731
bellardea2384d2004-08-01 21:59:26 +00001732const char *bdrv_get_device_name(BlockDriverState *bs)
1733{
1734 return bs->device_name;
1735}
1736
Kevin Wolf205ef792010-10-21 16:43:43 +02001737int bdrv_flush(BlockDriverState *bs)
pbrook7a6cba62006-06-04 11:39:07 +00001738{
Alexander Graf016f5cf2010-05-26 17:51:49 +02001739 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolf205ef792010-10-21 16:43:43 +02001740 return 0;
Alexander Graf016f5cf2010-05-26 17:51:49 +02001741 }
1742
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001743 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1744 return bdrv_co_flush_em(bs);
1745 }
1746
Kevin Wolf205ef792010-10-21 16:43:43 +02001747 if (bs->drv && bs->drv->bdrv_flush) {
1748 return bs->drv->bdrv_flush(bs);
1749 }
1750
1751 /*
1752 * Some block drivers always operate in either writethrough or unsafe mode
1753 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1754 * the server works (because the behaviour is hardcoded or depends on
1755 * server-side configuration), so we can't ensure that everything is safe
1756 * on disk. Returning an error doesn't work because that would break guests
1757 * even if the server operates in writethrough mode.
1758 *
1759 * Let's hope the user knows what he's doing.
1760 */
1761 return 0;
pbrook7a6cba62006-06-04 11:39:07 +00001762}
1763
aliguoric6ca28d2008-10-06 13:55:43 +00001764void bdrv_flush_all(void)
1765{
1766 BlockDriverState *bs;
1767
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001768 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Markus Armbrusterc602a482011-08-03 15:08:10 +02001769 if (!bdrv_is_read_only(bs) && bdrv_is_inserted(bs)) {
aliguoric6ca28d2008-10-06 13:55:43 +00001770 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001771 }
1772 }
aliguoric6ca28d2008-10-06 13:55:43 +00001773}
1774
Kevin Wolff2feebb2010-04-14 17:30:35 +02001775int bdrv_has_zero_init(BlockDriverState *bs)
1776{
1777 assert(bs->drv);
1778
Kevin Wolf336c1c12010-07-28 11:26:29 +02001779 if (bs->drv->bdrv_has_zero_init) {
1780 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02001781 }
1782
1783 return 1;
1784}
1785
Christoph Hellwigbb8bf762010-12-16 19:36:31 +01001786int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1787{
1788 if (!bs->drv) {
1789 return -ENOMEDIUM;
1790 }
1791 if (!bs->drv->bdrv_discard) {
1792 return 0;
1793 }
1794 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1795}
1796
thsf58c7b32008-06-05 21:53:49 +00001797/*
1798 * Returns true iff the specified sector is present in the disk image. Drivers
1799 * not implementing the functionality are assumed to not support backing files,
1800 * hence all their sectors are reported as allocated.
1801 *
1802 * 'pnum' is set to the number of sectors (including and immediately following
1803 * the specified sector) that are known to be in the same
1804 * allocated/unallocated state.
1805 *
1806 * 'nb_sectors' is the max value 'pnum' should be set to.
1807 */
1808int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1809 int *pnum)
1810{
1811 int64_t n;
1812 if (!bs->drv->bdrv_is_allocated) {
1813 if (sector_num >= bs->total_sectors) {
1814 *pnum = 0;
1815 return 0;
1816 }
1817 n = bs->total_sectors - sector_num;
1818 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1819 return 1;
1820 }
1821 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1822}
1823
Luiz Capitulino2582bfe2010-02-03 12:41:01 -02001824void bdrv_mon_event(const BlockDriverState *bdrv,
1825 BlockMonEventAction action, int is_read)
1826{
1827 QObject *data;
1828 const char *action_str;
1829
1830 switch (action) {
1831 case BDRV_ACTION_REPORT:
1832 action_str = "report";
1833 break;
1834 case BDRV_ACTION_IGNORE:
1835 action_str = "ignore";
1836 break;
1837 case BDRV_ACTION_STOP:
1838 action_str = "stop";
1839 break;
1840 default:
1841 abort();
1842 }
1843
1844 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1845 bdrv->device_name,
1846 action_str,
1847 is_read ? "read" : "write");
1848 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1849
1850 qobject_decref(data);
1851}
1852
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001853static void bdrv_print_dict(QObject *obj, void *opaque)
bellardb3380822004-03-14 21:38:54 +00001854{
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001855 QDict *bs_dict;
1856 Monitor *mon = opaque;
1857
1858 bs_dict = qobject_to_qdict(obj);
1859
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001860 monitor_printf(mon, "%s: removable=%d",
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001861 qdict_get_str(bs_dict, "device"),
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001862 qdict_get_bool(bs_dict, "removable"));
1863
1864 if (qdict_get_bool(bs_dict, "removable")) {
1865 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
Markus Armbrustere4def802011-09-06 18:58:53 +02001866 monitor_printf(mon, " tray-open=%d",
1867 qdict_get_bool(bs_dict, "tray-open"));
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001868 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001869 if (qdict_haskey(bs_dict, "inserted")) {
1870 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1871
1872 monitor_printf(mon, " file=");
1873 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1874 if (qdict_haskey(qdict, "backing_file")) {
1875 monitor_printf(mon, " backing_file=");
1876 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1877 }
1878 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1879 qdict_get_bool(qdict, "ro"),
1880 qdict_get_str(qdict, "drv"),
1881 qdict_get_bool(qdict, "encrypted"));
1882 } else {
1883 monitor_printf(mon, " [not inserted]");
1884 }
1885
1886 monitor_printf(mon, "\n");
1887}
1888
1889void bdrv_info_print(Monitor *mon, const QObject *data)
1890{
1891 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1892}
1893
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001894void bdrv_info(Monitor *mon, QObject **ret_data)
1895{
1896 QList *bs_list;
bellardb3380822004-03-14 21:38:54 +00001897 BlockDriverState *bs;
1898
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001899 bs_list = qlist_new();
1900
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001901 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001902 QObject *bs_obj;
Markus Armbrustere4def802011-09-06 18:58:53 +02001903 QDict *bs_dict;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001904
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001905 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001906 "'removable': %i, 'locked': %i }",
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001907 bs->device_name,
1908 bdrv_dev_has_removable_media(bs),
Markus Armbrusterf1076392011-09-06 18:58:46 +02001909 bdrv_dev_is_medium_locked(bs));
Markus Armbrustere4def802011-09-06 18:58:53 +02001910 bs_dict = qobject_to_qdict(bs_obj);
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001911
Markus Armbrustere4def802011-09-06 18:58:53 +02001912 if (bdrv_dev_has_removable_media(bs)) {
1913 qdict_put(bs_dict, "tray-open",
1914 qbool_from_int(bdrv_dev_is_tray_open(bs)));
1915 }
bellard19cb3732006-08-19 11:45:59 +00001916 if (bs->drv) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001917 QObject *obj;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001918
1919 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1920 "'encrypted': %i }",
1921 bs->filename, bs->read_only,
1922 bs->drv->format_name,
1923 bdrv_is_encrypted(bs));
thsfef30742006-12-22 14:11:32 +00001924 if (bs->backing_file[0] != '\0') {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001925 QDict *qdict = qobject_to_qdict(obj);
1926 qdict_put(qdict, "backing_file",
1927 qstring_from_str(bs->backing_file));
aliguori376253e2009-03-05 23:01:23 +00001928 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001929
1930 qdict_put_obj(bs_dict, "inserted", obj);
bellardb3380822004-03-14 21:38:54 +00001931 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001932 qlist_append_obj(bs_list, bs_obj);
bellardb3380822004-03-14 21:38:54 +00001933 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001934
1935 *ret_data = QOBJECT(bs_list);
bellardb3380822004-03-14 21:38:54 +00001936}
thsa36e69d2007-12-02 05:18:19 +00001937
Luiz Capitulino218a5362009-12-10 17:16:07 -02001938static void bdrv_stats_iter(QObject *data, void *opaque)
thsa36e69d2007-12-02 05:18:19 +00001939{
Luiz Capitulino218a5362009-12-10 17:16:07 -02001940 QDict *qdict;
1941 Monitor *mon = opaque;
1942
1943 qdict = qobject_to_qdict(data);
1944 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1945
1946 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1947 monitor_printf(mon, " rd_bytes=%" PRId64
1948 " wr_bytes=%" PRId64
1949 " rd_operations=%" PRId64
1950 " wr_operations=%" PRId64
Christoph Hellwige8045d62011-08-22 00:25:58 +02001951 " flush_operations=%" PRId64
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001952 " wr_total_time_ns=%" PRId64
1953 " rd_total_time_ns=%" PRId64
1954 " flush_total_time_ns=%" PRId64
Luiz Capitulino218a5362009-12-10 17:16:07 -02001955 "\n",
1956 qdict_get_int(qdict, "rd_bytes"),
1957 qdict_get_int(qdict, "wr_bytes"),
1958 qdict_get_int(qdict, "rd_operations"),
Christoph Hellwige8045d62011-08-22 00:25:58 +02001959 qdict_get_int(qdict, "wr_operations"),
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001960 qdict_get_int(qdict, "flush_operations"),
1961 qdict_get_int(qdict, "wr_total_time_ns"),
1962 qdict_get_int(qdict, "rd_total_time_ns"),
1963 qdict_get_int(qdict, "flush_total_time_ns"));
Luiz Capitulino218a5362009-12-10 17:16:07 -02001964}
1965
1966void bdrv_stats_print(Monitor *mon, const QObject *data)
1967{
1968 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1969}
1970
Kevin Wolf294cc352010-04-28 14:34:01 +02001971static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1972{
1973 QObject *res;
1974 QDict *dict;
1975
1976 res = qobject_from_jsonf("{ 'stats': {"
1977 "'rd_bytes': %" PRId64 ","
1978 "'wr_bytes': %" PRId64 ","
1979 "'rd_operations': %" PRId64 ","
1980 "'wr_operations': %" PRId64 ","
Christoph Hellwige8045d62011-08-22 00:25:58 +02001981 "'wr_highest_offset': %" PRId64 ","
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001982 "'flush_operations': %" PRId64 ","
1983 "'wr_total_time_ns': %" PRId64 ","
1984 "'rd_total_time_ns': %" PRId64 ","
1985 "'flush_total_time_ns': %" PRId64
Kevin Wolf294cc352010-04-28 14:34:01 +02001986 "} }",
Christoph Hellwiga597e792011-08-25 08:26:01 +02001987 bs->nr_bytes[BDRV_ACCT_READ],
1988 bs->nr_bytes[BDRV_ACCT_WRITE],
1989 bs->nr_ops[BDRV_ACCT_READ],
1990 bs->nr_ops[BDRV_ACCT_WRITE],
Blue Swirl5ffbbc62010-06-14 18:55:33 +00001991 bs->wr_highest_sector *
Christoph Hellwige8045d62011-08-22 00:25:58 +02001992 (uint64_t)BDRV_SECTOR_SIZE,
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001993 bs->nr_ops[BDRV_ACCT_FLUSH],
1994 bs->total_time_ns[BDRV_ACCT_WRITE],
1995 bs->total_time_ns[BDRV_ACCT_READ],
1996 bs->total_time_ns[BDRV_ACCT_FLUSH]);
Kevin Wolf294cc352010-04-28 14:34:01 +02001997 dict = qobject_to_qdict(res);
1998
1999 if (*bs->device_name) {
2000 qdict_put(dict, "device", qstring_from_str(bs->device_name));
2001 }
2002
2003 if (bs->file) {
2004 QObject *parent = bdrv_info_stats_bs(bs->file);
2005 qdict_put_obj(dict, "parent", parent);
2006 }
2007
2008 return res;
2009}
2010
Luiz Capitulino218a5362009-12-10 17:16:07 -02002011void bdrv_info_stats(Monitor *mon, QObject **ret_data)
2012{
2013 QObject *obj;
2014 QList *devices;
thsa36e69d2007-12-02 05:18:19 +00002015 BlockDriverState *bs;
2016
Luiz Capitulino218a5362009-12-10 17:16:07 -02002017 devices = qlist_new();
2018
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002019 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002020 obj = bdrv_info_stats_bs(bs);
Luiz Capitulino218a5362009-12-10 17:16:07 -02002021 qlist_append_obj(devices, obj);
thsa36e69d2007-12-02 05:18:19 +00002022 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02002023
2024 *ret_data = QOBJECT(devices);
thsa36e69d2007-12-02 05:18:19 +00002025}
bellardea2384d2004-08-01 21:59:26 +00002026
aliguori045df332009-03-05 23:00:48 +00002027const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2028{
2029 if (bs->backing_hd && bs->backing_hd->encrypted)
2030 return bs->backing_file;
2031 else if (bs->encrypted)
2032 return bs->filename;
2033 else
2034 return NULL;
2035}
2036
ths5fafdf22007-09-16 21:08:06 +00002037void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00002038 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00002039{
Kevin Wolfb783e402010-01-12 12:55:16 +01002040 if (!bs->backing_file) {
bellard83f64092006-08-01 16:21:11 +00002041 pstrcpy(filename, filename_size, "");
2042 } else {
2043 pstrcpy(filename, filename_size, bs->backing_file);
2044 }
bellardea2384d2004-08-01 21:59:26 +00002045}
2046
ths5fafdf22007-09-16 21:08:06 +00002047int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00002048 const uint8_t *buf, int nb_sectors)
2049{
2050 BlockDriver *drv = bs->drv;
2051 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002052 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002053 if (!drv->bdrv_write_compressed)
2054 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02002055 if (bdrv_check_request(bs, sector_num, nb_sectors))
2056 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002057
Jan Kiszkac6d22832009-11-30 18:21:20 +01002058 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002059 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2060 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002061
bellardfaea38e2006-08-05 21:31:00 +00002062 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2063}
ths3b46e622007-09-17 08:09:54 +00002064
bellardfaea38e2006-08-05 21:31:00 +00002065int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2066{
2067 BlockDriver *drv = bs->drv;
2068 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002069 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002070 if (!drv->bdrv_get_info)
2071 return -ENOTSUP;
2072 memset(bdi, 0, sizeof(*bdi));
2073 return drv->bdrv_get_info(bs, bdi);
2074}
2075
Christoph Hellwig45566e92009-07-10 23:11:57 +02002076int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2077 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002078{
2079 BlockDriver *drv = bs->drv;
2080 if (!drv)
2081 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002082 if (drv->bdrv_save_vmstate)
2083 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2084 if (bs->file)
2085 return bdrv_save_vmstate(bs->file, buf, pos, size);
2086 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002087}
2088
Christoph Hellwig45566e92009-07-10 23:11:57 +02002089int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2090 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002091{
2092 BlockDriver *drv = bs->drv;
2093 if (!drv)
2094 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002095 if (drv->bdrv_load_vmstate)
2096 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2097 if (bs->file)
2098 return bdrv_load_vmstate(bs->file, buf, pos, size);
2099 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002100}
2101
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01002102void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2103{
2104 BlockDriver *drv = bs->drv;
2105
2106 if (!drv || !drv->bdrv_debug_event) {
2107 return;
2108 }
2109
2110 return drv->bdrv_debug_event(bs, event);
2111
2112}
2113
bellardfaea38e2006-08-05 21:31:00 +00002114/**************************************************************/
2115/* handling of snapshots */
2116
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002117int bdrv_can_snapshot(BlockDriverState *bs)
2118{
2119 BlockDriver *drv = bs->drv;
Markus Armbruster07b70bf2011-08-03 15:08:11 +02002120 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002121 return 0;
2122 }
2123
2124 if (!drv->bdrv_snapshot_create) {
2125 if (bs->file != NULL) {
2126 return bdrv_can_snapshot(bs->file);
2127 }
2128 return 0;
2129 }
2130
2131 return 1;
2132}
2133
Blue Swirl199630b2010-07-25 20:49:34 +00002134int bdrv_is_snapshot(BlockDriverState *bs)
2135{
2136 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2137}
2138
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002139BlockDriverState *bdrv_snapshots(void)
2140{
2141 BlockDriverState *bs;
2142
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002143 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002144 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002145 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002146
2147 bs = NULL;
2148 while ((bs = bdrv_next(bs))) {
2149 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002150 bs_snapshots = bs;
2151 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002152 }
2153 }
2154 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002155}
2156
ths5fafdf22007-09-16 21:08:06 +00002157int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002158 QEMUSnapshotInfo *sn_info)
2159{
2160 BlockDriver *drv = bs->drv;
2161 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002162 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002163 if (drv->bdrv_snapshot_create)
2164 return drv->bdrv_snapshot_create(bs, sn_info);
2165 if (bs->file)
2166 return bdrv_snapshot_create(bs->file, sn_info);
2167 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002168}
2169
ths5fafdf22007-09-16 21:08:06 +00002170int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002171 const char *snapshot_id)
2172{
2173 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002174 int ret, open_ret;
2175
bellardfaea38e2006-08-05 21:31:00 +00002176 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002177 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002178 if (drv->bdrv_snapshot_goto)
2179 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2180
2181 if (bs->file) {
2182 drv->bdrv_close(bs);
2183 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2184 open_ret = drv->bdrv_open(bs, bs->open_flags);
2185 if (open_ret < 0) {
2186 bdrv_delete(bs->file);
2187 bs->drv = NULL;
2188 return open_ret;
2189 }
2190 return ret;
2191 }
2192
2193 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002194}
2195
2196int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2197{
2198 BlockDriver *drv = bs->drv;
2199 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002200 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002201 if (drv->bdrv_snapshot_delete)
2202 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2203 if (bs->file)
2204 return bdrv_snapshot_delete(bs->file, snapshot_id);
2205 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002206}
2207
ths5fafdf22007-09-16 21:08:06 +00002208int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002209 QEMUSnapshotInfo **psn_info)
2210{
2211 BlockDriver *drv = bs->drv;
2212 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002213 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002214 if (drv->bdrv_snapshot_list)
2215 return drv->bdrv_snapshot_list(bs, psn_info);
2216 if (bs->file)
2217 return bdrv_snapshot_list(bs->file, psn_info);
2218 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002219}
2220
edison51ef6722010-09-21 19:58:41 -07002221int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2222 const char *snapshot_name)
2223{
2224 BlockDriver *drv = bs->drv;
2225 if (!drv) {
2226 return -ENOMEDIUM;
2227 }
2228 if (!bs->read_only) {
2229 return -EINVAL;
2230 }
2231 if (drv->bdrv_snapshot_load_tmp) {
2232 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2233 }
2234 return -ENOTSUP;
2235}
2236
bellardfaea38e2006-08-05 21:31:00 +00002237#define NB_SUFFIXES 4
2238
2239char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2240{
2241 static const char suffixes[NB_SUFFIXES] = "KMGT";
2242 int64_t base;
2243 int i;
2244
2245 if (size <= 999) {
2246 snprintf(buf, buf_size, "%" PRId64, size);
2247 } else {
2248 base = 1024;
2249 for(i = 0; i < NB_SUFFIXES; i++) {
2250 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00002251 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00002252 (double)size / base,
2253 suffixes[i]);
2254 break;
2255 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00002256 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00002257 ((size + (base >> 1)) / base),
2258 suffixes[i]);
2259 break;
2260 }
2261 base = base * 1024;
2262 }
2263 }
2264 return buf;
2265}
2266
2267char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2268{
2269 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00002270#ifdef _WIN32
2271 struct tm *ptm;
2272#else
bellardfaea38e2006-08-05 21:31:00 +00002273 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00002274#endif
bellardfaea38e2006-08-05 21:31:00 +00002275 time_t ti;
2276 int64_t secs;
2277
2278 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00002279 snprintf(buf, buf_size,
2280 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002281 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2282 } else {
2283 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00002284#ifdef _WIN32
2285 ptm = localtime(&ti);
2286 strftime(date_buf, sizeof(date_buf),
2287 "%Y-%m-%d %H:%M:%S", ptm);
2288#else
bellardfaea38e2006-08-05 21:31:00 +00002289 localtime_r(&ti, &tm);
2290 strftime(date_buf, sizeof(date_buf),
2291 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00002292#endif
bellardfaea38e2006-08-05 21:31:00 +00002293 secs = sn->vm_clock_nsec / 1000000000;
2294 snprintf(clock_buf, sizeof(clock_buf),
2295 "%02d:%02d:%02d.%03d",
2296 (int)(secs / 3600),
2297 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00002298 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00002299 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2300 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00002301 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002302 sn->id_str, sn->name,
2303 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2304 date_buf,
2305 clock_buf);
2306 }
2307 return buf;
2308}
2309
bellard83f64092006-08-01 16:21:11 +00002310/**************************************************************/
2311/* async I/Os */
2312
aliguori3b69e4b2009-01-22 16:59:24 +00002313BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00002314 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00002315 BlockDriverCompletionFunc *cb, void *opaque)
2316{
bellard83f64092006-08-01 16:21:11 +00002317 BlockDriver *drv = bs->drv;
bellard83f64092006-08-01 16:21:11 +00002318
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002319 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2320
bellard19cb3732006-08-19 11:45:59 +00002321 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002322 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002323 if (bdrv_check_request(bs, sector_num, nb_sectors))
2324 return NULL;
ths3b46e622007-09-17 08:09:54 +00002325
Christoph Hellwiga597e792011-08-25 08:26:01 +02002326 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2327 cb, opaque);
bellard83f64092006-08-01 16:21:11 +00002328}
2329
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002330typedef struct BlockCompleteData {
2331 BlockDriverCompletionFunc *cb;
2332 void *opaque;
2333 BlockDriverState *bs;
2334 int64_t sector_num;
2335 int nb_sectors;
2336} BlockCompleteData;
2337
2338static void block_complete_cb(void *opaque, int ret)
2339{
2340 BlockCompleteData *b = opaque;
2341
2342 if (b->bs->dirty_bitmap) {
2343 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2344 }
2345 b->cb(b->opaque, ret);
Anthony Liguori7267c092011-08-20 22:09:37 -05002346 g_free(b);
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002347}
2348
2349static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2350 int64_t sector_num,
2351 int nb_sectors,
2352 BlockDriverCompletionFunc *cb,
2353 void *opaque)
2354{
Anthony Liguori7267c092011-08-20 22:09:37 -05002355 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002356
2357 blkdata->bs = bs;
2358 blkdata->cb = cb;
2359 blkdata->opaque = opaque;
2360 blkdata->sector_num = sector_num;
2361 blkdata->nb_sectors = nb_sectors;
2362
2363 return blkdata;
2364}
2365
aliguorif141eaf2009-04-07 18:43:24 +00002366BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2367 QEMUIOVector *qiov, int nb_sectors,
2368 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002369{
bellard83f64092006-08-01 16:21:11 +00002370 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002371 BlockDriverAIOCB *ret;
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002372 BlockCompleteData *blk_cb_data;
bellard83f64092006-08-01 16:21:11 +00002373
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002374 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2375
bellard19cb3732006-08-19 11:45:59 +00002376 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002377 return NULL;
bellard83f64092006-08-01 16:21:11 +00002378 if (bs->read_only)
pbrookce1a14d2006-08-07 02:38:06 +00002379 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002380 if (bdrv_check_request(bs, sector_num, nb_sectors))
2381 return NULL;
bellard83f64092006-08-01 16:21:11 +00002382
Jan Kiszkac6d22832009-11-30 18:21:20 +01002383 if (bs->dirty_bitmap) {
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002384 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2385 opaque);
2386 cb = &block_complete_cb;
2387 opaque = blk_cb_data;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002388 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002389
aliguorif141eaf2009-04-07 18:43:24 +00002390 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2391 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002392
2393 if (ret) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002394 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2395 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2396 }
thsa36e69d2007-12-02 05:18:19 +00002397 }
2398
2399 return ret;
bellard83f64092006-08-01 16:21:11 +00002400}
2401
Kevin Wolf40b4f532009-09-09 17:53:37 +02002402
2403typedef struct MultiwriteCB {
2404 int error;
2405 int num_requests;
2406 int num_callbacks;
2407 struct {
2408 BlockDriverCompletionFunc *cb;
2409 void *opaque;
2410 QEMUIOVector *free_qiov;
2411 void *free_buf;
2412 } callbacks[];
2413} MultiwriteCB;
2414
2415static void multiwrite_user_cb(MultiwriteCB *mcb)
2416{
2417 int i;
2418
2419 for (i = 0; i < mcb->num_callbacks; i++) {
2420 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01002421 if (mcb->callbacks[i].free_qiov) {
2422 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2423 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002424 g_free(mcb->callbacks[i].free_qiov);
Herve Poussineauf8a83242010-01-24 21:23:56 +00002425 qemu_vfree(mcb->callbacks[i].free_buf);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002426 }
2427}
2428
2429static void multiwrite_cb(void *opaque, int ret)
2430{
2431 MultiwriteCB *mcb = opaque;
2432
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002433 trace_multiwrite_cb(mcb, ret);
2434
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02002435 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02002436 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002437 }
2438
2439 mcb->num_requests--;
2440 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02002441 multiwrite_user_cb(mcb);
Anthony Liguori7267c092011-08-20 22:09:37 -05002442 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002443 }
2444}
2445
2446static int multiwrite_req_compare(const void *a, const void *b)
2447{
Christoph Hellwig77be4362010-05-19 20:53:10 +02002448 const BlockRequest *req1 = a, *req2 = b;
2449
2450 /*
2451 * Note that we can't simply subtract req2->sector from req1->sector
2452 * here as that could overflow the return value.
2453 */
2454 if (req1->sector > req2->sector) {
2455 return 1;
2456 } else if (req1->sector < req2->sector) {
2457 return -1;
2458 } else {
2459 return 0;
2460 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002461}
2462
2463/*
2464 * Takes a bunch of requests and tries to merge them. Returns the number of
2465 * requests that remain after merging.
2466 */
2467static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2468 int num_reqs, MultiwriteCB *mcb)
2469{
2470 int i, outidx;
2471
2472 // Sort requests by start sector
2473 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2474
2475 // Check if adjacent requests touch the same clusters. If so, combine them,
2476 // filling up gaps with zero sectors.
2477 outidx = 0;
2478 for (i = 1; i < num_reqs; i++) {
2479 int merge = 0;
2480 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2481
2482 // This handles the cases that are valid for all block drivers, namely
2483 // exactly sequential writes and overlapping writes.
2484 if (reqs[i].sector <= oldreq_last) {
2485 merge = 1;
2486 }
2487
2488 // The block driver may decide that it makes sense to combine requests
2489 // even if there is a gap of some sectors between them. In this case,
2490 // the gap is filled with zeros (therefore only applicable for yet
2491 // unused space in format like qcow2).
2492 if (!merge && bs->drv->bdrv_merge_requests) {
2493 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2494 }
2495
Christoph Hellwige2a305f2010-01-26 14:49:08 +01002496 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2497 merge = 0;
2498 }
2499
Kevin Wolf40b4f532009-09-09 17:53:37 +02002500 if (merge) {
2501 size_t size;
Anthony Liguori7267c092011-08-20 22:09:37 -05002502 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002503 qemu_iovec_init(qiov,
2504 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2505
2506 // Add the first request to the merged one. If the requests are
2507 // overlapping, drop the last sectors of the first request.
2508 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2509 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2510
2511 // We might need to add some zeros between the two requests
2512 if (reqs[i].sector > oldreq_last) {
2513 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2514 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2515 memset(buf, 0, zero_bytes);
2516 qemu_iovec_add(qiov, buf, zero_bytes);
2517 mcb->callbacks[i].free_buf = buf;
2518 }
2519
2520 // Add the second request
2521 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2522
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02002523 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002524 reqs[outidx].qiov = qiov;
2525
2526 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2527 } else {
2528 outidx++;
2529 reqs[outidx].sector = reqs[i].sector;
2530 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2531 reqs[outidx].qiov = reqs[i].qiov;
2532 }
2533 }
2534
2535 return outidx + 1;
2536}
2537
2538/*
2539 * Submit multiple AIO write requests at once.
2540 *
2541 * On success, the function returns 0 and all requests in the reqs array have
2542 * been submitted. In error case this function returns -1, and any of the
2543 * requests may or may not be submitted yet. In particular, this means that the
2544 * callback will be called for some of the requests, for others it won't. The
2545 * caller must check the error field of the BlockRequest to wait for the right
2546 * callbacks (if error != 0, no callback will be called).
2547 *
2548 * The implementation may modify the contents of the reqs array, e.g. to merge
2549 * requests. However, the fields opaque and error are left unmodified as they
2550 * are used to signal failure for a single request to the caller.
2551 */
2552int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2553{
2554 BlockDriverAIOCB *acb;
2555 MultiwriteCB *mcb;
2556 int i;
2557
Ryan Harper301db7c2011-03-07 10:01:04 -06002558 /* don't submit writes if we don't have a medium */
2559 if (bs->drv == NULL) {
2560 for (i = 0; i < num_reqs; i++) {
2561 reqs[i].error = -ENOMEDIUM;
2562 }
2563 return -1;
2564 }
2565
Kevin Wolf40b4f532009-09-09 17:53:37 +02002566 if (num_reqs == 0) {
2567 return 0;
2568 }
2569
2570 // Create MultiwriteCB structure
Anthony Liguori7267c092011-08-20 22:09:37 -05002571 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002572 mcb->num_requests = 0;
2573 mcb->num_callbacks = num_reqs;
2574
2575 for (i = 0; i < num_reqs; i++) {
2576 mcb->callbacks[i].cb = reqs[i].cb;
2577 mcb->callbacks[i].opaque = reqs[i].opaque;
2578 }
2579
2580 // Check for mergable requests
2581 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2582
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002583 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2584
Kevin Wolf453f9a12010-07-02 14:01:21 +02002585 /*
2586 * Run the aio requests. As soon as one request can't be submitted
2587 * successfully, fail all requests that are not yet submitted (we must
2588 * return failure for all requests anyway)
2589 *
2590 * num_requests cannot be set to the right value immediately: If
2591 * bdrv_aio_writev fails for some request, num_requests would be too high
2592 * and therefore multiwrite_cb() would never recognize the multiwrite
2593 * request as completed. We also cannot use the loop variable i to set it
2594 * when the first request fails because the callback may already have been
2595 * called for previously submitted requests. Thus, num_requests must be
2596 * incremented for each request that is submitted.
2597 *
2598 * The problem that callbacks may be called early also means that we need
2599 * to take care that num_requests doesn't become 0 before all requests are
2600 * submitted - multiwrite_cb() would consider the multiwrite request
2601 * completed. A dummy request that is "completed" by a manual call to
2602 * multiwrite_cb() takes care of this.
2603 */
2604 mcb->num_requests = 1;
2605
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002606 // Run the aio requests
Kevin Wolf40b4f532009-09-09 17:53:37 +02002607 for (i = 0; i < num_reqs; i++) {
Kevin Wolf453f9a12010-07-02 14:01:21 +02002608 mcb->num_requests++;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002609 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2610 reqs[i].nb_sectors, multiwrite_cb, mcb);
2611
2612 if (acb == NULL) {
2613 // We can only fail the whole thing if no request has been
2614 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2615 // complete and report the error in the callback.
Kevin Wolf453f9a12010-07-02 14:01:21 +02002616 if (i == 0) {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002617 trace_bdrv_aio_multiwrite_earlyfail(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002618 goto fail;
2619 } else {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002620 trace_bdrv_aio_multiwrite_latefail(mcb, i);
Kevin Wolf7eb58a62010-04-06 18:24:07 +02002621 multiwrite_cb(mcb, -EIO);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002622 break;
2623 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002624 }
2625 }
2626
Kevin Wolf453f9a12010-07-02 14:01:21 +02002627 /* Complete the dummy request */
2628 multiwrite_cb(mcb, 0);
2629
Kevin Wolf40b4f532009-09-09 17:53:37 +02002630 return 0;
2631
2632fail:
Kevin Wolf453f9a12010-07-02 14:01:21 +02002633 for (i = 0; i < mcb->num_callbacks; i++) {
2634 reqs[i].error = -EIO;
2635 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002636 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002637 return -1;
2638}
2639
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002640BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2641 BlockDriverCompletionFunc *cb, void *opaque)
2642{
2643 BlockDriver *drv = bs->drv;
2644
Stefan Hajnoczia13aac02011-03-07 07:58:04 +00002645 trace_bdrv_aio_flush(bs, opaque);
2646
Alexander Graf016f5cf2010-05-26 17:51:49 +02002647 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2648 return bdrv_aio_noop_em(bs, cb, opaque);
2649 }
2650
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002651 if (!drv)
2652 return NULL;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002653 return drv->bdrv_aio_flush(bs, cb, opaque);
2654}
2655
bellard83f64092006-08-01 16:21:11 +00002656void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00002657{
aliguori6bbff9a2009-03-20 18:25:59 +00002658 acb->pool->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00002659}
2660
pbrookce1a14d2006-08-07 02:38:06 +00002661
bellard83f64092006-08-01 16:21:11 +00002662/**************************************************************/
2663/* async block device emulation */
2664
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002665typedef struct BlockDriverAIOCBSync {
2666 BlockDriverAIOCB common;
2667 QEMUBH *bh;
2668 int ret;
2669 /* vector translation state */
2670 QEMUIOVector *qiov;
2671 uint8_t *bounce;
2672 int is_write;
2673} BlockDriverAIOCBSync;
2674
2675static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2676{
Kevin Wolfb666d232010-05-05 11:44:39 +02002677 BlockDriverAIOCBSync *acb =
2678 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03002679 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002680 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002681 qemu_aio_release(acb);
2682}
2683
2684static AIOPool bdrv_em_aio_pool = {
2685 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2686 .cancel = bdrv_aio_cancel_em,
2687};
2688
bellard83f64092006-08-01 16:21:11 +00002689static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00002690{
pbrookce1a14d2006-08-07 02:38:06 +00002691 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00002692
aliguorif141eaf2009-04-07 18:43:24 +00002693 if (!acb->is_write)
2694 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00002695 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00002696 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03002697 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002698 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00002699 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00002700}
bellardbeac80c2006-06-26 20:08:57 +00002701
aliguorif141eaf2009-04-07 18:43:24 +00002702static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2703 int64_t sector_num,
2704 QEMUIOVector *qiov,
2705 int nb_sectors,
2706 BlockDriverCompletionFunc *cb,
2707 void *opaque,
2708 int is_write)
2709
bellardea2384d2004-08-01 21:59:26 +00002710{
pbrookce1a14d2006-08-07 02:38:06 +00002711 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00002712
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002713 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00002714 acb->is_write = is_write;
2715 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00002716 acb->bounce = qemu_blockalign(bs, qiov->size);
aliguorif141eaf2009-04-07 18:43:24 +00002717
pbrookce1a14d2006-08-07 02:38:06 +00002718 if (!acb->bh)
2719 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00002720
2721 if (is_write) {
2722 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2723 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2724 } else {
2725 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2726 }
2727
pbrookce1a14d2006-08-07 02:38:06 +00002728 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00002729
pbrookce1a14d2006-08-07 02:38:06 +00002730 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00002731}
2732
aliguorif141eaf2009-04-07 18:43:24 +00002733static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2734 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00002735 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002736{
aliguorif141eaf2009-04-07 18:43:24 +00002737 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00002738}
2739
aliguorif141eaf2009-04-07 18:43:24 +00002740static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2741 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2742 BlockDriverCompletionFunc *cb, void *opaque)
2743{
2744 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2745}
2746
Kevin Wolf68485422011-06-30 10:05:46 +02002747
2748typedef struct BlockDriverAIOCBCoroutine {
2749 BlockDriverAIOCB common;
2750 BlockRequest req;
2751 bool is_write;
2752 QEMUBH* bh;
2753} BlockDriverAIOCBCoroutine;
2754
2755static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2756{
2757 qemu_aio_flush();
2758}
2759
2760static AIOPool bdrv_em_co_aio_pool = {
2761 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2762 .cancel = bdrv_aio_co_cancel_em,
2763};
2764
2765static void bdrv_co_rw_bh(void *opaque)
2766{
2767 BlockDriverAIOCBCoroutine *acb = opaque;
2768
2769 acb->common.cb(acb->common.opaque, acb->req.error);
2770 qemu_bh_delete(acb->bh);
2771 qemu_aio_release(acb);
2772}
2773
2774static void coroutine_fn bdrv_co_rw(void *opaque)
2775{
2776 BlockDriverAIOCBCoroutine *acb = opaque;
2777 BlockDriverState *bs = acb->common.bs;
2778
2779 if (!acb->is_write) {
2780 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2781 acb->req.nb_sectors, acb->req.qiov);
2782 } else {
2783 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2784 acb->req.nb_sectors, acb->req.qiov);
2785 }
2786
2787 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2788 qemu_bh_schedule(acb->bh);
2789}
2790
2791static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2792 int64_t sector_num,
2793 QEMUIOVector *qiov,
2794 int nb_sectors,
2795 BlockDriverCompletionFunc *cb,
2796 void *opaque,
2797 bool is_write)
2798{
2799 Coroutine *co;
2800 BlockDriverAIOCBCoroutine *acb;
2801
2802 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2803 acb->req.sector = sector_num;
2804 acb->req.nb_sectors = nb_sectors;
2805 acb->req.qiov = qiov;
2806 acb->is_write = is_write;
2807
2808 co = qemu_coroutine_create(bdrv_co_rw);
2809 qemu_coroutine_enter(co, acb);
2810
2811 return &acb->common;
2812}
2813
2814static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2815 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2816 BlockDriverCompletionFunc *cb, void *opaque)
2817{
2818 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2819 false);
2820}
2821
2822static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2823 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2824 BlockDriverCompletionFunc *cb, void *opaque)
2825{
2826 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2827 true);
2828}
2829
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002830static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2831 BlockDriverCompletionFunc *cb, void *opaque)
2832{
2833 BlockDriverAIOCBSync *acb;
2834
2835 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2836 acb->is_write = 1; /* don't bounce in the completion hadler */
2837 acb->qiov = NULL;
2838 acb->bounce = NULL;
2839 acb->ret = 0;
2840
2841 if (!acb->bh)
2842 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2843
2844 bdrv_flush(bs);
2845 qemu_bh_schedule(acb->bh);
2846 return &acb->common;
2847}
2848
Alexander Graf016f5cf2010-05-26 17:51:49 +02002849static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2850 BlockDriverCompletionFunc *cb, void *opaque)
2851{
2852 BlockDriverAIOCBSync *acb;
2853
2854 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2855 acb->is_write = 1; /* don't bounce in the completion handler */
2856 acb->qiov = NULL;
2857 acb->bounce = NULL;
2858 acb->ret = 0;
2859
2860 if (!acb->bh) {
2861 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2862 }
2863
2864 qemu_bh_schedule(acb->bh);
2865 return &acb->common;
2866}
2867
bellard83f64092006-08-01 16:21:11 +00002868/**************************************************************/
2869/* sync block device emulation */
2870
2871static void bdrv_rw_em_cb(void *opaque, int ret)
2872{
2873 *(int *)opaque = ret;
2874}
2875
2876#define NOT_DONE 0x7fffffff
2877
ths5fafdf22007-09-16 21:08:06 +00002878static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +00002879 uint8_t *buf, int nb_sectors)
2880{
pbrookce1a14d2006-08-07 02:38:06 +00002881 int async_ret;
2882 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002883 struct iovec iov;
2884 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002885
bellard83f64092006-08-01 16:21:11 +00002886 async_ret = NOT_DONE;
blueswir13f4cb3d2009-04-13 16:31:01 +00002887 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002888 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002889 qemu_iovec_init_external(&qiov, &iov, 1);
2890 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2891 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002892 if (acb == NULL) {
2893 async_ret = -1;
2894 goto fail;
2895 }
aliguoribaf35cb2008-09-10 15:45:19 +00002896
bellard83f64092006-08-01 16:21:11 +00002897 while (async_ret == NOT_DONE) {
2898 qemu_aio_wait();
2899 }
aliguoribaf35cb2008-09-10 15:45:19 +00002900
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002901
2902fail:
bellard83f64092006-08-01 16:21:11 +00002903 return async_ret;
2904}
2905
2906static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2907 const uint8_t *buf, int nb_sectors)
2908{
pbrookce1a14d2006-08-07 02:38:06 +00002909 int async_ret;
2910 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002911 struct iovec iov;
2912 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002913
bellard83f64092006-08-01 16:21:11 +00002914 async_ret = NOT_DONE;
aliguorif141eaf2009-04-07 18:43:24 +00002915 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002916 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002917 qemu_iovec_init_external(&qiov, &iov, 1);
2918 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2919 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002920 if (acb == NULL) {
2921 async_ret = -1;
2922 goto fail;
2923 }
bellard83f64092006-08-01 16:21:11 +00002924 while (async_ret == NOT_DONE) {
2925 qemu_aio_wait();
2926 }
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002927
2928fail:
bellard83f64092006-08-01 16:21:11 +00002929 return async_ret;
2930}
bellardea2384d2004-08-01 21:59:26 +00002931
2932void bdrv_init(void)
2933{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05002934 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00002935}
pbrookce1a14d2006-08-07 02:38:06 +00002936
Markus Armbrustereb852012009-10-27 18:41:44 +01002937void bdrv_init_with_whitelist(void)
2938{
2939 use_bdrv_whitelist = 1;
2940 bdrv_init();
2941}
2942
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002943void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2944 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00002945{
pbrookce1a14d2006-08-07 02:38:06 +00002946 BlockDriverAIOCB *acb;
2947
aliguori6bbff9a2009-03-20 18:25:59 +00002948 if (pool->free_aiocb) {
2949 acb = pool->free_aiocb;
2950 pool->free_aiocb = acb->next;
pbrookce1a14d2006-08-07 02:38:06 +00002951 } else {
Anthony Liguori7267c092011-08-20 22:09:37 -05002952 acb = g_malloc0(pool->aiocb_size);
aliguori6bbff9a2009-03-20 18:25:59 +00002953 acb->pool = pool;
pbrookce1a14d2006-08-07 02:38:06 +00002954 }
2955 acb->bs = bs;
2956 acb->cb = cb;
2957 acb->opaque = opaque;
2958 return acb;
2959}
2960
2961void qemu_aio_release(void *p)
2962{
aliguori6bbff9a2009-03-20 18:25:59 +00002963 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2964 AIOPool *pool = acb->pool;
2965 acb->next = pool->free_aiocb;
2966 pool->free_aiocb = acb;
pbrookce1a14d2006-08-07 02:38:06 +00002967}
bellard19cb3732006-08-19 11:45:59 +00002968
2969/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02002970/* Coroutine block device emulation */
2971
2972typedef struct CoroutineIOCompletion {
2973 Coroutine *coroutine;
2974 int ret;
2975} CoroutineIOCompletion;
2976
2977static void bdrv_co_io_em_complete(void *opaque, int ret)
2978{
2979 CoroutineIOCompletion *co = opaque;
2980
2981 co->ret = ret;
2982 qemu_coroutine_enter(co->coroutine, NULL);
2983}
2984
2985static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2986 int nb_sectors, QEMUIOVector *iov,
2987 bool is_write)
2988{
2989 CoroutineIOCompletion co = {
2990 .coroutine = qemu_coroutine_self(),
2991 };
2992 BlockDriverAIOCB *acb;
2993
2994 if (is_write) {
2995 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2996 bdrv_co_io_em_complete, &co);
2997 } else {
2998 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2999 bdrv_co_io_em_complete, &co);
3000 }
3001
3002 trace_bdrv_co_io(is_write, acb);
3003 if (!acb) {
3004 return -EIO;
3005 }
3006 qemu_coroutine_yield();
3007
3008 return co.ret;
3009}
3010
3011static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3012 int64_t sector_num, int nb_sectors,
3013 QEMUIOVector *iov)
3014{
3015 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3016}
3017
3018static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3019 int64_t sector_num, int nb_sectors,
3020 QEMUIOVector *iov)
3021{
3022 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3023}
3024
Kevin Wolfe7a8a782011-07-15 16:05:00 +02003025static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3026{
3027 CoroutineIOCompletion co = {
3028 .coroutine = qemu_coroutine_self(),
3029 };
3030 BlockDriverAIOCB *acb;
3031
3032 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3033 if (!acb) {
3034 return -EIO;
3035 }
3036 qemu_coroutine_yield();
3037 return co.ret;
3038}
3039
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003040/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00003041/* removable device support */
3042
3043/**
3044 * Return TRUE if the media is present
3045 */
3046int bdrv_is_inserted(BlockDriverState *bs)
3047{
3048 BlockDriver *drv = bs->drv;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003049
bellard19cb3732006-08-19 11:45:59 +00003050 if (!drv)
3051 return 0;
3052 if (!drv->bdrv_is_inserted)
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003053 return 1;
3054 return drv->bdrv_is_inserted(bs);
bellard19cb3732006-08-19 11:45:59 +00003055}
3056
3057/**
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003058 * Return whether the media changed since the last call to this
3059 * function, or -ENOTSUP if we don't know. Most drivers don't know.
bellard19cb3732006-08-19 11:45:59 +00003060 */
3061int bdrv_media_changed(BlockDriverState *bs)
3062{
3063 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003064
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003065 if (drv && drv->bdrv_media_changed) {
3066 return drv->bdrv_media_changed(bs);
3067 }
3068 return -ENOTSUP;
bellard19cb3732006-08-19 11:45:59 +00003069}
3070
3071/**
3072 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3073 */
Markus Armbrusterfdec4402011-09-06 18:58:45 +02003074void bdrv_eject(BlockDriverState *bs, int eject_flag)
bellard19cb3732006-08-19 11:45:59 +00003075{
3076 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003077
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003078 if (drv && drv->bdrv_eject) {
3079 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00003080 }
bellard19cb3732006-08-19 11:45:59 +00003081}
3082
bellard19cb3732006-08-19 11:45:59 +00003083/**
3084 * Lock or unlock the media (if it is locked, the user won't be able
3085 * to eject it manually).
3086 */
Markus Armbruster025e8492011-09-06 18:58:47 +02003087void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00003088{
3089 BlockDriver *drv = bs->drv;
3090
Markus Armbruster025e8492011-09-06 18:58:47 +02003091 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01003092
Markus Armbruster025e8492011-09-06 18:58:47 +02003093 if (drv && drv->bdrv_lock_medium) {
3094 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00003095 }
3096}
ths985a03b2007-12-24 16:10:43 +00003097
3098/* needed for generic scsi interface */
3099
3100int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3101{
3102 BlockDriver *drv = bs->drv;
3103
3104 if (drv && drv->bdrv_ioctl)
3105 return drv->bdrv_ioctl(bs, req, buf);
3106 return -ENOTSUP;
3107}
aliguori7d780662009-03-12 19:57:08 +00003108
aliguori221f7152009-03-28 17:28:41 +00003109BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3110 unsigned long int req, void *buf,
3111 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00003112{
aliguori221f7152009-03-28 17:28:41 +00003113 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00003114
aliguori221f7152009-03-28 17:28:41 +00003115 if (drv && drv->bdrv_aio_ioctl)
3116 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3117 return NULL;
aliguori7d780662009-03-12 19:57:08 +00003118}
aliguorie268ca52009-04-22 20:20:00 +00003119
Markus Armbruster7b6f9302011-09-06 18:58:56 +02003120void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
3121{
3122 bs->buffer_alignment = align;
3123}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003124
aliguorie268ca52009-04-22 20:20:00 +00003125void *qemu_blockalign(BlockDriverState *bs, size_t size)
3126{
3127 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3128}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003129
3130void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3131{
3132 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003133
Liran Schouraaa0eb72010-01-26 10:31:48 +02003134 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003135 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003136 if (!bs->dirty_bitmap) {
3137 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3138 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3139 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003140
Anthony Liguori7267c092011-08-20 22:09:37 -05003141 bs->dirty_bitmap = g_malloc0(bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003142 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003143 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003144 if (bs->dirty_bitmap) {
Anthony Liguori7267c092011-08-20 22:09:37 -05003145 g_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01003146 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003147 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003148 }
3149}
3150
3151int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3152{
Jan Kiszka6ea44302009-11-30 18:21:19 +01003153 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003154
Jan Kiszkac6d22832009-11-30 18:21:20 +01003155 if (bs->dirty_bitmap &&
3156 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02003157 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3158 (1UL << (chunk % (sizeof(unsigned long) * 8))));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003159 } else {
3160 return 0;
3161 }
3162}
3163
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003164void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3165 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003166{
3167 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3168}
Liran Schouraaa0eb72010-01-26 10:31:48 +02003169
3170int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3171{
3172 return bs->dirty_count;
3173}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003174
Marcelo Tosattidb593f22011-01-26 12:12:34 -02003175void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3176{
3177 assert(bs->in_use != in_use);
3178 bs->in_use = in_use;
3179}
3180
3181int bdrv_in_use(BlockDriverState *bs)
3182{
3183 return bs->in_use;
3184}
3185
Christoph Hellwiga597e792011-08-25 08:26:01 +02003186void
3187bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3188 enum BlockAcctType type)
3189{
3190 assert(type < BDRV_MAX_IOTYPE);
3191
3192 cookie->bytes = bytes;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003193 cookie->start_time_ns = get_clock();
Christoph Hellwiga597e792011-08-25 08:26:01 +02003194 cookie->type = type;
3195}
3196
3197void
3198bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3199{
3200 assert(cookie->type < BDRV_MAX_IOTYPE);
3201
3202 bs->nr_bytes[cookie->type] += cookie->bytes;
3203 bs->nr_ops[cookie->type]++;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003204 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
Christoph Hellwiga597e792011-08-25 08:26:01 +02003205}
3206
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003207int bdrv_img_create(const char *filename, const char *fmt,
3208 const char *base_filename, const char *base_fmt,
3209 char *options, uint64_t img_size, int flags)
3210{
3211 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02003212 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003213 BlockDriverState *bs = NULL;
3214 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003215 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003216 int ret = 0;
3217
3218 /* Find driver and parse its options */
3219 drv = bdrv_find_format(fmt);
3220 if (!drv) {
3221 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003222 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003223 goto out;
3224 }
3225
3226 proto_drv = bdrv_find_protocol(filename);
3227 if (!proto_drv) {
3228 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003229 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003230 goto out;
3231 }
3232
3233 create_options = append_option_parameters(create_options,
3234 drv->create_options);
3235 create_options = append_option_parameters(create_options,
3236 proto_drv->create_options);
3237
3238 /* Create parameter list with default values */
3239 param = parse_option_parameters("", create_options, param);
3240
3241 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3242
3243 /* Parse -o options */
3244 if (options) {
3245 param = parse_option_parameters(options, create_options, param);
3246 if (param == NULL) {
3247 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003248 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003249 goto out;
3250 }
3251 }
3252
3253 if (base_filename) {
3254 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3255 base_filename)) {
3256 error_report("Backing file not supported for file format '%s'",
3257 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003258 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003259 goto out;
3260 }
3261 }
3262
3263 if (base_fmt) {
3264 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3265 error_report("Backing file format not supported for file "
3266 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003267 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003268 goto out;
3269 }
3270 }
3271
Jes Sorensen792da932010-12-16 13:52:17 +01003272 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3273 if (backing_file && backing_file->value.s) {
3274 if (!strcmp(filename, backing_file->value.s)) {
3275 error_report("Error: Trying to create an image with the "
3276 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003277 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01003278 goto out;
3279 }
3280 }
3281
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003282 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3283 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003284 backing_drv = bdrv_find_format(backing_fmt->value.s);
3285 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003286 error_report("Unknown backing file format '%s'",
3287 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003288 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003289 goto out;
3290 }
3291 }
3292
3293 // The size for the image must always be specified, with one exception:
3294 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02003295 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3296 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003297 if (backing_file && backing_file->value.s) {
3298 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003299 char buf[32];
3300
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003301 bs = bdrv_new("");
3302
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003303 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003304 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003305 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003306 goto out;
3307 }
3308 bdrv_get_geometry(bs, &size);
3309 size *= 512;
3310
3311 snprintf(buf, sizeof(buf), "%" PRId64, size);
3312 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3313 } else {
3314 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003315 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003316 goto out;
3317 }
3318 }
3319
3320 printf("Formatting '%s', fmt=%s ", filename, fmt);
3321 print_option_parameters(param);
3322 puts("");
3323
3324 ret = bdrv_create(drv, filename, param);
3325
3326 if (ret < 0) {
3327 if (ret == -ENOTSUP) {
3328 error_report("Formatting or formatting option not supported for "
3329 "file format '%s'", fmt);
3330 } else if (ret == -EFBIG) {
3331 error_report("The image size is too large for file format '%s'",
3332 fmt);
3333 } else {
3334 error_report("%s: error while creating %s: %s", filename, fmt,
3335 strerror(-ret));
3336 }
3337 }
3338
3339out:
3340 free_option_parameters(create_options);
3341 free_option_parameters(param);
3342
3343 if (bs) {
3344 bdrv_delete(bs);
3345 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01003346
3347 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003348}