blob: dbef3ae6725adb5ebd99129f80753856d088b21d [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
aliguorif141eaf2009-04-07 18:43:24 +000047static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
48 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
aliguoric87c0672009-04-07 18:43:20 +000049 BlockDriverCompletionFunc *cb, void *opaque);
aliguorif141eaf2009-04-07 18:43:24 +000050static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
51 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +000052 BlockDriverCompletionFunc *cb, void *opaque);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +020053static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
Alexander Graf016f5cf2010-05-26 17:51:49 +020055static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
56 BlockDriverCompletionFunc *cb, void *opaque);
ths5fafdf22007-09-16 21:08:06 +000057static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +000058 uint8_t *buf, int nb_sectors);
59static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
60 const uint8_t *buf, int nb_sectors);
Kevin Wolf68485422011-06-30 10:05:46 +020061static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
62 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63 BlockDriverCompletionFunc *cb, void *opaque);
64static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
65 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66 BlockDriverCompletionFunc *cb, void *opaque);
Kevin Wolff9f05dc2011-07-15 13:50:26 +020067static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
68 int64_t sector_num, int nb_sectors,
69 QEMUIOVector *iov);
70static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
71 int64_t sector_num, int nb_sectors,
72 QEMUIOVector *iov);
Kevin Wolfe7a8a782011-07-15 16:05:00 +020073static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
bellardec530c82006-04-25 22:36:06 +000074
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +010075static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
76 QTAILQ_HEAD_INITIALIZER(bdrv_states);
blueswir17ee930d2008-09-17 19:04:14 +000077
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010078static QLIST_HEAD(, BlockDriver) bdrv_drivers =
79 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000080
Markus Armbrusterf9092b12010-06-25 10:33:39 +020081/* The device to use for VM snapshots */
82static BlockDriverState *bs_snapshots;
83
Markus Armbrustereb852012009-10-27 18:41:44 +010084/* If non-zero, use only whitelisted block drivers */
85static int use_bdrv_whitelist;
86
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000087#ifdef _WIN32
88static int is_windows_drive_prefix(const char *filename)
89{
90 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
91 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
92 filename[1] == ':');
93}
94
95int is_windows_drive(const char *filename)
96{
97 if (is_windows_drive_prefix(filename) &&
98 filename[2] == '\0')
99 return 1;
100 if (strstart(filename, "\\\\.\\", NULL) ||
101 strstart(filename, "//./", NULL))
102 return 1;
103 return 0;
104}
105#endif
106
107/* check if the path starts with "<protocol>:" */
108static int path_has_protocol(const char *path)
109{
110#ifdef _WIN32
111 if (is_windows_drive(path) ||
112 is_windows_drive_prefix(path)) {
113 return 0;
114 }
115#endif
116
117 return strchr(path, ':') != NULL;
118}
119
bellard83f64092006-08-01 16:21:11 +0000120int path_is_absolute(const char *path)
121{
122 const char *p;
bellard21664422007-01-07 18:22:37 +0000123#ifdef _WIN32
124 /* specific case for names like: "\\.\d:" */
125 if (*path == '/' || *path == '\\')
126 return 1;
127#endif
bellard83f64092006-08-01 16:21:11 +0000128 p = strchr(path, ':');
129 if (p)
130 p++;
131 else
132 p = path;
bellard3b9f94e2007-01-07 17:27:07 +0000133#ifdef _WIN32
134 return (*p == '/' || *p == '\\');
135#else
136 return (*p == '/');
137#endif
bellard83f64092006-08-01 16:21:11 +0000138}
139
140/* if filename is absolute, just copy it to dest. Otherwise, build a
141 path to it by considering it is relative to base_path. URL are
142 supported. */
143void path_combine(char *dest, int dest_size,
144 const char *base_path,
145 const char *filename)
146{
147 const char *p, *p1;
148 int len;
149
150 if (dest_size <= 0)
151 return;
152 if (path_is_absolute(filename)) {
153 pstrcpy(dest, dest_size, filename);
154 } else {
155 p = strchr(base_path, ':');
156 if (p)
157 p++;
158 else
159 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000160 p1 = strrchr(base_path, '/');
161#ifdef _WIN32
162 {
163 const char *p2;
164 p2 = strrchr(base_path, '\\');
165 if (!p1 || p2 > p1)
166 p1 = p2;
167 }
168#endif
bellard83f64092006-08-01 16:21:11 +0000169 if (p1)
170 p1++;
171 else
172 p1 = base_path;
173 if (p1 > p)
174 p = p1;
175 len = p - base_path;
176 if (len > dest_size - 1)
177 len = dest_size - 1;
178 memcpy(dest, base_path, len);
179 dest[len] = '\0';
180 pstrcat(dest, dest_size, filename);
181 }
182}
183
Anthony Liguori5efa9d52009-05-09 17:03:42 -0500184void bdrv_register(BlockDriver *bdrv)
bellardea2384d2004-08-01 21:59:26 +0000185{
Kevin Wolf68485422011-06-30 10:05:46 +0200186 if (bdrv->bdrv_co_readv) {
187 /* Emulate AIO by coroutines, and sync by AIO */
188 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
189 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
190 bdrv->bdrv_read = bdrv_read_em;
191 bdrv->bdrv_write = bdrv_write_em;
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200192 } else {
193 bdrv->bdrv_co_readv = bdrv_co_readv_em;
194 bdrv->bdrv_co_writev = bdrv_co_writev_em;
195
196 if (!bdrv->bdrv_aio_readv) {
197 /* add AIO emulation layer */
198 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
199 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
200 } else if (!bdrv->bdrv_read) {
201 /* add synchronous IO emulation layer */
202 bdrv->bdrv_read = bdrv_read_em;
203 bdrv->bdrv_write = bdrv_write_em;
204 }
bellard83f64092006-08-01 16:21:11 +0000205 }
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +0200206
207 if (!bdrv->bdrv_aio_flush)
208 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
209
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100210 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000211}
bellardb3380822004-03-14 21:38:54 +0000212
213/* create a new block device (by default it is empty) */
214BlockDriverState *bdrv_new(const char *device_name)
bellardfc01f7e2003-06-30 10:03:06 +0000215{
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100216 BlockDriverState *bs;
bellardb3380822004-03-14 21:38:54 +0000217
Anthony Liguori7267c092011-08-20 22:09:37 -0500218 bs = g_malloc0(sizeof(BlockDriverState));
bellardb3380822004-03-14 21:38:54 +0000219 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellardea2384d2004-08-01 21:59:26 +0000220 if (device_name[0] != '\0') {
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100221 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellardea2384d2004-08-01 21:59:26 +0000222 }
bellardb3380822004-03-14 21:38:54 +0000223 return bs;
224}
225
bellardea2384d2004-08-01 21:59:26 +0000226BlockDriver *bdrv_find_format(const char *format_name)
227{
228 BlockDriver *drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100229 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
230 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000231 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100232 }
bellardea2384d2004-08-01 21:59:26 +0000233 }
234 return NULL;
235}
236
Markus Armbrustereb852012009-10-27 18:41:44 +0100237static int bdrv_is_whitelisted(BlockDriver *drv)
238{
239 static const char *whitelist[] = {
240 CONFIG_BDRV_WHITELIST
241 };
242 const char **p;
243
244 if (!whitelist[0])
245 return 1; /* no whitelist, anything goes */
246
247 for (p = whitelist; *p; p++) {
248 if (!strcmp(drv->format_name, *p)) {
249 return 1;
250 }
251 }
252 return 0;
253}
254
255BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
256{
257 BlockDriver *drv = bdrv_find_format(format_name);
258 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
259}
260
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200261int bdrv_create(BlockDriver *drv, const char* filename,
262 QEMUOptionParameter *options)
bellardea2384d2004-08-01 21:59:26 +0000263{
264 if (!drv->bdrv_create)
265 return -ENOTSUP;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200266
267 return drv->bdrv_create(filename, options);
bellardea2384d2004-08-01 21:59:26 +0000268}
269
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200270int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
271{
272 BlockDriver *drv;
273
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900274 drv = bdrv_find_protocol(filename);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200275 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000276 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200277 }
278
279 return bdrv_create(drv, filename, options);
280}
281
bellardd5249392004-08-03 21:14:23 +0000282#ifdef _WIN32
bellard95389c82005-12-18 18:28:15 +0000283void get_tmp_filename(char *filename, int size)
bellardd5249392004-08-03 21:14:23 +0000284{
bellard3b9f94e2007-01-07 17:27:07 +0000285 char temp_dir[MAX_PATH];
ths3b46e622007-09-17 08:09:54 +0000286
bellard3b9f94e2007-01-07 17:27:07 +0000287 GetTempPath(MAX_PATH, temp_dir);
288 GetTempFileName(temp_dir, "qem", 0, filename);
bellardd5249392004-08-03 21:14:23 +0000289}
290#else
bellard95389c82005-12-18 18:28:15 +0000291void get_tmp_filename(char *filename, int size)
bellardea2384d2004-08-01 21:59:26 +0000292{
293 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000294 const char *tmpdir;
bellardd5249392004-08-03 21:14:23 +0000295 /* XXX: race condition possible */
aurel320badc1e2008-03-10 00:05:34 +0000296 tmpdir = getenv("TMPDIR");
297 if (!tmpdir)
298 tmpdir = "/tmp";
299 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
bellardea2384d2004-08-01 21:59:26 +0000300 fd = mkstemp(filename);
301 close(fd);
302}
bellardd5249392004-08-03 21:14:23 +0000303#endif
bellardea2384d2004-08-01 21:59:26 +0000304
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200305/*
306 * Detect host devices. By convention, /dev/cdrom[N] is always
307 * recognized as a host CDROM.
308 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200309static BlockDriver *find_hdev_driver(const char *filename)
310{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200311 int score_max = 0, score;
312 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200313
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100314 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200315 if (d->bdrv_probe_device) {
316 score = d->bdrv_probe_device(filename);
317 if (score > score_max) {
318 score_max = score;
319 drv = d;
320 }
321 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200322 }
323
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200324 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200325}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200326
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900327BlockDriver *bdrv_find_protocol(const char *filename)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200328{
329 BlockDriver *drv1;
330 char protocol[128];
331 int len;
332 const char *p;
333
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200334 /* TODO Drivers without bdrv_file_open must be specified explicitly */
335
Christoph Hellwig39508e72010-06-23 12:25:17 +0200336 /*
337 * XXX(hch): we really should not let host device detection
338 * override an explicit protocol specification, but moving this
339 * later breaks access to device names with colons in them.
340 * Thanks to the brain-dead persistent naming schemes on udev-
341 * based Linux systems those actually are quite common.
342 */
343 drv1 = find_hdev_driver(filename);
344 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200345 return drv1;
346 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200347
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000348 if (!path_has_protocol(filename)) {
Christoph Hellwig39508e72010-06-23 12:25:17 +0200349 return bdrv_find_format("file");
350 }
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000351 p = strchr(filename, ':');
352 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200353 len = p - filename;
354 if (len > sizeof(protocol) - 1)
355 len = sizeof(protocol) - 1;
356 memcpy(protocol, filename, len);
357 protocol[len] = '\0';
358 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
359 if (drv1->protocol_name &&
360 !strcmp(drv1->protocol_name, protocol)) {
361 return drv1;
362 }
363 }
364 return NULL;
365}
366
Stefan Weilc98ac352010-07-21 21:51:51 +0200367static int find_image_format(const char *filename, BlockDriver **pdrv)
bellardea2384d2004-08-01 21:59:26 +0000368{
bellard83f64092006-08-01 16:21:11 +0000369 int ret, score, score_max;
bellardea2384d2004-08-01 21:59:26 +0000370 BlockDriver *drv1, *drv;
bellard83f64092006-08-01 16:21:11 +0000371 uint8_t buf[2048];
372 BlockDriverState *bs;
ths3b46e622007-09-17 08:09:54 +0000373
Naphtali Spreif5edb012010-01-17 16:48:13 +0200374 ret = bdrv_file_open(&bs, filename, 0);
Stefan Weilc98ac352010-07-21 21:51:51 +0200375 if (ret < 0) {
376 *pdrv = NULL;
377 return ret;
378 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700379
Kevin Wolf08a00552010-06-01 18:37:31 +0200380 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
381 if (bs->sg || !bdrv_is_inserted(bs)) {
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700382 bdrv_delete(bs);
Stefan Weilc98ac352010-07-21 21:51:51 +0200383 drv = bdrv_find_format("raw");
384 if (!drv) {
385 ret = -ENOENT;
386 }
387 *pdrv = drv;
388 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700389 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700390
bellard83f64092006-08-01 16:21:11 +0000391 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
392 bdrv_delete(bs);
393 if (ret < 0) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200394 *pdrv = NULL;
395 return ret;
bellard83f64092006-08-01 16:21:11 +0000396 }
397
bellardea2384d2004-08-01 21:59:26 +0000398 score_max = 0;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200399 drv = NULL;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100400 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard83f64092006-08-01 16:21:11 +0000401 if (drv1->bdrv_probe) {
402 score = drv1->bdrv_probe(buf, ret, filename);
403 if (score > score_max) {
404 score_max = score;
405 drv = drv1;
406 }
bellardea2384d2004-08-01 21:59:26 +0000407 }
408 }
Stefan Weilc98ac352010-07-21 21:51:51 +0200409 if (!drv) {
410 ret = -ENOENT;
411 }
412 *pdrv = drv;
413 return ret;
bellardea2384d2004-08-01 21:59:26 +0000414}
415
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100416/**
417 * Set the current 'total_sectors' value
418 */
419static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
420{
421 BlockDriver *drv = bs->drv;
422
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700423 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
424 if (bs->sg)
425 return 0;
426
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100427 /* query actual device if possible, otherwise just trust the hint */
428 if (drv->bdrv_getlength) {
429 int64_t length = drv->bdrv_getlength(bs);
430 if (length < 0) {
431 return length;
432 }
433 hint = length >> BDRV_SECTOR_BITS;
434 }
435
436 bs->total_sectors = hint;
437 return 0;
438}
439
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100440/**
441 * Set open flags for a given cache mode
442 *
443 * Return 0 on success, -1 if the cache mode was invalid.
444 */
445int bdrv_parse_cache_flags(const char *mode, int *flags)
446{
447 *flags &= ~BDRV_O_CACHE_MASK;
448
449 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
450 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
451 } else if (!strcmp(mode, "writeback")) {
452 *flags |= BDRV_O_CACHE_WB;
453 } else if (!strcmp(mode, "unsafe")) {
454 *flags |= BDRV_O_CACHE_WB;
455 *flags |= BDRV_O_NO_FLUSH;
456 } else if (!strcmp(mode, "writethrough")) {
457 /* this is the default */
458 } else {
459 return -1;
460 }
461
462 return 0;
463}
464
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200465/*
Kevin Wolf57915332010-04-14 15:24:50 +0200466 * Common part for opening disk images and files
467 */
468static int bdrv_open_common(BlockDriverState *bs, const char *filename,
469 int flags, BlockDriver *drv)
470{
471 int ret, open_flags;
472
473 assert(drv != NULL);
474
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200475 bs->file = NULL;
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100476 bs->total_sectors = 0;
Kevin Wolf57915332010-04-14 15:24:50 +0200477 bs->encrypted = 0;
478 bs->valid_key = 0;
479 bs->open_flags = flags;
480 /* buffer_alignment defaulted to 512, drivers can change this value */
481 bs->buffer_alignment = 512;
482
483 pstrcpy(bs->filename, sizeof(bs->filename), filename);
484
485 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
486 return -ENOTSUP;
487 }
488
489 bs->drv = drv;
Anthony Liguori7267c092011-08-20 22:09:37 -0500490 bs->opaque = g_malloc0(drv->instance_size);
Kevin Wolf57915332010-04-14 15:24:50 +0200491
Christoph Hellwiga6599792011-05-17 18:04:06 +0200492 if (flags & BDRV_O_CACHE_WB)
Kevin Wolf57915332010-04-14 15:24:50 +0200493 bs->enable_write_cache = 1;
494
495 /*
496 * Clear flags that are internal to the block layer before opening the
497 * image.
498 */
499 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
500
501 /*
Stefan Weilebabb672011-04-26 10:29:36 +0200502 * Snapshots should be writable.
Kevin Wolf57915332010-04-14 15:24:50 +0200503 */
504 if (bs->is_temporary) {
505 open_flags |= BDRV_O_RDWR;
506 }
507
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200508 /* Open the image, either directly or using a protocol */
509 if (drv->bdrv_file_open) {
510 ret = drv->bdrv_file_open(bs, filename, open_flags);
511 } else {
512 ret = bdrv_file_open(&bs->file, filename, open_flags);
513 if (ret >= 0) {
514 ret = drv->bdrv_open(bs, open_flags);
515 }
516 }
517
Kevin Wolf57915332010-04-14 15:24:50 +0200518 if (ret < 0) {
519 goto free_and_fail;
520 }
521
522 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100523
524 ret = refresh_total_sectors(bs, bs->total_sectors);
525 if (ret < 0) {
526 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200527 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100528
Kevin Wolf57915332010-04-14 15:24:50 +0200529#ifndef _WIN32
530 if (bs->is_temporary) {
531 unlink(filename);
532 }
533#endif
534 return 0;
535
536free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200537 if (bs->file) {
538 bdrv_delete(bs->file);
539 bs->file = NULL;
540 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500541 g_free(bs->opaque);
Kevin Wolf57915332010-04-14 15:24:50 +0200542 bs->opaque = NULL;
543 bs->drv = NULL;
544 return ret;
545}
546
547/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200548 * Opens a file using a protocol (file, host_device, nbd, ...)
549 */
bellard83f64092006-08-01 16:21:11 +0000550int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000551{
bellard83f64092006-08-01 16:21:11 +0000552 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200553 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000554 int ret;
555
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900556 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200557 if (!drv) {
558 return -ENOENT;
559 }
560
bellard83f64092006-08-01 16:21:11 +0000561 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200562 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000563 if (ret < 0) {
564 bdrv_delete(bs);
565 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000566 }
aliguori71d07702009-03-03 17:37:16 +0000567 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000568 *pbs = bs;
569 return 0;
bellardea2384d2004-08-01 21:59:26 +0000570}
bellardfc01f7e2003-06-30 10:03:06 +0000571
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200572/*
573 * Opens a disk image (raw, qcow2, vmdk, ...)
574 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200575int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
576 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000577{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200578 int ret;
bellard712e7872005-04-28 21:09:32 +0000579
bellard83f64092006-08-01 16:21:11 +0000580 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000581 BlockDriverState *bs1;
582 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000583 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200584 BlockDriver *bdrv_qcow2;
585 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200586 char tmp_filename[PATH_MAX];
587 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000588
bellardea2384d2004-08-01 21:59:26 +0000589 /* if snapshot, we create a temporary backing file and open it
590 instead of opening 'filename' directly */
591
592 /* if there is a backing file, use it */
593 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200594 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000595 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000596 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000597 return ret;
bellardea2384d2004-08-01 21:59:26 +0000598 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200599 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000600
601 if (bs1->drv && bs1->drv->protocol_name)
602 is_protocol = 1;
603
bellardea2384d2004-08-01 21:59:26 +0000604 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000605
bellardea2384d2004-08-01 21:59:26 +0000606 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
aliguori7c96d462008-09-12 17:54:13 +0000607
608 /* Real path is meaningless for protocols */
609 if (is_protocol)
610 snprintf(backing_filename, sizeof(backing_filename),
611 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000612 else if (!realpath(filename, backing_filename))
613 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000614
Kevin Wolf91a073a2009-05-27 14:48:06 +0200615 bdrv_qcow2 = bdrv_find_format("qcow2");
616 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
617
Jes Sorensen3e829902010-05-27 16:20:30 +0200618 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200619 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
620 if (drv) {
621 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
622 drv->format_name);
623 }
624
625 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200626 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000627 if (ret < 0) {
628 return ret;
bellardea2384d2004-08-01 21:59:26 +0000629 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200630
bellardea2384d2004-08-01 21:59:26 +0000631 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200632 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000633 bs->is_temporary = 1;
634 }
bellard712e7872005-04-28 21:09:32 +0000635
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200636 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200637 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200638 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000639 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100640
aliguori51d7c002009-03-05 23:00:29 +0000641 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000642 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000643 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200644
645 /* Open the image */
646 ret = bdrv_open_common(bs, filename, flags, drv);
647 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100648 goto unlink_and_fail;
649 }
650
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200651 /* If there is a backing file, use it */
652 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
653 char backing_filename[PATH_MAX];
654 int back_flags;
655 BlockDriver *back_drv = NULL;
656
657 bs->backing_hd = bdrv_new("");
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000658
659 if (path_has_protocol(bs->backing_file)) {
660 pstrcpy(backing_filename, sizeof(backing_filename),
661 bs->backing_file);
662 } else {
663 path_combine(backing_filename, sizeof(backing_filename),
664 filename, bs->backing_file);
665 }
666
667 if (bs->backing_format[0] != '\0') {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200668 back_drv = bdrv_find_format(bs->backing_format);
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000669 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200670
671 /* backing files always opened read-only */
672 back_flags =
673 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
674
675 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
676 if (ret < 0) {
677 bdrv_close(bs);
678 return ret;
679 }
680 if (bs->is_temporary) {
681 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
682 } else {
683 /* base image inherits from "parent" */
684 bs->backing_hd->keep_read_only = bs->keep_read_only;
685 }
686 }
687
688 if (!bdrv_key_required(bs)) {
689 /* call the change callback */
690 bs->media_changed = 1;
691 if (bs->change_cb)
Christoph Hellwigdb97ee62011-01-24 13:32:41 +0100692 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200693 }
694
695 return 0;
696
697unlink_and_fail:
698 if (bs->is_temporary) {
699 unlink(filename);
700 }
701 return ret;
702}
703
bellardfc01f7e2003-06-30 10:03:06 +0000704void bdrv_close(BlockDriverState *bs)
705{
bellard19cb3732006-08-19 11:45:59 +0000706 if (bs->drv) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200707 if (bs == bs_snapshots) {
708 bs_snapshots = NULL;
709 }
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100710 if (bs->backing_hd) {
bellardea2384d2004-08-01 21:59:26 +0000711 bdrv_delete(bs->backing_hd);
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100712 bs->backing_hd = NULL;
713 }
bellardea2384d2004-08-01 21:59:26 +0000714 bs->drv->bdrv_close(bs);
Anthony Liguori7267c092011-08-20 22:09:37 -0500715 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +0000716#ifdef _WIN32
717 if (bs->is_temporary) {
718 unlink(bs->filename);
719 }
bellard67b915a2004-03-31 23:37:16 +0000720#endif
bellardea2384d2004-08-01 21:59:26 +0000721 bs->opaque = NULL;
722 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +0000723
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200724 if (bs->file != NULL) {
725 bdrv_close(bs->file);
726 }
727
bellardb3380822004-03-14 21:38:54 +0000728 /* call the change callback */
bellard19cb3732006-08-19 11:45:59 +0000729 bs->media_changed = 1;
bellardb3380822004-03-14 21:38:54 +0000730 if (bs->change_cb)
Christoph Hellwigdb97ee62011-01-24 13:32:41 +0100731 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
bellardb3380822004-03-14 21:38:54 +0000732 }
733}
734
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +0900735void bdrv_close_all(void)
736{
737 BlockDriverState *bs;
738
739 QTAILQ_FOREACH(bs, &bdrv_states, list) {
740 bdrv_close(bs);
741 }
742}
743
Ryan Harperd22b2f42011-03-29 20:51:47 -0500744/* make a BlockDriverState anonymous by removing from bdrv_state list.
745 Also, NULL terminate the device_name to prevent double remove */
746void bdrv_make_anon(BlockDriverState *bs)
747{
748 if (bs->device_name[0] != '\0') {
749 QTAILQ_REMOVE(&bdrv_states, bs, list);
750 }
751 bs->device_name[0] = '\0';
752}
753
bellardb3380822004-03-14 21:38:54 +0000754void bdrv_delete(BlockDriverState *bs)
755{
Markus Armbruster18846de2010-06-29 16:58:30 +0200756 assert(!bs->peer);
757
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100758 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -0500759 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +0000760
bellardb3380822004-03-14 21:38:54 +0000761 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200762 if (bs->file != NULL) {
763 bdrv_delete(bs->file);
764 }
765
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200766 assert(bs != bs_snapshots);
Anthony Liguori7267c092011-08-20 22:09:37 -0500767 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +0000768}
769
Markus Armbruster18846de2010-06-29 16:58:30 +0200770int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
771{
772 if (bs->peer) {
773 return -EBUSY;
774 }
775 bs->peer = qdev;
776 return 0;
777}
778
779void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
780{
781 assert(bs->peer == qdev);
782 bs->peer = NULL;
Markus Armbrustera19712b2011-07-20 18:23:36 +0200783 bs->change_cb = NULL;
784 bs->change_opaque = NULL;
Markus Armbruster18846de2010-06-29 16:58:30 +0200785}
786
787DeviceState *bdrv_get_attached(BlockDriverState *bs)
788{
789 return bs->peer;
790}
791
aliguorie97fc192009-04-21 23:11:50 +0000792/*
793 * Run consistency checks on an image
794 *
Kevin Wolfe076f332010-06-29 11:43:13 +0200795 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +0200796 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +0200797 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +0000798 */
Kevin Wolfe076f332010-06-29 11:43:13 +0200799int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
aliguorie97fc192009-04-21 23:11:50 +0000800{
801 if (bs->drv->bdrv_check == NULL) {
802 return -ENOTSUP;
803 }
804
Kevin Wolfe076f332010-06-29 11:43:13 +0200805 memset(res, 0, sizeof(*res));
Kevin Wolf9ac228e2010-06-29 12:37:54 +0200806 return bs->drv->bdrv_check(bs, res);
aliguorie97fc192009-04-21 23:11:50 +0000807}
808
Kevin Wolf8a426612010-07-16 17:17:01 +0200809#define COMMIT_BUF_SECTORS 2048
810
bellard33e39632003-07-06 17:15:21 +0000811/* commit COW file into the raw image */
812int bdrv_commit(BlockDriverState *bs)
813{
bellard19cb3732006-08-19 11:45:59 +0000814 BlockDriver *drv = bs->drv;
Kevin Wolfee181192010-08-05 13:05:22 +0200815 BlockDriver *backing_drv;
Kevin Wolf8a426612010-07-16 17:17:01 +0200816 int64_t sector, total_sectors;
817 int n, ro, open_flags;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200818 int ret = 0, rw_ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +0200819 uint8_t *buf;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200820 char filename[1024];
821 BlockDriverState *bs_rw, *bs_ro;
bellard33e39632003-07-06 17:15:21 +0000822
bellard19cb3732006-08-19 11:45:59 +0000823 if (!drv)
824 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200825
826 if (!bs->backing_hd) {
827 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +0000828 }
829
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200830 if (bs->backing_hd->keep_read_only) {
831 return -EACCES;
832 }
Kevin Wolfee181192010-08-05 13:05:22 +0200833
834 backing_drv = bs->backing_hd->drv;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200835 ro = bs->backing_hd->read_only;
836 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
837 open_flags = bs->backing_hd->open_flags;
838
839 if (ro) {
840 /* re-open as RW */
841 bdrv_delete(bs->backing_hd);
842 bs->backing_hd = NULL;
843 bs_rw = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200844 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
845 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200846 if (rw_ret < 0) {
847 bdrv_delete(bs_rw);
848 /* try to re-open read-only */
849 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200850 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
851 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200852 if (ret < 0) {
853 bdrv_delete(bs_ro);
854 /* drive not functional anymore */
855 bs->drv = NULL;
856 return ret;
857 }
858 bs->backing_hd = bs_ro;
859 return rw_ret;
860 }
861 bs->backing_hd = bs_rw;
bellard33e39632003-07-06 17:15:21 +0000862 }
bellardea2384d2004-08-01 21:59:26 +0000863
Jan Kiszka6ea44302009-11-30 18:21:19 +0100864 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Anthony Liguori7267c092011-08-20 22:09:37 -0500865 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +0000866
Kevin Wolf8a426612010-07-16 17:17:01 +0200867 for (sector = 0; sector < total_sectors; sector += n) {
868 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
869
870 if (bdrv_read(bs, sector, buf, n) != 0) {
871 ret = -EIO;
872 goto ro_cleanup;
873 }
874
875 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
876 ret = -EIO;
877 goto ro_cleanup;
878 }
bellardea2384d2004-08-01 21:59:26 +0000879 }
880 }
bellard95389c82005-12-18 18:28:15 +0000881
Christoph Hellwig1d449522010-01-17 12:32:30 +0100882 if (drv->bdrv_make_empty) {
883 ret = drv->bdrv_make_empty(bs);
884 bdrv_flush(bs);
885 }
bellard95389c82005-12-18 18:28:15 +0000886
Christoph Hellwig3f5075a2010-01-12 13:49:23 +0100887 /*
888 * Make sure all data we wrote to the backing device is actually
889 * stable on disk.
890 */
891 if (bs->backing_hd)
892 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200893
894ro_cleanup:
Anthony Liguori7267c092011-08-20 22:09:37 -0500895 g_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200896
897 if (ro) {
898 /* re-open as RO */
899 bdrv_delete(bs->backing_hd);
900 bs->backing_hd = NULL;
901 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200902 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
903 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200904 if (ret < 0) {
905 bdrv_delete(bs_ro);
906 /* drive not functional anymore */
907 bs->drv = NULL;
908 return ret;
909 }
910 bs->backing_hd = bs_ro;
911 bs->backing_hd->keep_read_only = 0;
912 }
913
Christoph Hellwig1d449522010-01-17 12:32:30 +0100914 return ret;
bellard33e39632003-07-06 17:15:21 +0000915}
916
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +0200917void bdrv_commit_all(void)
918{
919 BlockDriverState *bs;
920
921 QTAILQ_FOREACH(bs, &bdrv_states, list) {
922 bdrv_commit(bs);
923 }
924}
925
Kevin Wolf756e6732010-01-12 12:55:17 +0100926/*
927 * Return values:
928 * 0 - success
929 * -EINVAL - backing format specified, but no file
930 * -ENOSPC - can't update the backing file because no space is left in the
931 * image file header
932 * -ENOTSUP - format driver doesn't support changing the backing file
933 */
934int bdrv_change_backing_file(BlockDriverState *bs,
935 const char *backing_file, const char *backing_fmt)
936{
937 BlockDriver *drv = bs->drv;
938
939 if (drv->bdrv_change_backing_file != NULL) {
940 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
941 } else {
942 return -ENOTSUP;
943 }
944}
945
aliguori71d07702009-03-03 17:37:16 +0000946static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
947 size_t size)
948{
949 int64_t len;
950
951 if (!bdrv_is_inserted(bs))
952 return -ENOMEDIUM;
953
954 if (bs->growable)
955 return 0;
956
957 len = bdrv_getlength(bs);
958
Kevin Wolffbb7b4e2009-05-08 14:47:24 +0200959 if (offset < 0)
960 return -EIO;
961
962 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +0000963 return -EIO;
964
965 return 0;
966}
967
968static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
969 int nb_sectors)
970{
Jes Sorenseneb5a3162010-05-27 16:20:31 +0200971 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
972 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +0000973}
974
Kevin Wolfe7a8a782011-07-15 16:05:00 +0200975static inline bool bdrv_has_async_rw(BlockDriver *drv)
976{
977 return drv->bdrv_co_readv != bdrv_co_readv_em
978 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
979}
980
981static inline bool bdrv_has_async_flush(BlockDriver *drv)
982{
983 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
984}
985
bellard19cb3732006-08-19 11:45:59 +0000986/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +0000987int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +0000988 uint8_t *buf, int nb_sectors)
989{
bellardea2384d2004-08-01 21:59:26 +0000990 BlockDriver *drv = bs->drv;
991
bellard19cb3732006-08-19 11:45:59 +0000992 if (!drv)
993 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +0200994
995 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
996 QEMUIOVector qiov;
997 struct iovec iov = {
998 .iov_base = (void *)buf,
999 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1000 };
1001
1002 qemu_iovec_init_external(&qiov, &iov, 1);
1003 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1004 }
1005
aliguori71d07702009-03-03 17:37:16 +00001006 if (bdrv_check_request(bs, sector_num, nb_sectors))
1007 return -EIO;
bellardb3380822004-03-14 21:38:54 +00001008
aliguorieda578e2009-03-12 19:57:16 +00001009 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
bellardfc01f7e2003-06-30 10:03:06 +00001010}
1011
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001012static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001013 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001014{
1015 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001016 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001017
Jan Kiszka6ea44302009-11-30 18:21:19 +01001018 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001019 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001020
1021 for (; start <= end; start++) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01001022 idx = start / (sizeof(unsigned long) * 8);
1023 bit = start % (sizeof(unsigned long) * 8);
1024 val = bs->dirty_bitmap[idx];
1025 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001026 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001027 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001028 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +02001029 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001030 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001031 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001032 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001033 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +02001034 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001035 }
1036 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001037 }
1038}
1039
ths5fafdf22007-09-16 21:08:06 +00001040/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +00001041 -EIO generic I/O error (may happen for all errors)
1042 -ENOMEDIUM No media inserted.
1043 -EINVAL Invalid sector number or nb_sectors
1044 -EACCES Trying to write a read-only device
1045*/
ths5fafdf22007-09-16 21:08:06 +00001046int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001047 const uint8_t *buf, int nb_sectors)
1048{
bellard83f64092006-08-01 16:21:11 +00001049 BlockDriver *drv = bs->drv;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001050
bellard19cb3732006-08-19 11:45:59 +00001051 if (!bs->drv)
1052 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001053
1054 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1055 QEMUIOVector qiov;
1056 struct iovec iov = {
1057 .iov_base = (void *)buf,
1058 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1059 };
1060
1061 qemu_iovec_init_external(&qiov, &iov, 1);
1062 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1063 }
1064
bellard0849bf02003-06-30 23:17:31 +00001065 if (bs->read_only)
bellard19cb3732006-08-19 11:45:59 +00001066 return -EACCES;
aliguori71d07702009-03-03 17:37:16 +00001067 if (bdrv_check_request(bs, sector_num, nb_sectors))
1068 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001069
Jan Kiszkac6d22832009-11-30 18:21:20 +01001070 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001071 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1072 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001073
Kevin Wolf294cc352010-04-28 14:34:01 +02001074 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1075 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1076 }
1077
aliguori42fb2802009-01-15 20:43:39 +00001078 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
bellard83f64092006-08-01 16:21:11 +00001079}
1080
aliguorieda578e2009-03-12 19:57:16 +00001081int bdrv_pread(BlockDriverState *bs, int64_t offset,
1082 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001083{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001084 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001085 int len, nb_sectors, count;
1086 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001087 int ret;
bellard83f64092006-08-01 16:21:11 +00001088
1089 count = count1;
1090 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001091 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001092 if (len > count)
1093 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001094 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001095 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001096 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1097 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001098 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00001099 count -= len;
1100 if (count == 0)
1101 return count1;
1102 sector_num++;
1103 buf += len;
1104 }
1105
1106 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001107 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001108 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001109 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1110 return ret;
bellard83f64092006-08-01 16:21:11 +00001111 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001112 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001113 buf += len;
1114 count -= len;
1115 }
1116
1117 /* add data from the last sector */
1118 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001119 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1120 return ret;
bellard83f64092006-08-01 16:21:11 +00001121 memcpy(buf, tmp_buf, count);
1122 }
1123 return count1;
1124}
1125
aliguorieda578e2009-03-12 19:57:16 +00001126int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1127 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001128{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001129 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001130 int len, nb_sectors, count;
1131 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001132 int ret;
bellard83f64092006-08-01 16:21:11 +00001133
1134 count = count1;
1135 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001136 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001137 if (len > count)
1138 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001139 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001140 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001141 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1142 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001143 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001144 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1145 return ret;
bellard83f64092006-08-01 16:21:11 +00001146 count -= len;
1147 if (count == 0)
1148 return count1;
1149 sector_num++;
1150 buf += len;
1151 }
1152
1153 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001154 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001155 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001156 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1157 return ret;
bellard83f64092006-08-01 16:21:11 +00001158 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001159 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001160 buf += len;
1161 count -= len;
1162 }
1163
1164 /* add data from the last sector */
1165 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001166 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1167 return ret;
bellard83f64092006-08-01 16:21:11 +00001168 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001169 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1170 return ret;
bellard83f64092006-08-01 16:21:11 +00001171 }
1172 return count1;
1173}
bellard83f64092006-08-01 16:21:11 +00001174
Kevin Wolff08145f2010-06-16 16:38:15 +02001175/*
1176 * Writes to the file and ensures that no writes are reordered across this
1177 * request (acts as a barrier)
1178 *
1179 * Returns 0 on success, -errno in error cases.
1180 */
1181int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1182 const void *buf, int count)
1183{
1184 int ret;
1185
1186 ret = bdrv_pwrite(bs, offset, buf, count);
1187 if (ret < 0) {
1188 return ret;
1189 }
1190
1191 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1192 if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1193 bdrv_flush(bs);
1194 }
1195
1196 return 0;
1197}
1198
Kevin Wolfda1fa912011-07-14 17:27:13 +02001199int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1200 int nb_sectors, QEMUIOVector *qiov)
1201{
1202 BlockDriver *drv = bs->drv;
1203
1204 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1205
1206 if (!drv) {
1207 return -ENOMEDIUM;
1208 }
1209 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1210 return -EIO;
1211 }
1212
1213 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1214}
1215
1216int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1217 int nb_sectors, QEMUIOVector *qiov)
1218{
1219 BlockDriver *drv = bs->drv;
1220
1221 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1222
1223 if (!bs->drv) {
1224 return -ENOMEDIUM;
1225 }
1226 if (bs->read_only) {
1227 return -EACCES;
1228 }
1229 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1230 return -EIO;
1231 }
1232
1233 if (bs->dirty_bitmap) {
1234 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1235 }
1236
1237 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1238 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1239 }
1240
1241 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1242}
1243
bellard83f64092006-08-01 16:21:11 +00001244/**
bellard83f64092006-08-01 16:21:11 +00001245 * Truncate file to 'offset' bytes (needed only for file protocols)
1246 */
1247int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1248{
1249 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001250 int ret;
bellard83f64092006-08-01 16:21:11 +00001251 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001252 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00001253 if (!drv->bdrv_truncate)
1254 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02001255 if (bs->read_only)
1256 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02001257 if (bdrv_in_use(bs))
1258 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001259 ret = drv->bdrv_truncate(bs, offset);
1260 if (ret == 0) {
1261 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Christoph Hellwigdb97ee62011-01-24 13:32:41 +01001262 if (bs->change_cb) {
1263 bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1264 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001265 }
1266 return ret;
bellard83f64092006-08-01 16:21:11 +00001267}
1268
1269/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08001270 * Length of a allocated file in bytes. Sparse files are counted by actual
1271 * allocated space. Return < 0 if error or unknown.
1272 */
1273int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1274{
1275 BlockDriver *drv = bs->drv;
1276 if (!drv) {
1277 return -ENOMEDIUM;
1278 }
1279 if (drv->bdrv_get_allocated_file_size) {
1280 return drv->bdrv_get_allocated_file_size(bs);
1281 }
1282 if (bs->file) {
1283 return bdrv_get_allocated_file_size(bs->file);
1284 }
1285 return -ENOTSUP;
1286}
1287
1288/**
bellard83f64092006-08-01 16:21:11 +00001289 * Length of a file in bytes. Return < 0 if error or unknown.
1290 */
1291int64_t bdrv_getlength(BlockDriverState *bs)
1292{
1293 BlockDriver *drv = bs->drv;
1294 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001295 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001296
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001297 if (bs->growable || bs->removable) {
1298 if (drv->bdrv_getlength) {
1299 return drv->bdrv_getlength(bs);
1300 }
bellard83f64092006-08-01 16:21:11 +00001301 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001302 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00001303}
1304
bellard19cb3732006-08-19 11:45:59 +00001305/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00001306void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00001307{
bellard19cb3732006-08-19 11:45:59 +00001308 int64_t length;
1309 length = bdrv_getlength(bs);
1310 if (length < 0)
1311 length = 0;
1312 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01001313 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00001314 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00001315}
bellardcf989512004-02-16 21:56:36 +00001316
aliguorif3d54fc2008-11-25 21:50:24 +00001317struct partition {
1318 uint8_t boot_ind; /* 0x80 - active */
1319 uint8_t head; /* starting head */
1320 uint8_t sector; /* starting sector */
1321 uint8_t cyl; /* starting cylinder */
1322 uint8_t sys_ind; /* What partition type */
1323 uint8_t end_head; /* end head */
1324 uint8_t end_sector; /* end sector */
1325 uint8_t end_cyl; /* end cylinder */
1326 uint32_t start_sect; /* starting sector counting from 0 */
1327 uint32_t nr_sects; /* nr of sectors in partition */
1328} __attribute__((packed));
1329
1330/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1331static int guess_disk_lchs(BlockDriverState *bs,
1332 int *pcylinders, int *pheads, int *psectors)
1333{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001334 uint8_t buf[BDRV_SECTOR_SIZE];
aliguorif3d54fc2008-11-25 21:50:24 +00001335 int ret, i, heads, sectors, cylinders;
1336 struct partition *p;
1337 uint32_t nr_sects;
blueswir1a38131b2008-12-05 17:56:40 +00001338 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001339
1340 bdrv_get_geometry(bs, &nb_sectors);
1341
1342 ret = bdrv_read(bs, 0, buf, 1);
1343 if (ret < 0)
1344 return -1;
1345 /* test msdos magic */
1346 if (buf[510] != 0x55 || buf[511] != 0xaa)
1347 return -1;
1348 for(i = 0; i < 4; i++) {
1349 p = ((struct partition *)(buf + 0x1be)) + i;
1350 nr_sects = le32_to_cpu(p->nr_sects);
1351 if (nr_sects && p->end_head) {
1352 /* We make the assumption that the partition terminates on
1353 a cylinder boundary */
1354 heads = p->end_head + 1;
1355 sectors = p->end_sector & 63;
1356 if (sectors == 0)
1357 continue;
1358 cylinders = nb_sectors / (heads * sectors);
1359 if (cylinders < 1 || cylinders > 16383)
1360 continue;
1361 *pheads = heads;
1362 *psectors = sectors;
1363 *pcylinders = cylinders;
1364#if 0
1365 printf("guessed geometry: LCHS=%d %d %d\n",
1366 cylinders, heads, sectors);
1367#endif
1368 return 0;
1369 }
1370 }
1371 return -1;
1372}
1373
1374void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1375{
1376 int translation, lba_detected = 0;
1377 int cylinders, heads, secs;
blueswir1a38131b2008-12-05 17:56:40 +00001378 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001379
1380 /* if a geometry hint is available, use it */
1381 bdrv_get_geometry(bs, &nb_sectors);
1382 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1383 translation = bdrv_get_translation_hint(bs);
1384 if (cylinders != 0) {
1385 *pcyls = cylinders;
1386 *pheads = heads;
1387 *psecs = secs;
1388 } else {
1389 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1390 if (heads > 16) {
1391 /* if heads > 16, it means that a BIOS LBA
1392 translation was active, so the default
1393 hardware geometry is OK */
1394 lba_detected = 1;
1395 goto default_geometry;
1396 } else {
1397 *pcyls = cylinders;
1398 *pheads = heads;
1399 *psecs = secs;
1400 /* disable any translation to be in sync with
1401 the logical geometry */
1402 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1403 bdrv_set_translation_hint(bs,
1404 BIOS_ATA_TRANSLATION_NONE);
1405 }
1406 }
1407 } else {
1408 default_geometry:
1409 /* if no geometry, use a standard physical disk geometry */
1410 cylinders = nb_sectors / (16 * 63);
1411
1412 if (cylinders > 16383)
1413 cylinders = 16383;
1414 else if (cylinders < 2)
1415 cylinders = 2;
1416 *pcyls = cylinders;
1417 *pheads = 16;
1418 *psecs = 63;
1419 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1420 if ((*pcyls * *pheads) <= 131072) {
1421 bdrv_set_translation_hint(bs,
1422 BIOS_ATA_TRANSLATION_LARGE);
1423 } else {
1424 bdrv_set_translation_hint(bs,
1425 BIOS_ATA_TRANSLATION_LBA);
1426 }
1427 }
1428 }
1429 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1430 }
1431}
1432
ths5fafdf22007-09-16 21:08:06 +00001433void bdrv_set_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001434 int cyls, int heads, int secs)
1435{
1436 bs->cyls = cyls;
1437 bs->heads = heads;
1438 bs->secs = secs;
1439}
1440
bellard46d47672004-11-16 01:45:27 +00001441void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1442{
1443 bs->translation = translation;
1444}
1445
ths5fafdf22007-09-16 21:08:06 +00001446void bdrv_get_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001447 int *pcyls, int *pheads, int *psecs)
1448{
1449 *pcyls = bs->cyls;
1450 *pheads = bs->heads;
1451 *psecs = bs->secs;
1452}
1453
Blue Swirl5bbdbb42011-02-12 20:43:32 +00001454/* Recognize floppy formats */
1455typedef struct FDFormat {
1456 FDriveType drive;
1457 uint8_t last_sect;
1458 uint8_t max_track;
1459 uint8_t max_head;
1460} FDFormat;
1461
1462static const FDFormat fd_formats[] = {
1463 /* First entry is default format */
1464 /* 1.44 MB 3"1/2 floppy disks */
1465 { FDRIVE_DRV_144, 18, 80, 1, },
1466 { FDRIVE_DRV_144, 20, 80, 1, },
1467 { FDRIVE_DRV_144, 21, 80, 1, },
1468 { FDRIVE_DRV_144, 21, 82, 1, },
1469 { FDRIVE_DRV_144, 21, 83, 1, },
1470 { FDRIVE_DRV_144, 22, 80, 1, },
1471 { FDRIVE_DRV_144, 23, 80, 1, },
1472 { FDRIVE_DRV_144, 24, 80, 1, },
1473 /* 2.88 MB 3"1/2 floppy disks */
1474 { FDRIVE_DRV_288, 36, 80, 1, },
1475 { FDRIVE_DRV_288, 39, 80, 1, },
1476 { FDRIVE_DRV_288, 40, 80, 1, },
1477 { FDRIVE_DRV_288, 44, 80, 1, },
1478 { FDRIVE_DRV_288, 48, 80, 1, },
1479 /* 720 kB 3"1/2 floppy disks */
1480 { FDRIVE_DRV_144, 9, 80, 1, },
1481 { FDRIVE_DRV_144, 10, 80, 1, },
1482 { FDRIVE_DRV_144, 10, 82, 1, },
1483 { FDRIVE_DRV_144, 10, 83, 1, },
1484 { FDRIVE_DRV_144, 13, 80, 1, },
1485 { FDRIVE_DRV_144, 14, 80, 1, },
1486 /* 1.2 MB 5"1/4 floppy disks */
1487 { FDRIVE_DRV_120, 15, 80, 1, },
1488 { FDRIVE_DRV_120, 18, 80, 1, },
1489 { FDRIVE_DRV_120, 18, 82, 1, },
1490 { FDRIVE_DRV_120, 18, 83, 1, },
1491 { FDRIVE_DRV_120, 20, 80, 1, },
1492 /* 720 kB 5"1/4 floppy disks */
1493 { FDRIVE_DRV_120, 9, 80, 1, },
1494 { FDRIVE_DRV_120, 11, 80, 1, },
1495 /* 360 kB 5"1/4 floppy disks */
1496 { FDRIVE_DRV_120, 9, 40, 1, },
1497 { FDRIVE_DRV_120, 9, 40, 0, },
1498 { FDRIVE_DRV_120, 10, 41, 1, },
1499 { FDRIVE_DRV_120, 10, 42, 1, },
1500 /* 320 kB 5"1/4 floppy disks */
1501 { FDRIVE_DRV_120, 8, 40, 1, },
1502 { FDRIVE_DRV_120, 8, 40, 0, },
1503 /* 360 kB must match 5"1/4 better than 3"1/2... */
1504 { FDRIVE_DRV_144, 9, 80, 0, },
1505 /* end */
1506 { FDRIVE_DRV_NONE, -1, -1, 0, },
1507};
1508
1509void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1510 int *max_track, int *last_sect,
1511 FDriveType drive_in, FDriveType *drive)
1512{
1513 const FDFormat *parse;
1514 uint64_t nb_sectors, size;
1515 int i, first_match, match;
1516
1517 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1518 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1519 /* User defined disk */
1520 } else {
1521 bdrv_get_geometry(bs, &nb_sectors);
1522 match = -1;
1523 first_match = -1;
1524 for (i = 0; ; i++) {
1525 parse = &fd_formats[i];
1526 if (parse->drive == FDRIVE_DRV_NONE) {
1527 break;
1528 }
1529 if (drive_in == parse->drive ||
1530 drive_in == FDRIVE_DRV_NONE) {
1531 size = (parse->max_head + 1) * parse->max_track *
1532 parse->last_sect;
1533 if (nb_sectors == size) {
1534 match = i;
1535 break;
1536 }
1537 if (first_match == -1) {
1538 first_match = i;
1539 }
1540 }
1541 }
1542 if (match == -1) {
1543 if (first_match == -1) {
1544 match = 1;
1545 } else {
1546 match = first_match;
1547 }
1548 parse = &fd_formats[match];
1549 }
1550 *nb_heads = parse->max_head + 1;
1551 *max_track = parse->max_track;
1552 *last_sect = parse->last_sect;
1553 *drive = parse->drive;
1554 }
1555}
1556
bellard46d47672004-11-16 01:45:27 +00001557int bdrv_get_translation_hint(BlockDriverState *bs)
1558{
1559 return bs->translation;
1560}
1561
Markus Armbrusterabd7f682010-06-02 18:55:17 +02001562void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1563 BlockErrorAction on_write_error)
1564{
1565 bs->on_read_error = on_read_error;
1566 bs->on_write_error = on_write_error;
1567}
1568
1569BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1570{
1571 return is_read ? bs->on_read_error : bs->on_write_error;
1572}
1573
Markus Armbruster7d0d6952010-06-25 13:42:14 +02001574void bdrv_set_removable(BlockDriverState *bs, int removable)
1575{
1576 bs->removable = removable;
1577 if (removable && bs == bs_snapshots) {
1578 bs_snapshots = NULL;
1579 }
1580}
1581
bellardb3380822004-03-14 21:38:54 +00001582int bdrv_is_removable(BlockDriverState *bs)
1583{
1584 return bs->removable;
1585}
1586
1587int bdrv_is_read_only(BlockDriverState *bs)
1588{
1589 return bs->read_only;
1590}
1591
ths985a03b2007-12-24 16:10:43 +00001592int bdrv_is_sg(BlockDriverState *bs)
1593{
1594 return bs->sg;
1595}
1596
Christoph Hellwige900a7b2009-09-04 19:01:15 +02001597int bdrv_enable_write_cache(BlockDriverState *bs)
1598{
1599 return bs->enable_write_cache;
1600}
1601
bellard19cb3732006-08-19 11:45:59 +00001602/* XXX: no longer used */
ths5fafdf22007-09-16 21:08:06 +00001603void bdrv_set_change_cb(BlockDriverState *bs,
Christoph Hellwigdb97ee62011-01-24 13:32:41 +01001604 void (*change_cb)(void *opaque, int reason),
1605 void *opaque)
bellardb3380822004-03-14 21:38:54 +00001606{
1607 bs->change_cb = change_cb;
1608 bs->change_opaque = opaque;
1609}
1610
bellardea2384d2004-08-01 21:59:26 +00001611int bdrv_is_encrypted(BlockDriverState *bs)
1612{
1613 if (bs->backing_hd && bs->backing_hd->encrypted)
1614 return 1;
1615 return bs->encrypted;
1616}
1617
aliguoric0f4ce72009-03-05 23:01:01 +00001618int bdrv_key_required(BlockDriverState *bs)
1619{
1620 BlockDriverState *backing_hd = bs->backing_hd;
1621
1622 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1623 return 1;
1624 return (bs->encrypted && !bs->valid_key);
1625}
1626
bellardea2384d2004-08-01 21:59:26 +00001627int bdrv_set_key(BlockDriverState *bs, const char *key)
1628{
1629 int ret;
1630 if (bs->backing_hd && bs->backing_hd->encrypted) {
1631 ret = bdrv_set_key(bs->backing_hd, key);
1632 if (ret < 0)
1633 return ret;
1634 if (!bs->encrypted)
1635 return 0;
1636 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02001637 if (!bs->encrypted) {
1638 return -EINVAL;
1639 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1640 return -ENOMEDIUM;
1641 }
aliguoric0f4ce72009-03-05 23:01:01 +00001642 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00001643 if (ret < 0) {
1644 bs->valid_key = 0;
1645 } else if (!bs->valid_key) {
1646 bs->valid_key = 1;
1647 /* call the change callback now, we skipped it on open */
1648 bs->media_changed = 1;
1649 if (bs->change_cb)
Christoph Hellwigdb97ee62011-01-24 13:32:41 +01001650 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
aliguoribb5fc202009-03-05 23:01:15 +00001651 }
aliguoric0f4ce72009-03-05 23:01:01 +00001652 return ret;
bellardea2384d2004-08-01 21:59:26 +00001653}
1654
1655void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1656{
bellard19cb3732006-08-19 11:45:59 +00001657 if (!bs->drv) {
bellardea2384d2004-08-01 21:59:26 +00001658 buf[0] = '\0';
1659 } else {
1660 pstrcpy(buf, buf_size, bs->drv->format_name);
1661 }
1662}
1663
ths5fafdf22007-09-16 21:08:06 +00001664void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00001665 void *opaque)
1666{
1667 BlockDriver *drv;
1668
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01001669 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00001670 it(opaque, drv->format_name);
1671 }
1672}
1673
bellardb3380822004-03-14 21:38:54 +00001674BlockDriverState *bdrv_find(const char *name)
1675{
1676 BlockDriverState *bs;
1677
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001678 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1679 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00001680 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001681 }
bellardb3380822004-03-14 21:38:54 +00001682 }
1683 return NULL;
1684}
1685
Markus Armbruster2f399b02010-06-02 18:55:20 +02001686BlockDriverState *bdrv_next(BlockDriverState *bs)
1687{
1688 if (!bs) {
1689 return QTAILQ_FIRST(&bdrv_states);
1690 }
1691 return QTAILQ_NEXT(bs, list);
1692}
1693
aliguori51de9762009-03-05 23:00:43 +00001694void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00001695{
1696 BlockDriverState *bs;
1697
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001698 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00001699 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00001700 }
1701}
1702
bellardea2384d2004-08-01 21:59:26 +00001703const char *bdrv_get_device_name(BlockDriverState *bs)
1704{
1705 return bs->device_name;
1706}
1707
Kevin Wolf205ef792010-10-21 16:43:43 +02001708int bdrv_flush(BlockDriverState *bs)
pbrook7a6cba62006-06-04 11:39:07 +00001709{
Alexander Graf016f5cf2010-05-26 17:51:49 +02001710 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolf205ef792010-10-21 16:43:43 +02001711 return 0;
Alexander Graf016f5cf2010-05-26 17:51:49 +02001712 }
1713
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001714 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1715 return bdrv_co_flush_em(bs);
1716 }
1717
Kevin Wolf205ef792010-10-21 16:43:43 +02001718 if (bs->drv && bs->drv->bdrv_flush) {
1719 return bs->drv->bdrv_flush(bs);
1720 }
1721
1722 /*
1723 * Some block drivers always operate in either writethrough or unsafe mode
1724 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1725 * the server works (because the behaviour is hardcoded or depends on
1726 * server-side configuration), so we can't ensure that everything is safe
1727 * on disk. Returning an error doesn't work because that would break guests
1728 * even if the server operates in writethrough mode.
1729 *
1730 * Let's hope the user knows what he's doing.
1731 */
1732 return 0;
pbrook7a6cba62006-06-04 11:39:07 +00001733}
1734
aliguoric6ca28d2008-10-06 13:55:43 +00001735void bdrv_flush_all(void)
1736{
1737 BlockDriverState *bs;
1738
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001739 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1740 if (bs->drv && !bdrv_is_read_only(bs) &&
1741 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
aliguoric6ca28d2008-10-06 13:55:43 +00001742 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001743 }
1744 }
aliguoric6ca28d2008-10-06 13:55:43 +00001745}
1746
Kevin Wolff2feebb2010-04-14 17:30:35 +02001747int bdrv_has_zero_init(BlockDriverState *bs)
1748{
1749 assert(bs->drv);
1750
Kevin Wolf336c1c12010-07-28 11:26:29 +02001751 if (bs->drv->bdrv_has_zero_init) {
1752 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02001753 }
1754
1755 return 1;
1756}
1757
Christoph Hellwigbb8bf762010-12-16 19:36:31 +01001758int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1759{
1760 if (!bs->drv) {
1761 return -ENOMEDIUM;
1762 }
1763 if (!bs->drv->bdrv_discard) {
1764 return 0;
1765 }
1766 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1767}
1768
thsf58c7b32008-06-05 21:53:49 +00001769/*
1770 * Returns true iff the specified sector is present in the disk image. Drivers
1771 * not implementing the functionality are assumed to not support backing files,
1772 * hence all their sectors are reported as allocated.
1773 *
1774 * 'pnum' is set to the number of sectors (including and immediately following
1775 * the specified sector) that are known to be in the same
1776 * allocated/unallocated state.
1777 *
1778 * 'nb_sectors' is the max value 'pnum' should be set to.
1779 */
1780int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1781 int *pnum)
1782{
1783 int64_t n;
1784 if (!bs->drv->bdrv_is_allocated) {
1785 if (sector_num >= bs->total_sectors) {
1786 *pnum = 0;
1787 return 0;
1788 }
1789 n = bs->total_sectors - sector_num;
1790 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1791 return 1;
1792 }
1793 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1794}
1795
Luiz Capitulino2582bfe2010-02-03 12:41:01 -02001796void bdrv_mon_event(const BlockDriverState *bdrv,
1797 BlockMonEventAction action, int is_read)
1798{
1799 QObject *data;
1800 const char *action_str;
1801
1802 switch (action) {
1803 case BDRV_ACTION_REPORT:
1804 action_str = "report";
1805 break;
1806 case BDRV_ACTION_IGNORE:
1807 action_str = "ignore";
1808 break;
1809 case BDRV_ACTION_STOP:
1810 action_str = "stop";
1811 break;
1812 default:
1813 abort();
1814 }
1815
1816 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1817 bdrv->device_name,
1818 action_str,
1819 is_read ? "read" : "write");
1820 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1821
1822 qobject_decref(data);
1823}
1824
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001825static void bdrv_print_dict(QObject *obj, void *opaque)
bellardb3380822004-03-14 21:38:54 +00001826{
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001827 QDict *bs_dict;
1828 Monitor *mon = opaque;
1829
1830 bs_dict = qobject_to_qdict(obj);
1831
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001832 monitor_printf(mon, "%s: removable=%d",
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001833 qdict_get_str(bs_dict, "device"),
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001834 qdict_get_bool(bs_dict, "removable"));
1835
1836 if (qdict_get_bool(bs_dict, "removable")) {
1837 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1838 }
1839
1840 if (qdict_haskey(bs_dict, "inserted")) {
1841 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1842
1843 monitor_printf(mon, " file=");
1844 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1845 if (qdict_haskey(qdict, "backing_file")) {
1846 monitor_printf(mon, " backing_file=");
1847 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1848 }
1849 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1850 qdict_get_bool(qdict, "ro"),
1851 qdict_get_str(qdict, "drv"),
1852 qdict_get_bool(qdict, "encrypted"));
1853 } else {
1854 monitor_printf(mon, " [not inserted]");
1855 }
1856
1857 monitor_printf(mon, "\n");
1858}
1859
1860void bdrv_info_print(Monitor *mon, const QObject *data)
1861{
1862 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1863}
1864
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001865void bdrv_info(Monitor *mon, QObject **ret_data)
1866{
1867 QList *bs_list;
bellardb3380822004-03-14 21:38:54 +00001868 BlockDriverState *bs;
1869
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001870 bs_list = qlist_new();
1871
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001872 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001873 QObject *bs_obj;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001874
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001875 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001876 "'removable': %i, 'locked': %i }",
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001877 bs->device_name, bs->removable,
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001878 bs->locked);
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001879
bellard19cb3732006-08-19 11:45:59 +00001880 if (bs->drv) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001881 QObject *obj;
1882 QDict *bs_dict = qobject_to_qdict(bs_obj);
1883
1884 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1885 "'encrypted': %i }",
1886 bs->filename, bs->read_only,
1887 bs->drv->format_name,
1888 bdrv_is_encrypted(bs));
thsfef30742006-12-22 14:11:32 +00001889 if (bs->backing_file[0] != '\0') {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001890 QDict *qdict = qobject_to_qdict(obj);
1891 qdict_put(qdict, "backing_file",
1892 qstring_from_str(bs->backing_file));
aliguori376253e2009-03-05 23:01:23 +00001893 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001894
1895 qdict_put_obj(bs_dict, "inserted", obj);
bellardb3380822004-03-14 21:38:54 +00001896 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001897 qlist_append_obj(bs_list, bs_obj);
bellardb3380822004-03-14 21:38:54 +00001898 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001899
1900 *ret_data = QOBJECT(bs_list);
bellardb3380822004-03-14 21:38:54 +00001901}
thsa36e69d2007-12-02 05:18:19 +00001902
Luiz Capitulino218a5362009-12-10 17:16:07 -02001903static void bdrv_stats_iter(QObject *data, void *opaque)
thsa36e69d2007-12-02 05:18:19 +00001904{
Luiz Capitulino218a5362009-12-10 17:16:07 -02001905 QDict *qdict;
1906 Monitor *mon = opaque;
1907
1908 qdict = qobject_to_qdict(data);
1909 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1910
1911 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1912 monitor_printf(mon, " rd_bytes=%" PRId64
1913 " wr_bytes=%" PRId64
1914 " rd_operations=%" PRId64
1915 " wr_operations=%" PRId64
1916 "\n",
1917 qdict_get_int(qdict, "rd_bytes"),
1918 qdict_get_int(qdict, "wr_bytes"),
1919 qdict_get_int(qdict, "rd_operations"),
1920 qdict_get_int(qdict, "wr_operations"));
1921}
1922
1923void bdrv_stats_print(Monitor *mon, const QObject *data)
1924{
1925 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1926}
1927
Kevin Wolf294cc352010-04-28 14:34:01 +02001928static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1929{
1930 QObject *res;
1931 QDict *dict;
1932
1933 res = qobject_from_jsonf("{ 'stats': {"
1934 "'rd_bytes': %" PRId64 ","
1935 "'wr_bytes': %" PRId64 ","
1936 "'rd_operations': %" PRId64 ","
1937 "'wr_operations': %" PRId64 ","
1938 "'wr_highest_offset': %" PRId64
1939 "} }",
1940 bs->rd_bytes, bs->wr_bytes,
1941 bs->rd_ops, bs->wr_ops,
Blue Swirl5ffbbc62010-06-14 18:55:33 +00001942 bs->wr_highest_sector *
1943 (uint64_t)BDRV_SECTOR_SIZE);
Kevin Wolf294cc352010-04-28 14:34:01 +02001944 dict = qobject_to_qdict(res);
1945
1946 if (*bs->device_name) {
1947 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1948 }
1949
1950 if (bs->file) {
1951 QObject *parent = bdrv_info_stats_bs(bs->file);
1952 qdict_put_obj(dict, "parent", parent);
1953 }
1954
1955 return res;
1956}
1957
Luiz Capitulino218a5362009-12-10 17:16:07 -02001958void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1959{
1960 QObject *obj;
1961 QList *devices;
thsa36e69d2007-12-02 05:18:19 +00001962 BlockDriverState *bs;
1963
Luiz Capitulino218a5362009-12-10 17:16:07 -02001964 devices = qlist_new();
1965
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001966 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Kevin Wolf294cc352010-04-28 14:34:01 +02001967 obj = bdrv_info_stats_bs(bs);
Luiz Capitulino218a5362009-12-10 17:16:07 -02001968 qlist_append_obj(devices, obj);
thsa36e69d2007-12-02 05:18:19 +00001969 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02001970
1971 *ret_data = QOBJECT(devices);
thsa36e69d2007-12-02 05:18:19 +00001972}
bellardea2384d2004-08-01 21:59:26 +00001973
aliguori045df332009-03-05 23:00:48 +00001974const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1975{
1976 if (bs->backing_hd && bs->backing_hd->encrypted)
1977 return bs->backing_file;
1978 else if (bs->encrypted)
1979 return bs->filename;
1980 else
1981 return NULL;
1982}
1983
ths5fafdf22007-09-16 21:08:06 +00001984void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00001985 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00001986{
Kevin Wolfb783e402010-01-12 12:55:16 +01001987 if (!bs->backing_file) {
bellard83f64092006-08-01 16:21:11 +00001988 pstrcpy(filename, filename_size, "");
1989 } else {
1990 pstrcpy(filename, filename_size, bs->backing_file);
1991 }
bellardea2384d2004-08-01 21:59:26 +00001992}
1993
ths5fafdf22007-09-16 21:08:06 +00001994int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00001995 const uint8_t *buf, int nb_sectors)
1996{
1997 BlockDriver *drv = bs->drv;
1998 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001999 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002000 if (!drv->bdrv_write_compressed)
2001 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02002002 if (bdrv_check_request(bs, sector_num, nb_sectors))
2003 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002004
Jan Kiszkac6d22832009-11-30 18:21:20 +01002005 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002006 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2007 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002008
bellardfaea38e2006-08-05 21:31:00 +00002009 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2010}
ths3b46e622007-09-17 08:09:54 +00002011
bellardfaea38e2006-08-05 21:31:00 +00002012int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2013{
2014 BlockDriver *drv = bs->drv;
2015 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002016 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002017 if (!drv->bdrv_get_info)
2018 return -ENOTSUP;
2019 memset(bdi, 0, sizeof(*bdi));
2020 return drv->bdrv_get_info(bs, bdi);
2021}
2022
Christoph Hellwig45566e92009-07-10 23:11:57 +02002023int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2024 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002025{
2026 BlockDriver *drv = bs->drv;
2027 if (!drv)
2028 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002029 if (drv->bdrv_save_vmstate)
2030 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2031 if (bs->file)
2032 return bdrv_save_vmstate(bs->file, buf, pos, size);
2033 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002034}
2035
Christoph Hellwig45566e92009-07-10 23:11:57 +02002036int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2037 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002038{
2039 BlockDriver *drv = bs->drv;
2040 if (!drv)
2041 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002042 if (drv->bdrv_load_vmstate)
2043 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2044 if (bs->file)
2045 return bdrv_load_vmstate(bs->file, buf, pos, size);
2046 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002047}
2048
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01002049void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2050{
2051 BlockDriver *drv = bs->drv;
2052
2053 if (!drv || !drv->bdrv_debug_event) {
2054 return;
2055 }
2056
2057 return drv->bdrv_debug_event(bs, event);
2058
2059}
2060
bellardfaea38e2006-08-05 21:31:00 +00002061/**************************************************************/
2062/* handling of snapshots */
2063
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002064int bdrv_can_snapshot(BlockDriverState *bs)
2065{
2066 BlockDriver *drv = bs->drv;
2067 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
2068 return 0;
2069 }
2070
2071 if (!drv->bdrv_snapshot_create) {
2072 if (bs->file != NULL) {
2073 return bdrv_can_snapshot(bs->file);
2074 }
2075 return 0;
2076 }
2077
2078 return 1;
2079}
2080
Blue Swirl199630b2010-07-25 20:49:34 +00002081int bdrv_is_snapshot(BlockDriverState *bs)
2082{
2083 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2084}
2085
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002086BlockDriverState *bdrv_snapshots(void)
2087{
2088 BlockDriverState *bs;
2089
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002090 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002091 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002092 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002093
2094 bs = NULL;
2095 while ((bs = bdrv_next(bs))) {
2096 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002097 bs_snapshots = bs;
2098 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002099 }
2100 }
2101 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002102}
2103
ths5fafdf22007-09-16 21:08:06 +00002104int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002105 QEMUSnapshotInfo *sn_info)
2106{
2107 BlockDriver *drv = bs->drv;
2108 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002109 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002110 if (drv->bdrv_snapshot_create)
2111 return drv->bdrv_snapshot_create(bs, sn_info);
2112 if (bs->file)
2113 return bdrv_snapshot_create(bs->file, sn_info);
2114 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002115}
2116
ths5fafdf22007-09-16 21:08:06 +00002117int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002118 const char *snapshot_id)
2119{
2120 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002121 int ret, open_ret;
2122
bellardfaea38e2006-08-05 21:31:00 +00002123 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002124 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002125 if (drv->bdrv_snapshot_goto)
2126 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2127
2128 if (bs->file) {
2129 drv->bdrv_close(bs);
2130 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2131 open_ret = drv->bdrv_open(bs, bs->open_flags);
2132 if (open_ret < 0) {
2133 bdrv_delete(bs->file);
2134 bs->drv = NULL;
2135 return open_ret;
2136 }
2137 return ret;
2138 }
2139
2140 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002141}
2142
2143int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2144{
2145 BlockDriver *drv = bs->drv;
2146 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002147 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002148 if (drv->bdrv_snapshot_delete)
2149 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2150 if (bs->file)
2151 return bdrv_snapshot_delete(bs->file, snapshot_id);
2152 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002153}
2154
ths5fafdf22007-09-16 21:08:06 +00002155int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002156 QEMUSnapshotInfo **psn_info)
2157{
2158 BlockDriver *drv = bs->drv;
2159 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002160 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002161 if (drv->bdrv_snapshot_list)
2162 return drv->bdrv_snapshot_list(bs, psn_info);
2163 if (bs->file)
2164 return bdrv_snapshot_list(bs->file, psn_info);
2165 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002166}
2167
edison51ef6722010-09-21 19:58:41 -07002168int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2169 const char *snapshot_name)
2170{
2171 BlockDriver *drv = bs->drv;
2172 if (!drv) {
2173 return -ENOMEDIUM;
2174 }
2175 if (!bs->read_only) {
2176 return -EINVAL;
2177 }
2178 if (drv->bdrv_snapshot_load_tmp) {
2179 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2180 }
2181 return -ENOTSUP;
2182}
2183
bellardfaea38e2006-08-05 21:31:00 +00002184#define NB_SUFFIXES 4
2185
2186char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2187{
2188 static const char suffixes[NB_SUFFIXES] = "KMGT";
2189 int64_t base;
2190 int i;
2191
2192 if (size <= 999) {
2193 snprintf(buf, buf_size, "%" PRId64, size);
2194 } else {
2195 base = 1024;
2196 for(i = 0; i < NB_SUFFIXES; i++) {
2197 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00002198 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00002199 (double)size / base,
2200 suffixes[i]);
2201 break;
2202 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00002203 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00002204 ((size + (base >> 1)) / base),
2205 suffixes[i]);
2206 break;
2207 }
2208 base = base * 1024;
2209 }
2210 }
2211 return buf;
2212}
2213
2214char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2215{
2216 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00002217#ifdef _WIN32
2218 struct tm *ptm;
2219#else
bellardfaea38e2006-08-05 21:31:00 +00002220 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00002221#endif
bellardfaea38e2006-08-05 21:31:00 +00002222 time_t ti;
2223 int64_t secs;
2224
2225 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00002226 snprintf(buf, buf_size,
2227 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002228 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2229 } else {
2230 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00002231#ifdef _WIN32
2232 ptm = localtime(&ti);
2233 strftime(date_buf, sizeof(date_buf),
2234 "%Y-%m-%d %H:%M:%S", ptm);
2235#else
bellardfaea38e2006-08-05 21:31:00 +00002236 localtime_r(&ti, &tm);
2237 strftime(date_buf, sizeof(date_buf),
2238 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00002239#endif
bellardfaea38e2006-08-05 21:31:00 +00002240 secs = sn->vm_clock_nsec / 1000000000;
2241 snprintf(clock_buf, sizeof(clock_buf),
2242 "%02d:%02d:%02d.%03d",
2243 (int)(secs / 3600),
2244 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00002245 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00002246 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2247 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00002248 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002249 sn->id_str, sn->name,
2250 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2251 date_buf,
2252 clock_buf);
2253 }
2254 return buf;
2255}
2256
bellardea2384d2004-08-01 21:59:26 +00002257
bellard83f64092006-08-01 16:21:11 +00002258/**************************************************************/
2259/* async I/Os */
2260
aliguori3b69e4b2009-01-22 16:59:24 +00002261BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00002262 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00002263 BlockDriverCompletionFunc *cb, void *opaque)
2264{
bellard83f64092006-08-01 16:21:11 +00002265 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002266 BlockDriverAIOCB *ret;
bellard83f64092006-08-01 16:21:11 +00002267
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002268 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2269
bellard19cb3732006-08-19 11:45:59 +00002270 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002271 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002272 if (bdrv_check_request(bs, sector_num, nb_sectors))
2273 return NULL;
ths3b46e622007-09-17 08:09:54 +00002274
aliguorif141eaf2009-04-07 18:43:24 +00002275 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2276 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002277
2278 if (ret) {
Robert Wangd62b5de2011-08-19 17:17:12 +08002279 /* Update stats even though technically transfer has not happened. */
2280 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2281 bs->rd_ops++;
thsa36e69d2007-12-02 05:18:19 +00002282 }
2283
2284 return ret;
bellard83f64092006-08-01 16:21:11 +00002285}
2286
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002287typedef struct BlockCompleteData {
2288 BlockDriverCompletionFunc *cb;
2289 void *opaque;
2290 BlockDriverState *bs;
2291 int64_t sector_num;
2292 int nb_sectors;
2293} BlockCompleteData;
2294
2295static void block_complete_cb(void *opaque, int ret)
2296{
2297 BlockCompleteData *b = opaque;
2298
2299 if (b->bs->dirty_bitmap) {
2300 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2301 }
2302 b->cb(b->opaque, ret);
Anthony Liguori7267c092011-08-20 22:09:37 -05002303 g_free(b);
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002304}
2305
2306static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2307 int64_t sector_num,
2308 int nb_sectors,
2309 BlockDriverCompletionFunc *cb,
2310 void *opaque)
2311{
Anthony Liguori7267c092011-08-20 22:09:37 -05002312 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002313
2314 blkdata->bs = bs;
2315 blkdata->cb = cb;
2316 blkdata->opaque = opaque;
2317 blkdata->sector_num = sector_num;
2318 blkdata->nb_sectors = nb_sectors;
2319
2320 return blkdata;
2321}
2322
aliguorif141eaf2009-04-07 18:43:24 +00002323BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2324 QEMUIOVector *qiov, int nb_sectors,
2325 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002326{
bellard83f64092006-08-01 16:21:11 +00002327 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002328 BlockDriverAIOCB *ret;
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002329 BlockCompleteData *blk_cb_data;
bellard83f64092006-08-01 16:21:11 +00002330
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002331 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2332
bellard19cb3732006-08-19 11:45:59 +00002333 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002334 return NULL;
bellard83f64092006-08-01 16:21:11 +00002335 if (bs->read_only)
pbrookce1a14d2006-08-07 02:38:06 +00002336 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002337 if (bdrv_check_request(bs, sector_num, nb_sectors))
2338 return NULL;
bellard83f64092006-08-01 16:21:11 +00002339
Jan Kiszkac6d22832009-11-30 18:21:20 +01002340 if (bs->dirty_bitmap) {
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002341 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2342 opaque);
2343 cb = &block_complete_cb;
2344 opaque = blk_cb_data;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002345 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002346
aliguorif141eaf2009-04-07 18:43:24 +00002347 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2348 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002349
2350 if (ret) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002351 /* Update stats even though technically transfer has not happened. */
2352 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2353 bs->wr_ops ++;
2354 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2355 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2356 }
thsa36e69d2007-12-02 05:18:19 +00002357 }
2358
2359 return ret;
bellard83f64092006-08-01 16:21:11 +00002360}
2361
Kevin Wolf40b4f532009-09-09 17:53:37 +02002362
2363typedef struct MultiwriteCB {
2364 int error;
2365 int num_requests;
2366 int num_callbacks;
2367 struct {
2368 BlockDriverCompletionFunc *cb;
2369 void *opaque;
2370 QEMUIOVector *free_qiov;
2371 void *free_buf;
2372 } callbacks[];
2373} MultiwriteCB;
2374
2375static void multiwrite_user_cb(MultiwriteCB *mcb)
2376{
2377 int i;
2378
2379 for (i = 0; i < mcb->num_callbacks; i++) {
2380 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01002381 if (mcb->callbacks[i].free_qiov) {
2382 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2383 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002384 g_free(mcb->callbacks[i].free_qiov);
Herve Poussineauf8a83242010-01-24 21:23:56 +00002385 qemu_vfree(mcb->callbacks[i].free_buf);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002386 }
2387}
2388
2389static void multiwrite_cb(void *opaque, int ret)
2390{
2391 MultiwriteCB *mcb = opaque;
2392
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002393 trace_multiwrite_cb(mcb, ret);
2394
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02002395 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02002396 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002397 }
2398
2399 mcb->num_requests--;
2400 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02002401 multiwrite_user_cb(mcb);
Anthony Liguori7267c092011-08-20 22:09:37 -05002402 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002403 }
2404}
2405
2406static int multiwrite_req_compare(const void *a, const void *b)
2407{
Christoph Hellwig77be4362010-05-19 20:53:10 +02002408 const BlockRequest *req1 = a, *req2 = b;
2409
2410 /*
2411 * Note that we can't simply subtract req2->sector from req1->sector
2412 * here as that could overflow the return value.
2413 */
2414 if (req1->sector > req2->sector) {
2415 return 1;
2416 } else if (req1->sector < req2->sector) {
2417 return -1;
2418 } else {
2419 return 0;
2420 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002421}
2422
2423/*
2424 * Takes a bunch of requests and tries to merge them. Returns the number of
2425 * requests that remain after merging.
2426 */
2427static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2428 int num_reqs, MultiwriteCB *mcb)
2429{
2430 int i, outidx;
2431
2432 // Sort requests by start sector
2433 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2434
2435 // Check if adjacent requests touch the same clusters. If so, combine them,
2436 // filling up gaps with zero sectors.
2437 outidx = 0;
2438 for (i = 1; i < num_reqs; i++) {
2439 int merge = 0;
2440 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2441
2442 // This handles the cases that are valid for all block drivers, namely
2443 // exactly sequential writes and overlapping writes.
2444 if (reqs[i].sector <= oldreq_last) {
2445 merge = 1;
2446 }
2447
2448 // The block driver may decide that it makes sense to combine requests
2449 // even if there is a gap of some sectors between them. In this case,
2450 // the gap is filled with zeros (therefore only applicable for yet
2451 // unused space in format like qcow2).
2452 if (!merge && bs->drv->bdrv_merge_requests) {
2453 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2454 }
2455
Christoph Hellwige2a305f2010-01-26 14:49:08 +01002456 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2457 merge = 0;
2458 }
2459
Kevin Wolf40b4f532009-09-09 17:53:37 +02002460 if (merge) {
2461 size_t size;
Anthony Liguori7267c092011-08-20 22:09:37 -05002462 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002463 qemu_iovec_init(qiov,
2464 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2465
2466 // Add the first request to the merged one. If the requests are
2467 // overlapping, drop the last sectors of the first request.
2468 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2469 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2470
2471 // We might need to add some zeros between the two requests
2472 if (reqs[i].sector > oldreq_last) {
2473 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2474 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2475 memset(buf, 0, zero_bytes);
2476 qemu_iovec_add(qiov, buf, zero_bytes);
2477 mcb->callbacks[i].free_buf = buf;
2478 }
2479
2480 // Add the second request
2481 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2482
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02002483 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002484 reqs[outidx].qiov = qiov;
2485
2486 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2487 } else {
2488 outidx++;
2489 reqs[outidx].sector = reqs[i].sector;
2490 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2491 reqs[outidx].qiov = reqs[i].qiov;
2492 }
2493 }
2494
2495 return outidx + 1;
2496}
2497
2498/*
2499 * Submit multiple AIO write requests at once.
2500 *
2501 * On success, the function returns 0 and all requests in the reqs array have
2502 * been submitted. In error case this function returns -1, and any of the
2503 * requests may or may not be submitted yet. In particular, this means that the
2504 * callback will be called for some of the requests, for others it won't. The
2505 * caller must check the error field of the BlockRequest to wait for the right
2506 * callbacks (if error != 0, no callback will be called).
2507 *
2508 * The implementation may modify the contents of the reqs array, e.g. to merge
2509 * requests. However, the fields opaque and error are left unmodified as they
2510 * are used to signal failure for a single request to the caller.
2511 */
2512int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2513{
2514 BlockDriverAIOCB *acb;
2515 MultiwriteCB *mcb;
2516 int i;
2517
Ryan Harper301db7c2011-03-07 10:01:04 -06002518 /* don't submit writes if we don't have a medium */
2519 if (bs->drv == NULL) {
2520 for (i = 0; i < num_reqs; i++) {
2521 reqs[i].error = -ENOMEDIUM;
2522 }
2523 return -1;
2524 }
2525
Kevin Wolf40b4f532009-09-09 17:53:37 +02002526 if (num_reqs == 0) {
2527 return 0;
2528 }
2529
2530 // Create MultiwriteCB structure
Anthony Liguori7267c092011-08-20 22:09:37 -05002531 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002532 mcb->num_requests = 0;
2533 mcb->num_callbacks = num_reqs;
2534
2535 for (i = 0; i < num_reqs; i++) {
2536 mcb->callbacks[i].cb = reqs[i].cb;
2537 mcb->callbacks[i].opaque = reqs[i].opaque;
2538 }
2539
2540 // Check for mergable requests
2541 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2542
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002543 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2544
Kevin Wolf453f9a12010-07-02 14:01:21 +02002545 /*
2546 * Run the aio requests. As soon as one request can't be submitted
2547 * successfully, fail all requests that are not yet submitted (we must
2548 * return failure for all requests anyway)
2549 *
2550 * num_requests cannot be set to the right value immediately: If
2551 * bdrv_aio_writev fails for some request, num_requests would be too high
2552 * and therefore multiwrite_cb() would never recognize the multiwrite
2553 * request as completed. We also cannot use the loop variable i to set it
2554 * when the first request fails because the callback may already have been
2555 * called for previously submitted requests. Thus, num_requests must be
2556 * incremented for each request that is submitted.
2557 *
2558 * The problem that callbacks may be called early also means that we need
2559 * to take care that num_requests doesn't become 0 before all requests are
2560 * submitted - multiwrite_cb() would consider the multiwrite request
2561 * completed. A dummy request that is "completed" by a manual call to
2562 * multiwrite_cb() takes care of this.
2563 */
2564 mcb->num_requests = 1;
2565
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002566 // Run the aio requests
Kevin Wolf40b4f532009-09-09 17:53:37 +02002567 for (i = 0; i < num_reqs; i++) {
Kevin Wolf453f9a12010-07-02 14:01:21 +02002568 mcb->num_requests++;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002569 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2570 reqs[i].nb_sectors, multiwrite_cb, mcb);
2571
2572 if (acb == NULL) {
2573 // We can only fail the whole thing if no request has been
2574 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2575 // complete and report the error in the callback.
Kevin Wolf453f9a12010-07-02 14:01:21 +02002576 if (i == 0) {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002577 trace_bdrv_aio_multiwrite_earlyfail(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002578 goto fail;
2579 } else {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002580 trace_bdrv_aio_multiwrite_latefail(mcb, i);
Kevin Wolf7eb58a62010-04-06 18:24:07 +02002581 multiwrite_cb(mcb, -EIO);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002582 break;
2583 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002584 }
2585 }
2586
Kevin Wolf453f9a12010-07-02 14:01:21 +02002587 /* Complete the dummy request */
2588 multiwrite_cb(mcb, 0);
2589
Kevin Wolf40b4f532009-09-09 17:53:37 +02002590 return 0;
2591
2592fail:
Kevin Wolf453f9a12010-07-02 14:01:21 +02002593 for (i = 0; i < mcb->num_callbacks; i++) {
2594 reqs[i].error = -EIO;
2595 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002596 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002597 return -1;
2598}
2599
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002600BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2601 BlockDriverCompletionFunc *cb, void *opaque)
2602{
2603 BlockDriver *drv = bs->drv;
2604
Stefan Hajnoczia13aac02011-03-07 07:58:04 +00002605 trace_bdrv_aio_flush(bs, opaque);
2606
Alexander Graf016f5cf2010-05-26 17:51:49 +02002607 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2608 return bdrv_aio_noop_em(bs, cb, opaque);
2609 }
2610
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002611 if (!drv)
2612 return NULL;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002613 return drv->bdrv_aio_flush(bs, cb, opaque);
2614}
2615
bellard83f64092006-08-01 16:21:11 +00002616void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00002617{
aliguori6bbff9a2009-03-20 18:25:59 +00002618 acb->pool->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00002619}
2620
pbrookce1a14d2006-08-07 02:38:06 +00002621
bellard83f64092006-08-01 16:21:11 +00002622/**************************************************************/
2623/* async block device emulation */
2624
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002625typedef struct BlockDriverAIOCBSync {
2626 BlockDriverAIOCB common;
2627 QEMUBH *bh;
2628 int ret;
2629 /* vector translation state */
2630 QEMUIOVector *qiov;
2631 uint8_t *bounce;
2632 int is_write;
2633} BlockDriverAIOCBSync;
2634
2635static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2636{
Kevin Wolfb666d232010-05-05 11:44:39 +02002637 BlockDriverAIOCBSync *acb =
2638 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03002639 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002640 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002641 qemu_aio_release(acb);
2642}
2643
2644static AIOPool bdrv_em_aio_pool = {
2645 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2646 .cancel = bdrv_aio_cancel_em,
2647};
2648
bellard83f64092006-08-01 16:21:11 +00002649static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00002650{
pbrookce1a14d2006-08-07 02:38:06 +00002651 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00002652
aliguorif141eaf2009-04-07 18:43:24 +00002653 if (!acb->is_write)
2654 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00002655 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00002656 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03002657 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002658 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00002659 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00002660}
bellardbeac80c2006-06-26 20:08:57 +00002661
aliguorif141eaf2009-04-07 18:43:24 +00002662static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2663 int64_t sector_num,
2664 QEMUIOVector *qiov,
2665 int nb_sectors,
2666 BlockDriverCompletionFunc *cb,
2667 void *opaque,
2668 int is_write)
2669
bellardea2384d2004-08-01 21:59:26 +00002670{
pbrookce1a14d2006-08-07 02:38:06 +00002671 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00002672
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002673 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00002674 acb->is_write = is_write;
2675 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00002676 acb->bounce = qemu_blockalign(bs, qiov->size);
aliguorif141eaf2009-04-07 18:43:24 +00002677
pbrookce1a14d2006-08-07 02:38:06 +00002678 if (!acb->bh)
2679 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00002680
2681 if (is_write) {
2682 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2683 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2684 } else {
2685 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2686 }
2687
pbrookce1a14d2006-08-07 02:38:06 +00002688 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00002689
pbrookce1a14d2006-08-07 02:38:06 +00002690 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00002691}
2692
aliguorif141eaf2009-04-07 18:43:24 +00002693static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2694 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00002695 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002696{
aliguorif141eaf2009-04-07 18:43:24 +00002697 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00002698}
2699
aliguorif141eaf2009-04-07 18:43:24 +00002700static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2701 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2702 BlockDriverCompletionFunc *cb, void *opaque)
2703{
2704 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2705}
2706
Kevin Wolf68485422011-06-30 10:05:46 +02002707
2708typedef struct BlockDriverAIOCBCoroutine {
2709 BlockDriverAIOCB common;
2710 BlockRequest req;
2711 bool is_write;
2712 QEMUBH* bh;
2713} BlockDriverAIOCBCoroutine;
2714
2715static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2716{
2717 qemu_aio_flush();
2718}
2719
2720static AIOPool bdrv_em_co_aio_pool = {
2721 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2722 .cancel = bdrv_aio_co_cancel_em,
2723};
2724
2725static void bdrv_co_rw_bh(void *opaque)
2726{
2727 BlockDriverAIOCBCoroutine *acb = opaque;
2728
2729 acb->common.cb(acb->common.opaque, acb->req.error);
2730 qemu_bh_delete(acb->bh);
2731 qemu_aio_release(acb);
2732}
2733
2734static void coroutine_fn bdrv_co_rw(void *opaque)
2735{
2736 BlockDriverAIOCBCoroutine *acb = opaque;
2737 BlockDriverState *bs = acb->common.bs;
2738
2739 if (!acb->is_write) {
2740 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2741 acb->req.nb_sectors, acb->req.qiov);
2742 } else {
2743 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2744 acb->req.nb_sectors, acb->req.qiov);
2745 }
2746
2747 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2748 qemu_bh_schedule(acb->bh);
2749}
2750
2751static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2752 int64_t sector_num,
2753 QEMUIOVector *qiov,
2754 int nb_sectors,
2755 BlockDriverCompletionFunc *cb,
2756 void *opaque,
2757 bool is_write)
2758{
2759 Coroutine *co;
2760 BlockDriverAIOCBCoroutine *acb;
2761
2762 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2763 acb->req.sector = sector_num;
2764 acb->req.nb_sectors = nb_sectors;
2765 acb->req.qiov = qiov;
2766 acb->is_write = is_write;
2767
2768 co = qemu_coroutine_create(bdrv_co_rw);
2769 qemu_coroutine_enter(co, acb);
2770
2771 return &acb->common;
2772}
2773
2774static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2775 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2776 BlockDriverCompletionFunc *cb, void *opaque)
2777{
2778 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2779 false);
2780}
2781
2782static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2783 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2784 BlockDriverCompletionFunc *cb, void *opaque)
2785{
2786 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2787 true);
2788}
2789
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002790static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2791 BlockDriverCompletionFunc *cb, void *opaque)
2792{
2793 BlockDriverAIOCBSync *acb;
2794
2795 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2796 acb->is_write = 1; /* don't bounce in the completion hadler */
2797 acb->qiov = NULL;
2798 acb->bounce = NULL;
2799 acb->ret = 0;
2800
2801 if (!acb->bh)
2802 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2803
2804 bdrv_flush(bs);
2805 qemu_bh_schedule(acb->bh);
2806 return &acb->common;
2807}
2808
Alexander Graf016f5cf2010-05-26 17:51:49 +02002809static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2810 BlockDriverCompletionFunc *cb, void *opaque)
2811{
2812 BlockDriverAIOCBSync *acb;
2813
2814 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2815 acb->is_write = 1; /* don't bounce in the completion handler */
2816 acb->qiov = NULL;
2817 acb->bounce = NULL;
2818 acb->ret = 0;
2819
2820 if (!acb->bh) {
2821 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2822 }
2823
2824 qemu_bh_schedule(acb->bh);
2825 return &acb->common;
2826}
2827
bellard83f64092006-08-01 16:21:11 +00002828/**************************************************************/
2829/* sync block device emulation */
2830
2831static void bdrv_rw_em_cb(void *opaque, int ret)
2832{
2833 *(int *)opaque = ret;
2834}
2835
2836#define NOT_DONE 0x7fffffff
2837
ths5fafdf22007-09-16 21:08:06 +00002838static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +00002839 uint8_t *buf, int nb_sectors)
2840{
pbrookce1a14d2006-08-07 02:38:06 +00002841 int async_ret;
2842 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002843 struct iovec iov;
2844 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002845
bellard83f64092006-08-01 16:21:11 +00002846 async_ret = NOT_DONE;
blueswir13f4cb3d2009-04-13 16:31:01 +00002847 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002848 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002849 qemu_iovec_init_external(&qiov, &iov, 1);
2850 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2851 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002852 if (acb == NULL) {
2853 async_ret = -1;
2854 goto fail;
2855 }
aliguoribaf35cb2008-09-10 15:45:19 +00002856
bellard83f64092006-08-01 16:21:11 +00002857 while (async_ret == NOT_DONE) {
2858 qemu_aio_wait();
2859 }
aliguoribaf35cb2008-09-10 15:45:19 +00002860
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002861
2862fail:
bellard83f64092006-08-01 16:21:11 +00002863 return async_ret;
2864}
2865
2866static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2867 const uint8_t *buf, int nb_sectors)
2868{
pbrookce1a14d2006-08-07 02:38:06 +00002869 int async_ret;
2870 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002871 struct iovec iov;
2872 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002873
bellard83f64092006-08-01 16:21:11 +00002874 async_ret = NOT_DONE;
aliguorif141eaf2009-04-07 18:43:24 +00002875 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002876 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002877 qemu_iovec_init_external(&qiov, &iov, 1);
2878 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2879 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002880 if (acb == NULL) {
2881 async_ret = -1;
2882 goto fail;
2883 }
bellard83f64092006-08-01 16:21:11 +00002884 while (async_ret == NOT_DONE) {
2885 qemu_aio_wait();
2886 }
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002887
2888fail:
bellard83f64092006-08-01 16:21:11 +00002889 return async_ret;
2890}
bellardea2384d2004-08-01 21:59:26 +00002891
2892void bdrv_init(void)
2893{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05002894 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00002895}
pbrookce1a14d2006-08-07 02:38:06 +00002896
Markus Armbrustereb852012009-10-27 18:41:44 +01002897void bdrv_init_with_whitelist(void)
2898{
2899 use_bdrv_whitelist = 1;
2900 bdrv_init();
2901}
2902
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002903void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2904 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00002905{
pbrookce1a14d2006-08-07 02:38:06 +00002906 BlockDriverAIOCB *acb;
2907
aliguori6bbff9a2009-03-20 18:25:59 +00002908 if (pool->free_aiocb) {
2909 acb = pool->free_aiocb;
2910 pool->free_aiocb = acb->next;
pbrookce1a14d2006-08-07 02:38:06 +00002911 } else {
Anthony Liguori7267c092011-08-20 22:09:37 -05002912 acb = g_malloc0(pool->aiocb_size);
aliguori6bbff9a2009-03-20 18:25:59 +00002913 acb->pool = pool;
pbrookce1a14d2006-08-07 02:38:06 +00002914 }
2915 acb->bs = bs;
2916 acb->cb = cb;
2917 acb->opaque = opaque;
2918 return acb;
2919}
2920
2921void qemu_aio_release(void *p)
2922{
aliguori6bbff9a2009-03-20 18:25:59 +00002923 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2924 AIOPool *pool = acb->pool;
2925 acb->next = pool->free_aiocb;
2926 pool->free_aiocb = acb;
pbrookce1a14d2006-08-07 02:38:06 +00002927}
bellard19cb3732006-08-19 11:45:59 +00002928
2929/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02002930/* Coroutine block device emulation */
2931
2932typedef struct CoroutineIOCompletion {
2933 Coroutine *coroutine;
2934 int ret;
2935} CoroutineIOCompletion;
2936
2937static void bdrv_co_io_em_complete(void *opaque, int ret)
2938{
2939 CoroutineIOCompletion *co = opaque;
2940
2941 co->ret = ret;
2942 qemu_coroutine_enter(co->coroutine, NULL);
2943}
2944
2945static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2946 int nb_sectors, QEMUIOVector *iov,
2947 bool is_write)
2948{
2949 CoroutineIOCompletion co = {
2950 .coroutine = qemu_coroutine_self(),
2951 };
2952 BlockDriverAIOCB *acb;
2953
2954 if (is_write) {
2955 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2956 bdrv_co_io_em_complete, &co);
2957 } else {
2958 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2959 bdrv_co_io_em_complete, &co);
2960 }
2961
2962 trace_bdrv_co_io(is_write, acb);
2963 if (!acb) {
2964 return -EIO;
2965 }
2966 qemu_coroutine_yield();
2967
2968 return co.ret;
2969}
2970
2971static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2972 int64_t sector_num, int nb_sectors,
2973 QEMUIOVector *iov)
2974{
2975 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2976}
2977
2978static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2979 int64_t sector_num, int nb_sectors,
2980 QEMUIOVector *iov)
2981{
2982 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
2983}
2984
Kevin Wolfe7a8a782011-07-15 16:05:00 +02002985static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
2986{
2987 CoroutineIOCompletion co = {
2988 .coroutine = qemu_coroutine_self(),
2989 };
2990 BlockDriverAIOCB *acb;
2991
2992 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2993 if (!acb) {
2994 return -EIO;
2995 }
2996 qemu_coroutine_yield();
2997 return co.ret;
2998}
2999
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003000/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00003001/* removable device support */
3002
3003/**
3004 * Return TRUE if the media is present
3005 */
3006int bdrv_is_inserted(BlockDriverState *bs)
3007{
3008 BlockDriver *drv = bs->drv;
3009 int ret;
3010 if (!drv)
3011 return 0;
3012 if (!drv->bdrv_is_inserted)
Markus Armbruster4be97622010-07-27 14:02:01 +02003013 return !bs->tray_open;
bellard19cb3732006-08-19 11:45:59 +00003014 ret = drv->bdrv_is_inserted(bs);
3015 return ret;
3016}
3017
3018/**
3019 * Return TRUE if the media changed since the last call to this
ths5fafdf22007-09-16 21:08:06 +00003020 * function. It is currently only used for floppy disks
bellard19cb3732006-08-19 11:45:59 +00003021 */
3022int bdrv_media_changed(BlockDriverState *bs)
3023{
3024 BlockDriver *drv = bs->drv;
3025 int ret;
3026
3027 if (!drv || !drv->bdrv_media_changed)
3028 ret = -ENOTSUP;
3029 else
3030 ret = drv->bdrv_media_changed(bs);
3031 if (ret == -ENOTSUP)
3032 ret = bs->media_changed;
3033 bs->media_changed = 0;
3034 return ret;
3035}
3036
3037/**
3038 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3039 */
Mark McLoughlinaea2a332009-05-27 10:06:11 +01003040int bdrv_eject(BlockDriverState *bs, int eject_flag)
bellard19cb3732006-08-19 11:45:59 +00003041{
3042 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003043
Markus Armbruster49aa46b2011-07-20 18:23:43 +02003044 if (eject_flag && bs->locked) {
Mark McLoughlinaea2a332009-05-27 10:06:11 +01003045 return -EBUSY;
3046 }
3047
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003048 if (drv && drv->bdrv_eject) {
3049 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00003050 }
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003051 bs->tray_open = eject_flag;
3052 return 0;
bellard19cb3732006-08-19 11:45:59 +00003053}
3054
3055int bdrv_is_locked(BlockDriverState *bs)
3056{
3057 return bs->locked;
3058}
3059
3060/**
3061 * Lock or unlock the media (if it is locked, the user won't be able
3062 * to eject it manually).
3063 */
3064void bdrv_set_locked(BlockDriverState *bs, int locked)
3065{
3066 BlockDriver *drv = bs->drv;
3067
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01003068 trace_bdrv_set_locked(bs, locked);
3069
bellard19cb3732006-08-19 11:45:59 +00003070 bs->locked = locked;
3071 if (drv && drv->bdrv_set_locked) {
3072 drv->bdrv_set_locked(bs, locked);
3073 }
3074}
ths985a03b2007-12-24 16:10:43 +00003075
3076/* needed for generic scsi interface */
3077
3078int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3079{
3080 BlockDriver *drv = bs->drv;
3081
3082 if (drv && drv->bdrv_ioctl)
3083 return drv->bdrv_ioctl(bs, req, buf);
3084 return -ENOTSUP;
3085}
aliguori7d780662009-03-12 19:57:08 +00003086
aliguori221f7152009-03-28 17:28:41 +00003087BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3088 unsigned long int req, void *buf,
3089 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00003090{
aliguori221f7152009-03-28 17:28:41 +00003091 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00003092
aliguori221f7152009-03-28 17:28:41 +00003093 if (drv && drv->bdrv_aio_ioctl)
3094 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3095 return NULL;
aliguori7d780662009-03-12 19:57:08 +00003096}
aliguorie268ca52009-04-22 20:20:00 +00003097
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003098
3099
aliguorie268ca52009-04-22 20:20:00 +00003100void *qemu_blockalign(BlockDriverState *bs, size_t size)
3101{
3102 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3103}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003104
3105void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3106{
3107 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003108
Liran Schouraaa0eb72010-01-26 10:31:48 +02003109 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003110 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003111 if (!bs->dirty_bitmap) {
3112 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3113 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3114 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003115
Anthony Liguori7267c092011-08-20 22:09:37 -05003116 bs->dirty_bitmap = g_malloc0(bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003117 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003118 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003119 if (bs->dirty_bitmap) {
Anthony Liguori7267c092011-08-20 22:09:37 -05003120 g_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01003121 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003122 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003123 }
3124}
3125
3126int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3127{
Jan Kiszka6ea44302009-11-30 18:21:19 +01003128 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003129
Jan Kiszkac6d22832009-11-30 18:21:20 +01003130 if (bs->dirty_bitmap &&
3131 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02003132 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3133 (1UL << (chunk % (sizeof(unsigned long) * 8))));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003134 } else {
3135 return 0;
3136 }
3137}
3138
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003139void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3140 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003141{
3142 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3143}
Liran Schouraaa0eb72010-01-26 10:31:48 +02003144
3145int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3146{
3147 return bs->dirty_count;
3148}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003149
Marcelo Tosattidb593f22011-01-26 12:12:34 -02003150void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3151{
3152 assert(bs->in_use != in_use);
3153 bs->in_use = in_use;
3154}
3155
3156int bdrv_in_use(BlockDriverState *bs)
3157{
3158 return bs->in_use;
3159}
3160
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003161int bdrv_img_create(const char *filename, const char *fmt,
3162 const char *base_filename, const char *base_fmt,
3163 char *options, uint64_t img_size, int flags)
3164{
3165 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02003166 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003167 BlockDriverState *bs = NULL;
3168 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003169 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003170 int ret = 0;
3171
3172 /* Find driver and parse its options */
3173 drv = bdrv_find_format(fmt);
3174 if (!drv) {
3175 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003176 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003177 goto out;
3178 }
3179
3180 proto_drv = bdrv_find_protocol(filename);
3181 if (!proto_drv) {
3182 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003183 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003184 goto out;
3185 }
3186
3187 create_options = append_option_parameters(create_options,
3188 drv->create_options);
3189 create_options = append_option_parameters(create_options,
3190 proto_drv->create_options);
3191
3192 /* Create parameter list with default values */
3193 param = parse_option_parameters("", create_options, param);
3194
3195 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3196
3197 /* Parse -o options */
3198 if (options) {
3199 param = parse_option_parameters(options, create_options, param);
3200 if (param == NULL) {
3201 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003202 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003203 goto out;
3204 }
3205 }
3206
3207 if (base_filename) {
3208 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3209 base_filename)) {
3210 error_report("Backing file not supported for file format '%s'",
3211 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003212 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003213 goto out;
3214 }
3215 }
3216
3217 if (base_fmt) {
3218 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3219 error_report("Backing file format not supported for file "
3220 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003221 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003222 goto out;
3223 }
3224 }
3225
Jes Sorensen792da932010-12-16 13:52:17 +01003226 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3227 if (backing_file && backing_file->value.s) {
3228 if (!strcmp(filename, backing_file->value.s)) {
3229 error_report("Error: Trying to create an image with the "
3230 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003231 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01003232 goto out;
3233 }
3234 }
3235
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003236 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3237 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003238 backing_drv = bdrv_find_format(backing_fmt->value.s);
3239 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003240 error_report("Unknown backing file format '%s'",
3241 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003242 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003243 goto out;
3244 }
3245 }
3246
3247 // The size for the image must always be specified, with one exception:
3248 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02003249 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3250 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003251 if (backing_file && backing_file->value.s) {
3252 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003253 char buf[32];
3254
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003255 bs = bdrv_new("");
3256
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003257 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003258 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003259 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003260 goto out;
3261 }
3262 bdrv_get_geometry(bs, &size);
3263 size *= 512;
3264
3265 snprintf(buf, sizeof(buf), "%" PRId64, size);
3266 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3267 } else {
3268 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003269 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003270 goto out;
3271 }
3272 }
3273
3274 printf("Formatting '%s', fmt=%s ", filename, fmt);
3275 print_option_parameters(param);
3276 puts("");
3277
3278 ret = bdrv_create(drv, filename, param);
3279
3280 if (ret < 0) {
3281 if (ret == -ENOTSUP) {
3282 error_report("Formatting or formatting option not supported for "
3283 "file format '%s'", fmt);
3284 } else if (ret == -EFBIG) {
3285 error_report("The image size is too large for file format '%s'",
3286 fmt);
3287 } else {
3288 error_report("%s: error while creating %s: %s", filename, fmt,
3289 strerror(-ret));
3290 }
3291 }
3292
3293out:
3294 free_option_parameters(create_options);
3295 free_option_parameters(param);
3296
3297 if (bs) {
3298 bdrv_delete(bs);
3299 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01003300
3301 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003302}