blob: f4731eca6f1b0e6fd863d653d9f36e599eeee8e2 [file] [log] [blame]
bellardfc01f7e2003-06-30 10:03:06 +00001/*
2 * QEMU System Emulator block driver
ths5fafdf22007-09-16 21:08:06 +00003 *
bellardfc01f7e2003-06-30 10:03:06 +00004 * Copyright (c) 2003 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardfc01f7e2003-06-30 10:03:06 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
blueswir13990d092008-12-05 17:53:21 +000024#include "config-host.h"
pbrookfaf07962007-11-11 02:51:17 +000025#include "qemu-common.h"
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +010026#include "trace.h"
aliguori376253e2009-03-05 23:01:23 +000027#include "monitor.h"
bellardea2384d2004-08-01 21:59:26 +000028#include "block_int.h"
Anthony Liguori5efa9d52009-05-09 17:03:42 -050029#include "module.h"
Luiz Capitulinod15e5462009-12-10 17:16:06 -020030#include "qemu-objects.h"
Kevin Wolf68485422011-06-30 10:05:46 +020031#include "qemu-coroutine.h"
bellardfc01f7e2003-06-30 10:03:06 +000032
Juan Quintela71e72a12009-07-27 16:12:56 +020033#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000034#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000037#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000038#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000039#include <sys/disk.h>
40#endif
blueswir1c5e97232009-03-07 20:06:23 +000041#endif
bellard7674e7b2005-04-26 21:59:26 +000042
aliguori49dc7682009-03-08 16:26:59 +000043#ifdef _WIN32
44#include <windows.h>
45#endif
46
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +020047static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
aliguorif141eaf2009-04-07 18:43:24 +000048static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
aliguoric87c0672009-04-07 18:43:20 +000050 BlockDriverCompletionFunc *cb, void *opaque);
aliguorif141eaf2009-04-07 18:43:24 +000051static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +000053 BlockDriverCompletionFunc *cb, void *opaque);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +020054static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55 BlockDriverCompletionFunc *cb, void *opaque);
Alexander Graf016f5cf2010-05-26 17:51:49 +020056static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57 BlockDriverCompletionFunc *cb, void *opaque);
ths5fafdf22007-09-16 21:08:06 +000058static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +000059 uint8_t *buf, int nb_sectors);
60static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61 const uint8_t *buf, int nb_sectors);
Kevin Wolf68485422011-06-30 10:05:46 +020062static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64 BlockDriverCompletionFunc *cb, void *opaque);
65static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67 BlockDriverCompletionFunc *cb, void *opaque);
Kevin Wolff9f05dc2011-07-15 13:50:26 +020068static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69 int64_t sector_num, int nb_sectors,
70 QEMUIOVector *iov);
71static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72 int64_t sector_num, int nb_sectors,
73 QEMUIOVector *iov);
Kevin Wolfe7a8a782011-07-15 16:05:00 +020074static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +010075static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
76 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov);
bellardec530c82006-04-25 22:36:06 +000077
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +010078static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
79 QTAILQ_HEAD_INITIALIZER(bdrv_states);
blueswir17ee930d2008-09-17 19:04:14 +000080
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010081static QLIST_HEAD(, BlockDriver) bdrv_drivers =
82 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000083
Markus Armbrusterf9092b12010-06-25 10:33:39 +020084/* The device to use for VM snapshots */
85static BlockDriverState *bs_snapshots;
86
Markus Armbrustereb852012009-10-27 18:41:44 +010087/* If non-zero, use only whitelisted block drivers */
88static int use_bdrv_whitelist;
89
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000090#ifdef _WIN32
91static int is_windows_drive_prefix(const char *filename)
92{
93 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
94 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
95 filename[1] == ':');
96}
97
98int is_windows_drive(const char *filename)
99{
100 if (is_windows_drive_prefix(filename) &&
101 filename[2] == '\0')
102 return 1;
103 if (strstart(filename, "\\\\.\\", NULL) ||
104 strstart(filename, "//./", NULL))
105 return 1;
106 return 0;
107}
108#endif
109
110/* check if the path starts with "<protocol>:" */
111static int path_has_protocol(const char *path)
112{
113#ifdef _WIN32
114 if (is_windows_drive(path) ||
115 is_windows_drive_prefix(path)) {
116 return 0;
117 }
118#endif
119
120 return strchr(path, ':') != NULL;
121}
122
bellard83f64092006-08-01 16:21:11 +0000123int path_is_absolute(const char *path)
124{
125 const char *p;
bellard21664422007-01-07 18:22:37 +0000126#ifdef _WIN32
127 /* specific case for names like: "\\.\d:" */
128 if (*path == '/' || *path == '\\')
129 return 1;
130#endif
bellard83f64092006-08-01 16:21:11 +0000131 p = strchr(path, ':');
132 if (p)
133 p++;
134 else
135 p = path;
bellard3b9f94e2007-01-07 17:27:07 +0000136#ifdef _WIN32
137 return (*p == '/' || *p == '\\');
138#else
139 return (*p == '/');
140#endif
bellard83f64092006-08-01 16:21:11 +0000141}
142
143/* if filename is absolute, just copy it to dest. Otherwise, build a
144 path to it by considering it is relative to base_path. URL are
145 supported. */
146void path_combine(char *dest, int dest_size,
147 const char *base_path,
148 const char *filename)
149{
150 const char *p, *p1;
151 int len;
152
153 if (dest_size <= 0)
154 return;
155 if (path_is_absolute(filename)) {
156 pstrcpy(dest, dest_size, filename);
157 } else {
158 p = strchr(base_path, ':');
159 if (p)
160 p++;
161 else
162 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000163 p1 = strrchr(base_path, '/');
164#ifdef _WIN32
165 {
166 const char *p2;
167 p2 = strrchr(base_path, '\\');
168 if (!p1 || p2 > p1)
169 p1 = p2;
170 }
171#endif
bellard83f64092006-08-01 16:21:11 +0000172 if (p1)
173 p1++;
174 else
175 p1 = base_path;
176 if (p1 > p)
177 p = p1;
178 len = p - base_path;
179 if (len > dest_size - 1)
180 len = dest_size - 1;
181 memcpy(dest, base_path, len);
182 dest[len] = '\0';
183 pstrcat(dest, dest_size, filename);
184 }
185}
186
Anthony Liguori5efa9d52009-05-09 17:03:42 -0500187void bdrv_register(BlockDriver *bdrv)
bellardea2384d2004-08-01 21:59:26 +0000188{
Kevin Wolf68485422011-06-30 10:05:46 +0200189 if (bdrv->bdrv_co_readv) {
190 /* Emulate AIO by coroutines, and sync by AIO */
191 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
192 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
193 bdrv->bdrv_read = bdrv_read_em;
194 bdrv->bdrv_write = bdrv_write_em;
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200195 } else {
196 bdrv->bdrv_co_readv = bdrv_co_readv_em;
197 bdrv->bdrv_co_writev = bdrv_co_writev_em;
198
199 if (!bdrv->bdrv_aio_readv) {
200 /* add AIO emulation layer */
201 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
202 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
203 } else if (!bdrv->bdrv_read) {
204 /* add synchronous IO emulation layer */
205 bdrv->bdrv_read = bdrv_read_em;
206 bdrv->bdrv_write = bdrv_write_em;
207 }
bellard83f64092006-08-01 16:21:11 +0000208 }
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +0200209
210 if (!bdrv->bdrv_aio_flush)
211 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
212
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100213 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000214}
bellardb3380822004-03-14 21:38:54 +0000215
216/* create a new block device (by default it is empty) */
217BlockDriverState *bdrv_new(const char *device_name)
bellardfc01f7e2003-06-30 10:03:06 +0000218{
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100219 BlockDriverState *bs;
bellardb3380822004-03-14 21:38:54 +0000220
Anthony Liguori7267c092011-08-20 22:09:37 -0500221 bs = g_malloc0(sizeof(BlockDriverState));
bellardb3380822004-03-14 21:38:54 +0000222 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellardea2384d2004-08-01 21:59:26 +0000223 if (device_name[0] != '\0') {
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100224 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellardea2384d2004-08-01 21:59:26 +0000225 }
Luiz Capitulino28a72822011-09-26 17:43:50 -0300226 bdrv_iostatus_disable(bs);
bellardb3380822004-03-14 21:38:54 +0000227 return bs;
228}
229
bellardea2384d2004-08-01 21:59:26 +0000230BlockDriver *bdrv_find_format(const char *format_name)
231{
232 BlockDriver *drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100233 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
234 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000235 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100236 }
bellardea2384d2004-08-01 21:59:26 +0000237 }
238 return NULL;
239}
240
Markus Armbrustereb852012009-10-27 18:41:44 +0100241static int bdrv_is_whitelisted(BlockDriver *drv)
242{
243 static const char *whitelist[] = {
244 CONFIG_BDRV_WHITELIST
245 };
246 const char **p;
247
248 if (!whitelist[0])
249 return 1; /* no whitelist, anything goes */
250
251 for (p = whitelist; *p; p++) {
252 if (!strcmp(drv->format_name, *p)) {
253 return 1;
254 }
255 }
256 return 0;
257}
258
259BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
260{
261 BlockDriver *drv = bdrv_find_format(format_name);
262 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
263}
264
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200265int bdrv_create(BlockDriver *drv, const char* filename,
266 QEMUOptionParameter *options)
bellardea2384d2004-08-01 21:59:26 +0000267{
268 if (!drv->bdrv_create)
269 return -ENOTSUP;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200270
271 return drv->bdrv_create(filename, options);
bellardea2384d2004-08-01 21:59:26 +0000272}
273
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200274int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
275{
276 BlockDriver *drv;
277
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900278 drv = bdrv_find_protocol(filename);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200279 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000280 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200281 }
282
283 return bdrv_create(drv, filename, options);
284}
285
bellardd5249392004-08-03 21:14:23 +0000286#ifdef _WIN32
bellard95389c82005-12-18 18:28:15 +0000287void get_tmp_filename(char *filename, int size)
bellardd5249392004-08-03 21:14:23 +0000288{
bellard3b9f94e2007-01-07 17:27:07 +0000289 char temp_dir[MAX_PATH];
ths3b46e622007-09-17 08:09:54 +0000290
bellard3b9f94e2007-01-07 17:27:07 +0000291 GetTempPath(MAX_PATH, temp_dir);
292 GetTempFileName(temp_dir, "qem", 0, filename);
bellardd5249392004-08-03 21:14:23 +0000293}
294#else
bellard95389c82005-12-18 18:28:15 +0000295void get_tmp_filename(char *filename, int size)
bellardea2384d2004-08-01 21:59:26 +0000296{
297 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000298 const char *tmpdir;
bellardd5249392004-08-03 21:14:23 +0000299 /* XXX: race condition possible */
aurel320badc1e2008-03-10 00:05:34 +0000300 tmpdir = getenv("TMPDIR");
301 if (!tmpdir)
302 tmpdir = "/tmp";
303 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
bellardea2384d2004-08-01 21:59:26 +0000304 fd = mkstemp(filename);
305 close(fd);
306}
bellardd5249392004-08-03 21:14:23 +0000307#endif
bellardea2384d2004-08-01 21:59:26 +0000308
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200309/*
310 * Detect host devices. By convention, /dev/cdrom[N] is always
311 * recognized as a host CDROM.
312 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200313static BlockDriver *find_hdev_driver(const char *filename)
314{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200315 int score_max = 0, score;
316 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200317
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100318 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200319 if (d->bdrv_probe_device) {
320 score = d->bdrv_probe_device(filename);
321 if (score > score_max) {
322 score_max = score;
323 drv = d;
324 }
325 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200326 }
327
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200328 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200329}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200330
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900331BlockDriver *bdrv_find_protocol(const char *filename)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200332{
333 BlockDriver *drv1;
334 char protocol[128];
335 int len;
336 const char *p;
337
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200338 /* TODO Drivers without bdrv_file_open must be specified explicitly */
339
Christoph Hellwig39508e72010-06-23 12:25:17 +0200340 /*
341 * XXX(hch): we really should not let host device detection
342 * override an explicit protocol specification, but moving this
343 * later breaks access to device names with colons in them.
344 * Thanks to the brain-dead persistent naming schemes on udev-
345 * based Linux systems those actually are quite common.
346 */
347 drv1 = find_hdev_driver(filename);
348 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200349 return drv1;
350 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200351
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000352 if (!path_has_protocol(filename)) {
Christoph Hellwig39508e72010-06-23 12:25:17 +0200353 return bdrv_find_format("file");
354 }
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000355 p = strchr(filename, ':');
356 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200357 len = p - filename;
358 if (len > sizeof(protocol) - 1)
359 len = sizeof(protocol) - 1;
360 memcpy(protocol, filename, len);
361 protocol[len] = '\0';
362 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
363 if (drv1->protocol_name &&
364 !strcmp(drv1->protocol_name, protocol)) {
365 return drv1;
366 }
367 }
368 return NULL;
369}
370
Stefan Weilc98ac352010-07-21 21:51:51 +0200371static int find_image_format(const char *filename, BlockDriver **pdrv)
bellardea2384d2004-08-01 21:59:26 +0000372{
bellard83f64092006-08-01 16:21:11 +0000373 int ret, score, score_max;
bellardea2384d2004-08-01 21:59:26 +0000374 BlockDriver *drv1, *drv;
bellard83f64092006-08-01 16:21:11 +0000375 uint8_t buf[2048];
376 BlockDriverState *bs;
ths3b46e622007-09-17 08:09:54 +0000377
Naphtali Spreif5edb012010-01-17 16:48:13 +0200378 ret = bdrv_file_open(&bs, filename, 0);
Stefan Weilc98ac352010-07-21 21:51:51 +0200379 if (ret < 0) {
380 *pdrv = NULL;
381 return ret;
382 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700383
Kevin Wolf08a00552010-06-01 18:37:31 +0200384 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
385 if (bs->sg || !bdrv_is_inserted(bs)) {
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700386 bdrv_delete(bs);
Stefan Weilc98ac352010-07-21 21:51:51 +0200387 drv = bdrv_find_format("raw");
388 if (!drv) {
389 ret = -ENOENT;
390 }
391 *pdrv = drv;
392 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700393 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700394
bellard83f64092006-08-01 16:21:11 +0000395 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
396 bdrv_delete(bs);
397 if (ret < 0) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200398 *pdrv = NULL;
399 return ret;
bellard83f64092006-08-01 16:21:11 +0000400 }
401
bellardea2384d2004-08-01 21:59:26 +0000402 score_max = 0;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200403 drv = NULL;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100404 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard83f64092006-08-01 16:21:11 +0000405 if (drv1->bdrv_probe) {
406 score = drv1->bdrv_probe(buf, ret, filename);
407 if (score > score_max) {
408 score_max = score;
409 drv = drv1;
410 }
bellardea2384d2004-08-01 21:59:26 +0000411 }
412 }
Stefan Weilc98ac352010-07-21 21:51:51 +0200413 if (!drv) {
414 ret = -ENOENT;
415 }
416 *pdrv = drv;
417 return ret;
bellardea2384d2004-08-01 21:59:26 +0000418}
419
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100420/**
421 * Set the current 'total_sectors' value
422 */
423static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
424{
425 BlockDriver *drv = bs->drv;
426
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700427 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
428 if (bs->sg)
429 return 0;
430
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100431 /* query actual device if possible, otherwise just trust the hint */
432 if (drv->bdrv_getlength) {
433 int64_t length = drv->bdrv_getlength(bs);
434 if (length < 0) {
435 return length;
436 }
437 hint = length >> BDRV_SECTOR_BITS;
438 }
439
440 bs->total_sectors = hint;
441 return 0;
442}
443
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100444/**
445 * Set open flags for a given cache mode
446 *
447 * Return 0 on success, -1 if the cache mode was invalid.
448 */
449int bdrv_parse_cache_flags(const char *mode, int *flags)
450{
451 *flags &= ~BDRV_O_CACHE_MASK;
452
453 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
454 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100455 } else if (!strcmp(mode, "directsync")) {
456 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100457 } else if (!strcmp(mode, "writeback")) {
458 *flags |= BDRV_O_CACHE_WB;
459 } else if (!strcmp(mode, "unsafe")) {
460 *flags |= BDRV_O_CACHE_WB;
461 *flags |= BDRV_O_NO_FLUSH;
462 } else if (!strcmp(mode, "writethrough")) {
463 /* this is the default */
464 } else {
465 return -1;
466 }
467
468 return 0;
469}
470
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200471/*
Kevin Wolf57915332010-04-14 15:24:50 +0200472 * Common part for opening disk images and files
473 */
474static int bdrv_open_common(BlockDriverState *bs, const char *filename,
475 int flags, BlockDriver *drv)
476{
477 int ret, open_flags;
478
479 assert(drv != NULL);
480
Stefan Hajnoczi28dcee12011-09-22 20:14:12 +0100481 trace_bdrv_open_common(bs, filename, flags, drv->format_name);
482
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200483 bs->file = NULL;
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100484 bs->total_sectors = 0;
Kevin Wolf57915332010-04-14 15:24:50 +0200485 bs->encrypted = 0;
486 bs->valid_key = 0;
487 bs->open_flags = flags;
Kevin Wolf57915332010-04-14 15:24:50 +0200488 bs->buffer_alignment = 512;
489
490 pstrcpy(bs->filename, sizeof(bs->filename), filename);
491
492 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
493 return -ENOTSUP;
494 }
495
496 bs->drv = drv;
Anthony Liguori7267c092011-08-20 22:09:37 -0500497 bs->opaque = g_malloc0(drv->instance_size);
Kevin Wolf57915332010-04-14 15:24:50 +0200498
Christoph Hellwiga6599792011-05-17 18:04:06 +0200499 if (flags & BDRV_O_CACHE_WB)
Kevin Wolf57915332010-04-14 15:24:50 +0200500 bs->enable_write_cache = 1;
501
502 /*
503 * Clear flags that are internal to the block layer before opening the
504 * image.
505 */
506 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
507
508 /*
Stefan Weilebabb672011-04-26 10:29:36 +0200509 * Snapshots should be writable.
Kevin Wolf57915332010-04-14 15:24:50 +0200510 */
511 if (bs->is_temporary) {
512 open_flags |= BDRV_O_RDWR;
513 }
514
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200515 /* Open the image, either directly or using a protocol */
516 if (drv->bdrv_file_open) {
517 ret = drv->bdrv_file_open(bs, filename, open_flags);
518 } else {
519 ret = bdrv_file_open(&bs->file, filename, open_flags);
520 if (ret >= 0) {
521 ret = drv->bdrv_open(bs, open_flags);
522 }
523 }
524
Kevin Wolf57915332010-04-14 15:24:50 +0200525 if (ret < 0) {
526 goto free_and_fail;
527 }
528
529 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100530
531 ret = refresh_total_sectors(bs, bs->total_sectors);
532 if (ret < 0) {
533 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200534 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100535
Kevin Wolf57915332010-04-14 15:24:50 +0200536#ifndef _WIN32
537 if (bs->is_temporary) {
538 unlink(filename);
539 }
540#endif
541 return 0;
542
543free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200544 if (bs->file) {
545 bdrv_delete(bs->file);
546 bs->file = NULL;
547 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500548 g_free(bs->opaque);
Kevin Wolf57915332010-04-14 15:24:50 +0200549 bs->opaque = NULL;
550 bs->drv = NULL;
551 return ret;
552}
553
554/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200555 * Opens a file using a protocol (file, host_device, nbd, ...)
556 */
bellard83f64092006-08-01 16:21:11 +0000557int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000558{
bellard83f64092006-08-01 16:21:11 +0000559 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200560 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000561 int ret;
562
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900563 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200564 if (!drv) {
565 return -ENOENT;
566 }
567
bellard83f64092006-08-01 16:21:11 +0000568 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200569 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000570 if (ret < 0) {
571 bdrv_delete(bs);
572 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000573 }
aliguori71d07702009-03-03 17:37:16 +0000574 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000575 *pbs = bs;
576 return 0;
bellardea2384d2004-08-01 21:59:26 +0000577}
bellardfc01f7e2003-06-30 10:03:06 +0000578
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200579/*
580 * Opens a disk image (raw, qcow2, vmdk, ...)
581 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200582int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
583 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000584{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200585 int ret;
bellard712e7872005-04-28 21:09:32 +0000586
bellard83f64092006-08-01 16:21:11 +0000587 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000588 BlockDriverState *bs1;
589 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000590 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200591 BlockDriver *bdrv_qcow2;
592 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200593 char tmp_filename[PATH_MAX];
594 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000595
bellardea2384d2004-08-01 21:59:26 +0000596 /* if snapshot, we create a temporary backing file and open it
597 instead of opening 'filename' directly */
598
599 /* if there is a backing file, use it */
600 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200601 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000602 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000603 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000604 return ret;
bellardea2384d2004-08-01 21:59:26 +0000605 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200606 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000607
608 if (bs1->drv && bs1->drv->protocol_name)
609 is_protocol = 1;
610
bellardea2384d2004-08-01 21:59:26 +0000611 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000612
bellardea2384d2004-08-01 21:59:26 +0000613 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
aliguori7c96d462008-09-12 17:54:13 +0000614
615 /* Real path is meaningless for protocols */
616 if (is_protocol)
617 snprintf(backing_filename, sizeof(backing_filename),
618 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000619 else if (!realpath(filename, backing_filename))
620 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000621
Kevin Wolf91a073a2009-05-27 14:48:06 +0200622 bdrv_qcow2 = bdrv_find_format("qcow2");
623 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
624
Jes Sorensen3e829902010-05-27 16:20:30 +0200625 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200626 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
627 if (drv) {
628 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
629 drv->format_name);
630 }
631
632 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200633 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000634 if (ret < 0) {
635 return ret;
bellardea2384d2004-08-01 21:59:26 +0000636 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200637
bellardea2384d2004-08-01 21:59:26 +0000638 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200639 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000640 bs->is_temporary = 1;
641 }
bellard712e7872005-04-28 21:09:32 +0000642
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200643 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200644 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200645 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000646 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100647
aliguori51d7c002009-03-05 23:00:29 +0000648 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000649 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000650 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200651
652 /* Open the image */
653 ret = bdrv_open_common(bs, filename, flags, drv);
654 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100655 goto unlink_and_fail;
656 }
657
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200658 /* If there is a backing file, use it */
659 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
660 char backing_filename[PATH_MAX];
661 int back_flags;
662 BlockDriver *back_drv = NULL;
663
664 bs->backing_hd = bdrv_new("");
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000665
666 if (path_has_protocol(bs->backing_file)) {
667 pstrcpy(backing_filename, sizeof(backing_filename),
668 bs->backing_file);
669 } else {
670 path_combine(backing_filename, sizeof(backing_filename),
671 filename, bs->backing_file);
672 }
673
674 if (bs->backing_format[0] != '\0') {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200675 back_drv = bdrv_find_format(bs->backing_format);
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000676 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200677
678 /* backing files always opened read-only */
679 back_flags =
680 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
681
682 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
683 if (ret < 0) {
684 bdrv_close(bs);
685 return ret;
686 }
687 if (bs->is_temporary) {
688 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
689 } else {
690 /* base image inherits from "parent" */
691 bs->backing_hd->keep_read_only = bs->keep_read_only;
692 }
693 }
694
695 if (!bdrv_key_required(bs)) {
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200696 bdrv_dev_change_media_cb(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200697 }
698
699 return 0;
700
701unlink_and_fail:
702 if (bs->is_temporary) {
703 unlink(filename);
704 }
705 return ret;
706}
707
bellardfc01f7e2003-06-30 10:03:06 +0000708void bdrv_close(BlockDriverState *bs)
709{
bellard19cb3732006-08-19 11:45:59 +0000710 if (bs->drv) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200711 if (bs == bs_snapshots) {
712 bs_snapshots = NULL;
713 }
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100714 if (bs->backing_hd) {
bellardea2384d2004-08-01 21:59:26 +0000715 bdrv_delete(bs->backing_hd);
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100716 bs->backing_hd = NULL;
717 }
bellardea2384d2004-08-01 21:59:26 +0000718 bs->drv->bdrv_close(bs);
Anthony Liguori7267c092011-08-20 22:09:37 -0500719 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +0000720#ifdef _WIN32
721 if (bs->is_temporary) {
722 unlink(bs->filename);
723 }
bellard67b915a2004-03-31 23:37:16 +0000724#endif
bellardea2384d2004-08-01 21:59:26 +0000725 bs->opaque = NULL;
726 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +0000727
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200728 if (bs->file != NULL) {
729 bdrv_close(bs->file);
730 }
731
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200732 bdrv_dev_change_media_cb(bs, false);
bellardb3380822004-03-14 21:38:54 +0000733 }
734}
735
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +0900736void bdrv_close_all(void)
737{
738 BlockDriverState *bs;
739
740 QTAILQ_FOREACH(bs, &bdrv_states, list) {
741 bdrv_close(bs);
742 }
743}
744
Ryan Harperd22b2f42011-03-29 20:51:47 -0500745/* make a BlockDriverState anonymous by removing from bdrv_state list.
746 Also, NULL terminate the device_name to prevent double remove */
747void bdrv_make_anon(BlockDriverState *bs)
748{
749 if (bs->device_name[0] != '\0') {
750 QTAILQ_REMOVE(&bdrv_states, bs, list);
751 }
752 bs->device_name[0] = '\0';
753}
754
bellardb3380822004-03-14 21:38:54 +0000755void bdrv_delete(BlockDriverState *bs)
756{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200757 assert(!bs->dev);
Markus Armbruster18846de2010-06-29 16:58:30 +0200758
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100759 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -0500760 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +0000761
bellardb3380822004-03-14 21:38:54 +0000762 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200763 if (bs->file != NULL) {
764 bdrv_delete(bs->file);
765 }
766
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200767 assert(bs != bs_snapshots);
Anthony Liguori7267c092011-08-20 22:09:37 -0500768 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +0000769}
770
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200771int bdrv_attach_dev(BlockDriverState *bs, void *dev)
772/* TODO change to DeviceState *dev when all users are qdevified */
Markus Armbruster18846de2010-06-29 16:58:30 +0200773{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200774 if (bs->dev) {
Markus Armbruster18846de2010-06-29 16:58:30 +0200775 return -EBUSY;
776 }
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200777 bs->dev = dev;
Luiz Capitulino28a72822011-09-26 17:43:50 -0300778 bdrv_iostatus_reset(bs);
Markus Armbruster18846de2010-06-29 16:58:30 +0200779 return 0;
780}
781
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200782/* TODO qdevified devices don't use this, remove when devices are qdevified */
783void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
Markus Armbruster18846de2010-06-29 16:58:30 +0200784{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200785 if (bdrv_attach_dev(bs, dev) < 0) {
786 abort();
787 }
788}
789
790void bdrv_detach_dev(BlockDriverState *bs, void *dev)
791/* TODO change to DeviceState *dev when all users are qdevified */
792{
793 assert(bs->dev == dev);
794 bs->dev = NULL;
Markus Armbruster0e49de52011-08-03 15:07:41 +0200795 bs->dev_ops = NULL;
796 bs->dev_opaque = NULL;
Markus Armbruster29e05f22011-09-06 18:58:57 +0200797 bs->buffer_alignment = 512;
Markus Armbruster18846de2010-06-29 16:58:30 +0200798}
799
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200800/* TODO change to return DeviceState * when all users are qdevified */
801void *bdrv_get_attached_dev(BlockDriverState *bs)
Markus Armbruster18846de2010-06-29 16:58:30 +0200802{
Markus Armbrusterfa879d62011-08-03 15:07:40 +0200803 return bs->dev;
Markus Armbruster18846de2010-06-29 16:58:30 +0200804}
805
Markus Armbruster0e49de52011-08-03 15:07:41 +0200806void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
807 void *opaque)
808{
809 bs->dev_ops = ops;
810 bs->dev_opaque = opaque;
Markus Armbruster2c6942f2011-09-06 18:58:51 +0200811 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
812 bs_snapshots = NULL;
813 }
Markus Armbruster0e49de52011-08-03 15:07:41 +0200814}
815
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200816static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
Markus Armbruster0e49de52011-08-03 15:07:41 +0200817{
Markus Armbruster145feb12011-08-03 15:07:42 +0200818 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200819 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
Markus Armbruster145feb12011-08-03 15:07:42 +0200820 }
821}
822
Markus Armbruster2c6942f2011-09-06 18:58:51 +0200823bool bdrv_dev_has_removable_media(BlockDriverState *bs)
824{
825 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
826}
827
Markus Armbrustere4def802011-09-06 18:58:53 +0200828bool bdrv_dev_is_tray_open(BlockDriverState *bs)
829{
830 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
831 return bs->dev_ops->is_tray_open(bs->dev_opaque);
832 }
833 return false;
834}
835
Markus Armbruster145feb12011-08-03 15:07:42 +0200836static void bdrv_dev_resize_cb(BlockDriverState *bs)
837{
838 if (bs->dev_ops && bs->dev_ops->resize_cb) {
839 bs->dev_ops->resize_cb(bs->dev_opaque);
Markus Armbruster0e49de52011-08-03 15:07:41 +0200840 }
841}
842
Markus Armbrusterf1076392011-09-06 18:58:46 +0200843bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
844{
845 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
846 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
847 }
848 return false;
849}
850
aliguorie97fc192009-04-21 23:11:50 +0000851/*
852 * Run consistency checks on an image
853 *
Kevin Wolfe076f332010-06-29 11:43:13 +0200854 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +0200855 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +0200856 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +0000857 */
Kevin Wolfe076f332010-06-29 11:43:13 +0200858int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
aliguorie97fc192009-04-21 23:11:50 +0000859{
860 if (bs->drv->bdrv_check == NULL) {
861 return -ENOTSUP;
862 }
863
Kevin Wolfe076f332010-06-29 11:43:13 +0200864 memset(res, 0, sizeof(*res));
Kevin Wolf9ac228e2010-06-29 12:37:54 +0200865 return bs->drv->bdrv_check(bs, res);
aliguorie97fc192009-04-21 23:11:50 +0000866}
867
Kevin Wolf8a426612010-07-16 17:17:01 +0200868#define COMMIT_BUF_SECTORS 2048
869
bellard33e39632003-07-06 17:15:21 +0000870/* commit COW file into the raw image */
871int bdrv_commit(BlockDriverState *bs)
872{
bellard19cb3732006-08-19 11:45:59 +0000873 BlockDriver *drv = bs->drv;
Kevin Wolfee181192010-08-05 13:05:22 +0200874 BlockDriver *backing_drv;
Kevin Wolf8a426612010-07-16 17:17:01 +0200875 int64_t sector, total_sectors;
876 int n, ro, open_flags;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200877 int ret = 0, rw_ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +0200878 uint8_t *buf;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200879 char filename[1024];
880 BlockDriverState *bs_rw, *bs_ro;
bellard33e39632003-07-06 17:15:21 +0000881
bellard19cb3732006-08-19 11:45:59 +0000882 if (!drv)
883 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200884
885 if (!bs->backing_hd) {
886 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +0000887 }
888
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200889 if (bs->backing_hd->keep_read_only) {
890 return -EACCES;
891 }
Kevin Wolfee181192010-08-05 13:05:22 +0200892
893 backing_drv = bs->backing_hd->drv;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200894 ro = bs->backing_hd->read_only;
895 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
896 open_flags = bs->backing_hd->open_flags;
897
898 if (ro) {
899 /* re-open as RW */
900 bdrv_delete(bs->backing_hd);
901 bs->backing_hd = NULL;
902 bs_rw = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200903 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
904 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200905 if (rw_ret < 0) {
906 bdrv_delete(bs_rw);
907 /* try to re-open read-only */
908 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200909 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
910 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200911 if (ret < 0) {
912 bdrv_delete(bs_ro);
913 /* drive not functional anymore */
914 bs->drv = NULL;
915 return ret;
916 }
917 bs->backing_hd = bs_ro;
918 return rw_ret;
919 }
920 bs->backing_hd = bs_rw;
bellard33e39632003-07-06 17:15:21 +0000921 }
bellardea2384d2004-08-01 21:59:26 +0000922
Jan Kiszka6ea44302009-11-30 18:21:19 +0100923 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Anthony Liguori7267c092011-08-20 22:09:37 -0500924 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +0000925
Kevin Wolf8a426612010-07-16 17:17:01 +0200926 for (sector = 0; sector < total_sectors; sector += n) {
927 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
928
929 if (bdrv_read(bs, sector, buf, n) != 0) {
930 ret = -EIO;
931 goto ro_cleanup;
932 }
933
934 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
935 ret = -EIO;
936 goto ro_cleanup;
937 }
bellardea2384d2004-08-01 21:59:26 +0000938 }
939 }
bellard95389c82005-12-18 18:28:15 +0000940
Christoph Hellwig1d449522010-01-17 12:32:30 +0100941 if (drv->bdrv_make_empty) {
942 ret = drv->bdrv_make_empty(bs);
943 bdrv_flush(bs);
944 }
bellard95389c82005-12-18 18:28:15 +0000945
Christoph Hellwig3f5075a2010-01-12 13:49:23 +0100946 /*
947 * Make sure all data we wrote to the backing device is actually
948 * stable on disk.
949 */
950 if (bs->backing_hd)
951 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200952
953ro_cleanup:
Anthony Liguori7267c092011-08-20 22:09:37 -0500954 g_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200955
956 if (ro) {
957 /* re-open as RO */
958 bdrv_delete(bs->backing_hd);
959 bs->backing_hd = NULL;
960 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200961 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
962 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200963 if (ret < 0) {
964 bdrv_delete(bs_ro);
965 /* drive not functional anymore */
966 bs->drv = NULL;
967 return ret;
968 }
969 bs->backing_hd = bs_ro;
970 bs->backing_hd->keep_read_only = 0;
971 }
972
Christoph Hellwig1d449522010-01-17 12:32:30 +0100973 return ret;
bellard33e39632003-07-06 17:15:21 +0000974}
975
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +0200976void bdrv_commit_all(void)
977{
978 BlockDriverState *bs;
979
980 QTAILQ_FOREACH(bs, &bdrv_states, list) {
981 bdrv_commit(bs);
982 }
983}
984
Kevin Wolf756e6732010-01-12 12:55:17 +0100985/*
986 * Return values:
987 * 0 - success
988 * -EINVAL - backing format specified, but no file
989 * -ENOSPC - can't update the backing file because no space is left in the
990 * image file header
991 * -ENOTSUP - format driver doesn't support changing the backing file
992 */
993int bdrv_change_backing_file(BlockDriverState *bs,
994 const char *backing_file, const char *backing_fmt)
995{
996 BlockDriver *drv = bs->drv;
997
998 if (drv->bdrv_change_backing_file != NULL) {
999 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1000 } else {
1001 return -ENOTSUP;
1002 }
1003}
1004
aliguori71d07702009-03-03 17:37:16 +00001005static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1006 size_t size)
1007{
1008 int64_t len;
1009
1010 if (!bdrv_is_inserted(bs))
1011 return -ENOMEDIUM;
1012
1013 if (bs->growable)
1014 return 0;
1015
1016 len = bdrv_getlength(bs);
1017
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02001018 if (offset < 0)
1019 return -EIO;
1020
1021 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +00001022 return -EIO;
1023
1024 return 0;
1025}
1026
1027static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1028 int nb_sectors)
1029{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001030 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1031 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +00001032}
1033
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001034static inline bool bdrv_has_async_rw(BlockDriver *drv)
1035{
1036 return drv->bdrv_co_readv != bdrv_co_readv_em
1037 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1038}
1039
1040static inline bool bdrv_has_async_flush(BlockDriver *drv)
1041{
1042 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1043}
1044
bellard19cb3732006-08-19 11:45:59 +00001045/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +00001046int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001047 uint8_t *buf, int nb_sectors)
1048{
bellardea2384d2004-08-01 21:59:26 +00001049 BlockDriver *drv = bs->drv;
1050
bellard19cb3732006-08-19 11:45:59 +00001051 if (!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_readv(bs, sector_num, nb_sectors, &qiov);
1063 }
1064
aliguori71d07702009-03-03 17:37:16 +00001065 if (bdrv_check_request(bs, sector_num, nb_sectors))
1066 return -EIO;
bellardb3380822004-03-14 21:38:54 +00001067
aliguorieda578e2009-03-12 19:57:16 +00001068 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
bellardfc01f7e2003-06-30 10:03:06 +00001069}
1070
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001071static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001072 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001073{
1074 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001075 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001076
Jan Kiszka6ea44302009-11-30 18:21:19 +01001077 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +01001078 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001079
1080 for (; start <= end; start++) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01001081 idx = start / (sizeof(unsigned long) * 8);
1082 bit = start % (sizeof(unsigned long) * 8);
1083 val = bs->dirty_bitmap[idx];
1084 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001085 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001086 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001087 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +02001088 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001089 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001090 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02001091 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02001092 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +02001093 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01001094 }
1095 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001096 }
1097}
1098
ths5fafdf22007-09-16 21:08:06 +00001099/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +00001100 -EIO generic I/O error (may happen for all errors)
1101 -ENOMEDIUM No media inserted.
1102 -EINVAL Invalid sector number or nb_sectors
1103 -EACCES Trying to write a read-only device
1104*/
ths5fafdf22007-09-16 21:08:06 +00001105int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00001106 const uint8_t *buf, int nb_sectors)
1107{
bellard83f64092006-08-01 16:21:11 +00001108 BlockDriver *drv = bs->drv;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001109
bellard19cb3732006-08-19 11:45:59 +00001110 if (!bs->drv)
1111 return -ENOMEDIUM;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001112
1113 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1114 QEMUIOVector qiov;
1115 struct iovec iov = {
1116 .iov_base = (void *)buf,
1117 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1118 };
1119
1120 qemu_iovec_init_external(&qiov, &iov, 1);
1121 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1122 }
1123
bellard0849bf02003-06-30 23:17:31 +00001124 if (bs->read_only)
bellard19cb3732006-08-19 11:45:59 +00001125 return -EACCES;
aliguori71d07702009-03-03 17:37:16 +00001126 if (bdrv_check_request(bs, sector_num, nb_sectors))
1127 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001128
Jan Kiszkac6d22832009-11-30 18:21:20 +01001129 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001130 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1131 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001132
Kevin Wolf294cc352010-04-28 14:34:01 +02001133 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1134 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1135 }
1136
aliguori42fb2802009-01-15 20:43:39 +00001137 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
bellard83f64092006-08-01 16:21:11 +00001138}
1139
aliguorieda578e2009-03-12 19:57:16 +00001140int bdrv_pread(BlockDriverState *bs, int64_t offset,
1141 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001142{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001143 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001144 int len, nb_sectors, count;
1145 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001146 int ret;
bellard83f64092006-08-01 16:21:11 +00001147
1148 count = count1;
1149 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001150 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001151 if (len > count)
1152 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001153 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001154 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001155 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1156 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001157 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00001158 count -= len;
1159 if (count == 0)
1160 return count1;
1161 sector_num++;
1162 buf += len;
1163 }
1164
1165 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001166 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001167 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001168 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1169 return ret;
bellard83f64092006-08-01 16:21:11 +00001170 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001171 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001172 buf += len;
1173 count -= len;
1174 }
1175
1176 /* add data from the last sector */
1177 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001178 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1179 return ret;
bellard83f64092006-08-01 16:21:11 +00001180 memcpy(buf, tmp_buf, count);
1181 }
1182 return count1;
1183}
1184
aliguorieda578e2009-03-12 19:57:16 +00001185int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1186 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001187{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001188 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001189 int len, nb_sectors, count;
1190 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001191 int ret;
bellard83f64092006-08-01 16:21:11 +00001192
1193 count = count1;
1194 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001195 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001196 if (len > count)
1197 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001198 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001199 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001200 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1201 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001202 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001203 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1204 return ret;
bellard83f64092006-08-01 16:21:11 +00001205 count -= len;
1206 if (count == 0)
1207 return count1;
1208 sector_num++;
1209 buf += len;
1210 }
1211
1212 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001213 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001214 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001215 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1216 return ret;
bellard83f64092006-08-01 16:21:11 +00001217 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001218 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001219 buf += len;
1220 count -= len;
1221 }
1222
1223 /* add data from the last sector */
1224 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001225 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1226 return ret;
bellard83f64092006-08-01 16:21:11 +00001227 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001228 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1229 return ret;
bellard83f64092006-08-01 16:21:11 +00001230 }
1231 return count1;
1232}
bellard83f64092006-08-01 16:21:11 +00001233
Kevin Wolff08145f2010-06-16 16:38:15 +02001234/*
1235 * Writes to the file and ensures that no writes are reordered across this
1236 * request (acts as a barrier)
1237 *
1238 * Returns 0 on success, -errno in error cases.
1239 */
1240int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1241 const void *buf, int count)
1242{
1243 int ret;
1244
1245 ret = bdrv_pwrite(bs, offset, buf, count);
1246 if (ret < 0) {
1247 return ret;
1248 }
1249
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001250 /* No flush needed for cache modes that use O_DSYNC */
1251 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
Kevin Wolff08145f2010-06-16 16:38:15 +02001252 bdrv_flush(bs);
1253 }
1254
1255 return 0;
1256}
1257
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01001258/*
1259 * Handle a read request in coroutine context
1260 */
1261static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
1262 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
Kevin Wolfda1fa912011-07-14 17:27:13 +02001263{
1264 BlockDriver *drv = bs->drv;
1265
Kevin Wolfda1fa912011-07-14 17:27:13 +02001266 if (!drv) {
1267 return -ENOMEDIUM;
1268 }
1269 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1270 return -EIO;
1271 }
1272
1273 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1274}
1275
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01001276int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
Kevin Wolfda1fa912011-07-14 17:27:13 +02001277 int nb_sectors, QEMUIOVector *qiov)
1278{
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01001279 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
Kevin Wolfda1fa912011-07-14 17:27:13 +02001280
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01001281 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov);
1282}
1283
1284/*
1285 * Handle a write request in coroutine context
1286 */
1287static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
1288 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1289{
1290 BlockDriver *drv = bs->drv;
Kevin Wolfda1fa912011-07-14 17:27:13 +02001291
1292 if (!bs->drv) {
1293 return -ENOMEDIUM;
1294 }
1295 if (bs->read_only) {
1296 return -EACCES;
1297 }
1298 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1299 return -EIO;
1300 }
1301
1302 if (bs->dirty_bitmap) {
1303 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1304 }
1305
1306 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1307 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1308 }
1309
1310 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1311}
1312
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01001313int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1314 int nb_sectors, QEMUIOVector *qiov)
1315{
1316 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1317
1318 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov);
1319}
1320
bellard83f64092006-08-01 16:21:11 +00001321/**
bellard83f64092006-08-01 16:21:11 +00001322 * Truncate file to 'offset' bytes (needed only for file protocols)
1323 */
1324int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1325{
1326 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001327 int ret;
bellard83f64092006-08-01 16:21:11 +00001328 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001329 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00001330 if (!drv->bdrv_truncate)
1331 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02001332 if (bs->read_only)
1333 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02001334 if (bdrv_in_use(bs))
1335 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001336 ret = drv->bdrv_truncate(bs, offset);
1337 if (ret == 0) {
1338 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Markus Armbruster145feb12011-08-03 15:07:42 +02001339 bdrv_dev_resize_cb(bs);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001340 }
1341 return ret;
bellard83f64092006-08-01 16:21:11 +00001342}
1343
1344/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08001345 * Length of a allocated file in bytes. Sparse files are counted by actual
1346 * allocated space. Return < 0 if error or unknown.
1347 */
1348int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1349{
1350 BlockDriver *drv = bs->drv;
1351 if (!drv) {
1352 return -ENOMEDIUM;
1353 }
1354 if (drv->bdrv_get_allocated_file_size) {
1355 return drv->bdrv_get_allocated_file_size(bs);
1356 }
1357 if (bs->file) {
1358 return bdrv_get_allocated_file_size(bs->file);
1359 }
1360 return -ENOTSUP;
1361}
1362
1363/**
bellard83f64092006-08-01 16:21:11 +00001364 * Length of a file in bytes. Return < 0 if error or unknown.
1365 */
1366int64_t bdrv_getlength(BlockDriverState *bs)
1367{
1368 BlockDriver *drv = bs->drv;
1369 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001370 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001371
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001372 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001373 if (drv->bdrv_getlength) {
1374 return drv->bdrv_getlength(bs);
1375 }
bellard83f64092006-08-01 16:21:11 +00001376 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001377 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00001378}
1379
bellard19cb3732006-08-19 11:45:59 +00001380/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00001381void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00001382{
bellard19cb3732006-08-19 11:45:59 +00001383 int64_t length;
1384 length = bdrv_getlength(bs);
1385 if (length < 0)
1386 length = 0;
1387 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01001388 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00001389 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00001390}
bellardcf989512004-02-16 21:56:36 +00001391
aliguorif3d54fc2008-11-25 21:50:24 +00001392struct partition {
1393 uint8_t boot_ind; /* 0x80 - active */
1394 uint8_t head; /* starting head */
1395 uint8_t sector; /* starting sector */
1396 uint8_t cyl; /* starting cylinder */
1397 uint8_t sys_ind; /* What partition type */
1398 uint8_t end_head; /* end head */
1399 uint8_t end_sector; /* end sector */
1400 uint8_t end_cyl; /* end cylinder */
1401 uint32_t start_sect; /* starting sector counting from 0 */
1402 uint32_t nr_sects; /* nr of sectors in partition */
Stefan Weil541dc0d2011-08-31 12:38:01 +02001403} QEMU_PACKED;
aliguorif3d54fc2008-11-25 21:50:24 +00001404
1405/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1406static int guess_disk_lchs(BlockDriverState *bs,
1407 int *pcylinders, int *pheads, int *psectors)
1408{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001409 uint8_t buf[BDRV_SECTOR_SIZE];
aliguorif3d54fc2008-11-25 21:50:24 +00001410 int ret, i, heads, sectors, cylinders;
1411 struct partition *p;
1412 uint32_t nr_sects;
blueswir1a38131b2008-12-05 17:56:40 +00001413 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001414
1415 bdrv_get_geometry(bs, &nb_sectors);
1416
1417 ret = bdrv_read(bs, 0, buf, 1);
1418 if (ret < 0)
1419 return -1;
1420 /* test msdos magic */
1421 if (buf[510] != 0x55 || buf[511] != 0xaa)
1422 return -1;
1423 for(i = 0; i < 4; i++) {
1424 p = ((struct partition *)(buf + 0x1be)) + i;
1425 nr_sects = le32_to_cpu(p->nr_sects);
1426 if (nr_sects && p->end_head) {
1427 /* We make the assumption that the partition terminates on
1428 a cylinder boundary */
1429 heads = p->end_head + 1;
1430 sectors = p->end_sector & 63;
1431 if (sectors == 0)
1432 continue;
1433 cylinders = nb_sectors / (heads * sectors);
1434 if (cylinders < 1 || cylinders > 16383)
1435 continue;
1436 *pheads = heads;
1437 *psectors = sectors;
1438 *pcylinders = cylinders;
1439#if 0
1440 printf("guessed geometry: LCHS=%d %d %d\n",
1441 cylinders, heads, sectors);
1442#endif
1443 return 0;
1444 }
1445 }
1446 return -1;
1447}
1448
1449void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1450{
1451 int translation, lba_detected = 0;
1452 int cylinders, heads, secs;
blueswir1a38131b2008-12-05 17:56:40 +00001453 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001454
1455 /* if a geometry hint is available, use it */
1456 bdrv_get_geometry(bs, &nb_sectors);
1457 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1458 translation = bdrv_get_translation_hint(bs);
1459 if (cylinders != 0) {
1460 *pcyls = cylinders;
1461 *pheads = heads;
1462 *psecs = secs;
1463 } else {
1464 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1465 if (heads > 16) {
1466 /* if heads > 16, it means that a BIOS LBA
1467 translation was active, so the default
1468 hardware geometry is OK */
1469 lba_detected = 1;
1470 goto default_geometry;
1471 } else {
1472 *pcyls = cylinders;
1473 *pheads = heads;
1474 *psecs = secs;
1475 /* disable any translation to be in sync with
1476 the logical geometry */
1477 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1478 bdrv_set_translation_hint(bs,
1479 BIOS_ATA_TRANSLATION_NONE);
1480 }
1481 }
1482 } else {
1483 default_geometry:
1484 /* if no geometry, use a standard physical disk geometry */
1485 cylinders = nb_sectors / (16 * 63);
1486
1487 if (cylinders > 16383)
1488 cylinders = 16383;
1489 else if (cylinders < 2)
1490 cylinders = 2;
1491 *pcyls = cylinders;
1492 *pheads = 16;
1493 *psecs = 63;
1494 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1495 if ((*pcyls * *pheads) <= 131072) {
1496 bdrv_set_translation_hint(bs,
1497 BIOS_ATA_TRANSLATION_LARGE);
1498 } else {
1499 bdrv_set_translation_hint(bs,
1500 BIOS_ATA_TRANSLATION_LBA);
1501 }
1502 }
1503 }
1504 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1505 }
1506}
1507
ths5fafdf22007-09-16 21:08:06 +00001508void bdrv_set_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001509 int cyls, int heads, int secs)
1510{
1511 bs->cyls = cyls;
1512 bs->heads = heads;
1513 bs->secs = secs;
1514}
1515
bellard46d47672004-11-16 01:45:27 +00001516void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1517{
1518 bs->translation = translation;
1519}
1520
ths5fafdf22007-09-16 21:08:06 +00001521void bdrv_get_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001522 int *pcyls, int *pheads, int *psecs)
1523{
1524 *pcyls = bs->cyls;
1525 *pheads = bs->heads;
1526 *psecs = bs->secs;
1527}
1528
Blue Swirl5bbdbb42011-02-12 20:43:32 +00001529/* Recognize floppy formats */
1530typedef struct FDFormat {
1531 FDriveType drive;
1532 uint8_t last_sect;
1533 uint8_t max_track;
1534 uint8_t max_head;
1535} FDFormat;
1536
1537static const FDFormat fd_formats[] = {
1538 /* First entry is default format */
1539 /* 1.44 MB 3"1/2 floppy disks */
1540 { FDRIVE_DRV_144, 18, 80, 1, },
1541 { FDRIVE_DRV_144, 20, 80, 1, },
1542 { FDRIVE_DRV_144, 21, 80, 1, },
1543 { FDRIVE_DRV_144, 21, 82, 1, },
1544 { FDRIVE_DRV_144, 21, 83, 1, },
1545 { FDRIVE_DRV_144, 22, 80, 1, },
1546 { FDRIVE_DRV_144, 23, 80, 1, },
1547 { FDRIVE_DRV_144, 24, 80, 1, },
1548 /* 2.88 MB 3"1/2 floppy disks */
1549 { FDRIVE_DRV_288, 36, 80, 1, },
1550 { FDRIVE_DRV_288, 39, 80, 1, },
1551 { FDRIVE_DRV_288, 40, 80, 1, },
1552 { FDRIVE_DRV_288, 44, 80, 1, },
1553 { FDRIVE_DRV_288, 48, 80, 1, },
1554 /* 720 kB 3"1/2 floppy disks */
1555 { FDRIVE_DRV_144, 9, 80, 1, },
1556 { FDRIVE_DRV_144, 10, 80, 1, },
1557 { FDRIVE_DRV_144, 10, 82, 1, },
1558 { FDRIVE_DRV_144, 10, 83, 1, },
1559 { FDRIVE_DRV_144, 13, 80, 1, },
1560 { FDRIVE_DRV_144, 14, 80, 1, },
1561 /* 1.2 MB 5"1/4 floppy disks */
1562 { FDRIVE_DRV_120, 15, 80, 1, },
1563 { FDRIVE_DRV_120, 18, 80, 1, },
1564 { FDRIVE_DRV_120, 18, 82, 1, },
1565 { FDRIVE_DRV_120, 18, 83, 1, },
1566 { FDRIVE_DRV_120, 20, 80, 1, },
1567 /* 720 kB 5"1/4 floppy disks */
1568 { FDRIVE_DRV_120, 9, 80, 1, },
1569 { FDRIVE_DRV_120, 11, 80, 1, },
1570 /* 360 kB 5"1/4 floppy disks */
1571 { FDRIVE_DRV_120, 9, 40, 1, },
1572 { FDRIVE_DRV_120, 9, 40, 0, },
1573 { FDRIVE_DRV_120, 10, 41, 1, },
1574 { FDRIVE_DRV_120, 10, 42, 1, },
1575 /* 320 kB 5"1/4 floppy disks */
1576 { FDRIVE_DRV_120, 8, 40, 1, },
1577 { FDRIVE_DRV_120, 8, 40, 0, },
1578 /* 360 kB must match 5"1/4 better than 3"1/2... */
1579 { FDRIVE_DRV_144, 9, 80, 0, },
1580 /* end */
1581 { FDRIVE_DRV_NONE, -1, -1, 0, },
1582};
1583
1584void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1585 int *max_track, int *last_sect,
1586 FDriveType drive_in, FDriveType *drive)
1587{
1588 const FDFormat *parse;
1589 uint64_t nb_sectors, size;
1590 int i, first_match, match;
1591
1592 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1593 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1594 /* User defined disk */
1595 } else {
1596 bdrv_get_geometry(bs, &nb_sectors);
1597 match = -1;
1598 first_match = -1;
1599 for (i = 0; ; i++) {
1600 parse = &fd_formats[i];
1601 if (parse->drive == FDRIVE_DRV_NONE) {
1602 break;
1603 }
1604 if (drive_in == parse->drive ||
1605 drive_in == FDRIVE_DRV_NONE) {
1606 size = (parse->max_head + 1) * parse->max_track *
1607 parse->last_sect;
1608 if (nb_sectors == size) {
1609 match = i;
1610 break;
1611 }
1612 if (first_match == -1) {
1613 first_match = i;
1614 }
1615 }
1616 }
1617 if (match == -1) {
1618 if (first_match == -1) {
1619 match = 1;
1620 } else {
1621 match = first_match;
1622 }
1623 parse = &fd_formats[match];
1624 }
1625 *nb_heads = parse->max_head + 1;
1626 *max_track = parse->max_track;
1627 *last_sect = parse->last_sect;
1628 *drive = parse->drive;
1629 }
1630}
1631
bellard46d47672004-11-16 01:45:27 +00001632int bdrv_get_translation_hint(BlockDriverState *bs)
1633{
1634 return bs->translation;
1635}
1636
Markus Armbrusterabd7f682010-06-02 18:55:17 +02001637void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1638 BlockErrorAction on_write_error)
1639{
1640 bs->on_read_error = on_read_error;
1641 bs->on_write_error = on_write_error;
1642}
1643
1644BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1645{
1646 return is_read ? bs->on_read_error : bs->on_write_error;
1647}
1648
bellardb3380822004-03-14 21:38:54 +00001649int bdrv_is_read_only(BlockDriverState *bs)
1650{
1651 return bs->read_only;
1652}
1653
ths985a03b2007-12-24 16:10:43 +00001654int bdrv_is_sg(BlockDriverState *bs)
1655{
1656 return bs->sg;
1657}
1658
Christoph Hellwige900a7b2009-09-04 19:01:15 +02001659int bdrv_enable_write_cache(BlockDriverState *bs)
1660{
1661 return bs->enable_write_cache;
1662}
1663
bellardea2384d2004-08-01 21:59:26 +00001664int bdrv_is_encrypted(BlockDriverState *bs)
1665{
1666 if (bs->backing_hd && bs->backing_hd->encrypted)
1667 return 1;
1668 return bs->encrypted;
1669}
1670
aliguoric0f4ce72009-03-05 23:01:01 +00001671int bdrv_key_required(BlockDriverState *bs)
1672{
1673 BlockDriverState *backing_hd = bs->backing_hd;
1674
1675 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1676 return 1;
1677 return (bs->encrypted && !bs->valid_key);
1678}
1679
bellardea2384d2004-08-01 21:59:26 +00001680int bdrv_set_key(BlockDriverState *bs, const char *key)
1681{
1682 int ret;
1683 if (bs->backing_hd && bs->backing_hd->encrypted) {
1684 ret = bdrv_set_key(bs->backing_hd, key);
1685 if (ret < 0)
1686 return ret;
1687 if (!bs->encrypted)
1688 return 0;
1689 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02001690 if (!bs->encrypted) {
1691 return -EINVAL;
1692 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1693 return -ENOMEDIUM;
1694 }
aliguoric0f4ce72009-03-05 23:01:01 +00001695 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00001696 if (ret < 0) {
1697 bs->valid_key = 0;
1698 } else if (!bs->valid_key) {
1699 bs->valid_key = 1;
1700 /* call the change callback now, we skipped it on open */
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +02001701 bdrv_dev_change_media_cb(bs, true);
aliguoribb5fc202009-03-05 23:01:15 +00001702 }
aliguoric0f4ce72009-03-05 23:01:01 +00001703 return ret;
bellardea2384d2004-08-01 21:59:26 +00001704}
1705
1706void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1707{
bellard19cb3732006-08-19 11:45:59 +00001708 if (!bs->drv) {
bellardea2384d2004-08-01 21:59:26 +00001709 buf[0] = '\0';
1710 } else {
1711 pstrcpy(buf, buf_size, bs->drv->format_name);
1712 }
1713}
1714
ths5fafdf22007-09-16 21:08:06 +00001715void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00001716 void *opaque)
1717{
1718 BlockDriver *drv;
1719
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01001720 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00001721 it(opaque, drv->format_name);
1722 }
1723}
1724
bellardb3380822004-03-14 21:38:54 +00001725BlockDriverState *bdrv_find(const char *name)
1726{
1727 BlockDriverState *bs;
1728
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001729 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1730 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00001731 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001732 }
bellardb3380822004-03-14 21:38:54 +00001733 }
1734 return NULL;
1735}
1736
Markus Armbruster2f399b02010-06-02 18:55:20 +02001737BlockDriverState *bdrv_next(BlockDriverState *bs)
1738{
1739 if (!bs) {
1740 return QTAILQ_FIRST(&bdrv_states);
1741 }
1742 return QTAILQ_NEXT(bs, list);
1743}
1744
aliguori51de9762009-03-05 23:00:43 +00001745void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00001746{
1747 BlockDriverState *bs;
1748
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001749 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00001750 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00001751 }
1752}
1753
bellardea2384d2004-08-01 21:59:26 +00001754const char *bdrv_get_device_name(BlockDriverState *bs)
1755{
1756 return bs->device_name;
1757}
1758
Kevin Wolf205ef792010-10-21 16:43:43 +02001759int bdrv_flush(BlockDriverState *bs)
pbrook7a6cba62006-06-04 11:39:07 +00001760{
Alexander Graf016f5cf2010-05-26 17:51:49 +02001761 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolf205ef792010-10-21 16:43:43 +02001762 return 0;
Alexander Graf016f5cf2010-05-26 17:51:49 +02001763 }
1764
Kevin Wolfe7a8a782011-07-15 16:05:00 +02001765 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1766 return bdrv_co_flush_em(bs);
1767 }
1768
Kevin Wolf205ef792010-10-21 16:43:43 +02001769 if (bs->drv && bs->drv->bdrv_flush) {
1770 return bs->drv->bdrv_flush(bs);
1771 }
1772
1773 /*
1774 * Some block drivers always operate in either writethrough or unsafe mode
1775 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1776 * the server works (because the behaviour is hardcoded or depends on
1777 * server-side configuration), so we can't ensure that everything is safe
1778 * on disk. Returning an error doesn't work because that would break guests
1779 * even if the server operates in writethrough mode.
1780 *
1781 * Let's hope the user knows what he's doing.
1782 */
1783 return 0;
pbrook7a6cba62006-06-04 11:39:07 +00001784}
1785
aliguoric6ca28d2008-10-06 13:55:43 +00001786void bdrv_flush_all(void)
1787{
1788 BlockDriverState *bs;
1789
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001790 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Markus Armbrusterc602a482011-08-03 15:08:10 +02001791 if (!bdrv_is_read_only(bs) && bdrv_is_inserted(bs)) {
aliguoric6ca28d2008-10-06 13:55:43 +00001792 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001793 }
1794 }
aliguoric6ca28d2008-10-06 13:55:43 +00001795}
1796
Kevin Wolff2feebb2010-04-14 17:30:35 +02001797int bdrv_has_zero_init(BlockDriverState *bs)
1798{
1799 assert(bs->drv);
1800
Kevin Wolf336c1c12010-07-28 11:26:29 +02001801 if (bs->drv->bdrv_has_zero_init) {
1802 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02001803 }
1804
1805 return 1;
1806}
1807
Christoph Hellwigbb8bf762010-12-16 19:36:31 +01001808int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1809{
1810 if (!bs->drv) {
1811 return -ENOMEDIUM;
1812 }
1813 if (!bs->drv->bdrv_discard) {
1814 return 0;
1815 }
1816 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1817}
1818
thsf58c7b32008-06-05 21:53:49 +00001819/*
1820 * Returns true iff the specified sector is present in the disk image. Drivers
1821 * not implementing the functionality are assumed to not support backing files,
1822 * hence all their sectors are reported as allocated.
1823 *
1824 * 'pnum' is set to the number of sectors (including and immediately following
1825 * the specified sector) that are known to be in the same
1826 * allocated/unallocated state.
1827 *
1828 * 'nb_sectors' is the max value 'pnum' should be set to.
1829 */
1830int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1831 int *pnum)
1832{
1833 int64_t n;
1834 if (!bs->drv->bdrv_is_allocated) {
1835 if (sector_num >= bs->total_sectors) {
1836 *pnum = 0;
1837 return 0;
1838 }
1839 n = bs->total_sectors - sector_num;
1840 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1841 return 1;
1842 }
1843 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1844}
1845
Luiz Capitulino2582bfe2010-02-03 12:41:01 -02001846void bdrv_mon_event(const BlockDriverState *bdrv,
1847 BlockMonEventAction action, int is_read)
1848{
1849 QObject *data;
1850 const char *action_str;
1851
1852 switch (action) {
1853 case BDRV_ACTION_REPORT:
1854 action_str = "report";
1855 break;
1856 case BDRV_ACTION_IGNORE:
1857 action_str = "ignore";
1858 break;
1859 case BDRV_ACTION_STOP:
1860 action_str = "stop";
1861 break;
1862 default:
1863 abort();
1864 }
1865
1866 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1867 bdrv->device_name,
1868 action_str,
1869 is_read ? "read" : "write");
1870 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1871
1872 qobject_decref(data);
1873}
1874
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001875static void bdrv_print_dict(QObject *obj, void *opaque)
bellardb3380822004-03-14 21:38:54 +00001876{
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001877 QDict *bs_dict;
1878 Monitor *mon = opaque;
1879
1880 bs_dict = qobject_to_qdict(obj);
1881
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001882 monitor_printf(mon, "%s: removable=%d",
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001883 qdict_get_str(bs_dict, "device"),
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001884 qdict_get_bool(bs_dict, "removable"));
1885
1886 if (qdict_get_bool(bs_dict, "removable")) {
1887 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
Markus Armbrustere4def802011-09-06 18:58:53 +02001888 monitor_printf(mon, " tray-open=%d",
1889 qdict_get_bool(bs_dict, "tray-open"));
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001890 }
Luiz Capitulinod2078cc2011-09-26 17:43:55 -03001891
1892 if (qdict_haskey(bs_dict, "io-status")) {
1893 monitor_printf(mon, " io-status=%s", qdict_get_str(bs_dict, "io-status"));
1894 }
1895
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001896 if (qdict_haskey(bs_dict, "inserted")) {
1897 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1898
1899 monitor_printf(mon, " file=");
1900 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1901 if (qdict_haskey(qdict, "backing_file")) {
1902 monitor_printf(mon, " backing_file=");
1903 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1904 }
1905 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1906 qdict_get_bool(qdict, "ro"),
1907 qdict_get_str(qdict, "drv"),
1908 qdict_get_bool(qdict, "encrypted"));
1909 } else {
1910 monitor_printf(mon, " [not inserted]");
1911 }
1912
1913 monitor_printf(mon, "\n");
1914}
1915
1916void bdrv_info_print(Monitor *mon, const QObject *data)
1917{
1918 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1919}
1920
Luiz Capitulinof04ef602011-09-26 17:43:54 -03001921static const char *const io_status_name[BDRV_IOS_MAX] = {
1922 [BDRV_IOS_OK] = "ok",
1923 [BDRV_IOS_FAILED] = "failed",
1924 [BDRV_IOS_ENOSPC] = "nospace",
1925};
1926
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001927void bdrv_info(Monitor *mon, QObject **ret_data)
1928{
1929 QList *bs_list;
bellardb3380822004-03-14 21:38:54 +00001930 BlockDriverState *bs;
1931
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001932 bs_list = qlist_new();
1933
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001934 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001935 QObject *bs_obj;
Markus Armbrustere4def802011-09-06 18:58:53 +02001936 QDict *bs_dict;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001937
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001938 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001939 "'removable': %i, 'locked': %i }",
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001940 bs->device_name,
1941 bdrv_dev_has_removable_media(bs),
Markus Armbrusterf1076392011-09-06 18:58:46 +02001942 bdrv_dev_is_medium_locked(bs));
Markus Armbrustere4def802011-09-06 18:58:53 +02001943 bs_dict = qobject_to_qdict(bs_obj);
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001944
Markus Armbrustere4def802011-09-06 18:58:53 +02001945 if (bdrv_dev_has_removable_media(bs)) {
1946 qdict_put(bs_dict, "tray-open",
1947 qbool_from_int(bdrv_dev_is_tray_open(bs)));
1948 }
Luiz Capitulinof04ef602011-09-26 17:43:54 -03001949
1950 if (bdrv_iostatus_is_enabled(bs)) {
1951 qdict_put(bs_dict, "io-status",
1952 qstring_from_str(io_status_name[bs->iostatus]));
1953 }
1954
bellard19cb3732006-08-19 11:45:59 +00001955 if (bs->drv) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001956 QObject *obj;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001957
1958 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1959 "'encrypted': %i }",
1960 bs->filename, bs->read_only,
1961 bs->drv->format_name,
1962 bdrv_is_encrypted(bs));
thsfef30742006-12-22 14:11:32 +00001963 if (bs->backing_file[0] != '\0') {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001964 QDict *qdict = qobject_to_qdict(obj);
1965 qdict_put(qdict, "backing_file",
1966 qstring_from_str(bs->backing_file));
aliguori376253e2009-03-05 23:01:23 +00001967 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001968
1969 qdict_put_obj(bs_dict, "inserted", obj);
bellardb3380822004-03-14 21:38:54 +00001970 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001971 qlist_append_obj(bs_list, bs_obj);
bellardb3380822004-03-14 21:38:54 +00001972 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001973
1974 *ret_data = QOBJECT(bs_list);
bellardb3380822004-03-14 21:38:54 +00001975}
thsa36e69d2007-12-02 05:18:19 +00001976
Luiz Capitulino218a5362009-12-10 17:16:07 -02001977static void bdrv_stats_iter(QObject *data, void *opaque)
thsa36e69d2007-12-02 05:18:19 +00001978{
Luiz Capitulino218a5362009-12-10 17:16:07 -02001979 QDict *qdict;
1980 Monitor *mon = opaque;
1981
1982 qdict = qobject_to_qdict(data);
1983 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1984
1985 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1986 monitor_printf(mon, " rd_bytes=%" PRId64
1987 " wr_bytes=%" PRId64
1988 " rd_operations=%" PRId64
1989 " wr_operations=%" PRId64
Christoph Hellwige8045d62011-08-22 00:25:58 +02001990 " flush_operations=%" PRId64
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001991 " wr_total_time_ns=%" PRId64
1992 " rd_total_time_ns=%" PRId64
1993 " flush_total_time_ns=%" PRId64
Luiz Capitulino218a5362009-12-10 17:16:07 -02001994 "\n",
1995 qdict_get_int(qdict, "rd_bytes"),
1996 qdict_get_int(qdict, "wr_bytes"),
1997 qdict_get_int(qdict, "rd_operations"),
Christoph Hellwige8045d62011-08-22 00:25:58 +02001998 qdict_get_int(qdict, "wr_operations"),
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02001999 qdict_get_int(qdict, "flush_operations"),
2000 qdict_get_int(qdict, "wr_total_time_ns"),
2001 qdict_get_int(qdict, "rd_total_time_ns"),
2002 qdict_get_int(qdict, "flush_total_time_ns"));
Luiz Capitulino218a5362009-12-10 17:16:07 -02002003}
2004
2005void bdrv_stats_print(Monitor *mon, const QObject *data)
2006{
2007 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
2008}
2009
Kevin Wolf294cc352010-04-28 14:34:01 +02002010static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
2011{
2012 QObject *res;
2013 QDict *dict;
2014
2015 res = qobject_from_jsonf("{ 'stats': {"
2016 "'rd_bytes': %" PRId64 ","
2017 "'wr_bytes': %" PRId64 ","
2018 "'rd_operations': %" PRId64 ","
2019 "'wr_operations': %" PRId64 ","
Christoph Hellwige8045d62011-08-22 00:25:58 +02002020 "'wr_highest_offset': %" PRId64 ","
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02002021 "'flush_operations': %" PRId64 ","
2022 "'wr_total_time_ns': %" PRId64 ","
2023 "'rd_total_time_ns': %" PRId64 ","
2024 "'flush_total_time_ns': %" PRId64
Kevin Wolf294cc352010-04-28 14:34:01 +02002025 "} }",
Christoph Hellwiga597e792011-08-25 08:26:01 +02002026 bs->nr_bytes[BDRV_ACCT_READ],
2027 bs->nr_bytes[BDRV_ACCT_WRITE],
2028 bs->nr_ops[BDRV_ACCT_READ],
2029 bs->nr_ops[BDRV_ACCT_WRITE],
Blue Swirl5ffbbc62010-06-14 18:55:33 +00002030 bs->wr_highest_sector *
Christoph Hellwige8045d62011-08-22 00:25:58 +02002031 (uint64_t)BDRV_SECTOR_SIZE,
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02002032 bs->nr_ops[BDRV_ACCT_FLUSH],
2033 bs->total_time_ns[BDRV_ACCT_WRITE],
2034 bs->total_time_ns[BDRV_ACCT_READ],
2035 bs->total_time_ns[BDRV_ACCT_FLUSH]);
Kevin Wolf294cc352010-04-28 14:34:01 +02002036 dict = qobject_to_qdict(res);
2037
2038 if (*bs->device_name) {
2039 qdict_put(dict, "device", qstring_from_str(bs->device_name));
2040 }
2041
2042 if (bs->file) {
2043 QObject *parent = bdrv_info_stats_bs(bs->file);
2044 qdict_put_obj(dict, "parent", parent);
2045 }
2046
2047 return res;
2048}
2049
Luiz Capitulino218a5362009-12-10 17:16:07 -02002050void bdrv_info_stats(Monitor *mon, QObject **ret_data)
2051{
2052 QObject *obj;
2053 QList *devices;
thsa36e69d2007-12-02 05:18:19 +00002054 BlockDriverState *bs;
2055
Luiz Capitulino218a5362009-12-10 17:16:07 -02002056 devices = qlist_new();
2057
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002058 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002059 obj = bdrv_info_stats_bs(bs);
Luiz Capitulino218a5362009-12-10 17:16:07 -02002060 qlist_append_obj(devices, obj);
thsa36e69d2007-12-02 05:18:19 +00002061 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02002062
2063 *ret_data = QOBJECT(devices);
thsa36e69d2007-12-02 05:18:19 +00002064}
bellardea2384d2004-08-01 21:59:26 +00002065
aliguori045df332009-03-05 23:00:48 +00002066const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2067{
2068 if (bs->backing_hd && bs->backing_hd->encrypted)
2069 return bs->backing_file;
2070 else if (bs->encrypted)
2071 return bs->filename;
2072 else
2073 return NULL;
2074}
2075
ths5fafdf22007-09-16 21:08:06 +00002076void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00002077 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00002078{
Kevin Wolfb783e402010-01-12 12:55:16 +01002079 if (!bs->backing_file) {
bellard83f64092006-08-01 16:21:11 +00002080 pstrcpy(filename, filename_size, "");
2081 } else {
2082 pstrcpy(filename, filename_size, bs->backing_file);
2083 }
bellardea2384d2004-08-01 21:59:26 +00002084}
2085
ths5fafdf22007-09-16 21:08:06 +00002086int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00002087 const uint8_t *buf, int nb_sectors)
2088{
2089 BlockDriver *drv = bs->drv;
2090 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002091 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002092 if (!drv->bdrv_write_compressed)
2093 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02002094 if (bdrv_check_request(bs, sector_num, nb_sectors))
2095 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002096
Jan Kiszkac6d22832009-11-30 18:21:20 +01002097 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002098 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2099 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002100
bellardfaea38e2006-08-05 21:31:00 +00002101 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2102}
ths3b46e622007-09-17 08:09:54 +00002103
bellardfaea38e2006-08-05 21:31:00 +00002104int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2105{
2106 BlockDriver *drv = bs->drv;
2107 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002108 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002109 if (!drv->bdrv_get_info)
2110 return -ENOTSUP;
2111 memset(bdi, 0, sizeof(*bdi));
2112 return drv->bdrv_get_info(bs, bdi);
2113}
2114
Christoph Hellwig45566e92009-07-10 23:11:57 +02002115int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2116 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002117{
2118 BlockDriver *drv = bs->drv;
2119 if (!drv)
2120 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002121 if (drv->bdrv_save_vmstate)
2122 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2123 if (bs->file)
2124 return bdrv_save_vmstate(bs->file, buf, pos, size);
2125 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002126}
2127
Christoph Hellwig45566e92009-07-10 23:11:57 +02002128int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2129 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00002130{
2131 BlockDriver *drv = bs->drv;
2132 if (!drv)
2133 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002134 if (drv->bdrv_load_vmstate)
2135 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2136 if (bs->file)
2137 return bdrv_load_vmstate(bs->file, buf, pos, size);
2138 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00002139}
2140
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01002141void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2142{
2143 BlockDriver *drv = bs->drv;
2144
2145 if (!drv || !drv->bdrv_debug_event) {
2146 return;
2147 }
2148
2149 return drv->bdrv_debug_event(bs, event);
2150
2151}
2152
bellardfaea38e2006-08-05 21:31:00 +00002153/**************************************************************/
2154/* handling of snapshots */
2155
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002156int bdrv_can_snapshot(BlockDriverState *bs)
2157{
2158 BlockDriver *drv = bs->drv;
Markus Armbruster07b70bf2011-08-03 15:08:11 +02002159 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03002160 return 0;
2161 }
2162
2163 if (!drv->bdrv_snapshot_create) {
2164 if (bs->file != NULL) {
2165 return bdrv_can_snapshot(bs->file);
2166 }
2167 return 0;
2168 }
2169
2170 return 1;
2171}
2172
Blue Swirl199630b2010-07-25 20:49:34 +00002173int bdrv_is_snapshot(BlockDriverState *bs)
2174{
2175 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2176}
2177
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002178BlockDriverState *bdrv_snapshots(void)
2179{
2180 BlockDriverState *bs;
2181
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002182 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002183 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002184 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002185
2186 bs = NULL;
2187 while ((bs = bdrv_next(bs))) {
2188 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002189 bs_snapshots = bs;
2190 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002191 }
2192 }
2193 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002194}
2195
ths5fafdf22007-09-16 21:08:06 +00002196int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002197 QEMUSnapshotInfo *sn_info)
2198{
2199 BlockDriver *drv = bs->drv;
2200 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002201 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002202 if (drv->bdrv_snapshot_create)
2203 return drv->bdrv_snapshot_create(bs, sn_info);
2204 if (bs->file)
2205 return bdrv_snapshot_create(bs->file, sn_info);
2206 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002207}
2208
ths5fafdf22007-09-16 21:08:06 +00002209int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002210 const char *snapshot_id)
2211{
2212 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002213 int ret, open_ret;
2214
bellardfaea38e2006-08-05 21:31:00 +00002215 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002216 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002217 if (drv->bdrv_snapshot_goto)
2218 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2219
2220 if (bs->file) {
2221 drv->bdrv_close(bs);
2222 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2223 open_ret = drv->bdrv_open(bs, bs->open_flags);
2224 if (open_ret < 0) {
2225 bdrv_delete(bs->file);
2226 bs->drv = NULL;
2227 return open_ret;
2228 }
2229 return ret;
2230 }
2231
2232 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002233}
2234
2235int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2236{
2237 BlockDriver *drv = bs->drv;
2238 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002239 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002240 if (drv->bdrv_snapshot_delete)
2241 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2242 if (bs->file)
2243 return bdrv_snapshot_delete(bs->file, snapshot_id);
2244 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002245}
2246
ths5fafdf22007-09-16 21:08:06 +00002247int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002248 QEMUSnapshotInfo **psn_info)
2249{
2250 BlockDriver *drv = bs->drv;
2251 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002252 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002253 if (drv->bdrv_snapshot_list)
2254 return drv->bdrv_snapshot_list(bs, psn_info);
2255 if (bs->file)
2256 return bdrv_snapshot_list(bs->file, psn_info);
2257 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002258}
2259
edison51ef6722010-09-21 19:58:41 -07002260int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2261 const char *snapshot_name)
2262{
2263 BlockDriver *drv = bs->drv;
2264 if (!drv) {
2265 return -ENOMEDIUM;
2266 }
2267 if (!bs->read_only) {
2268 return -EINVAL;
2269 }
2270 if (drv->bdrv_snapshot_load_tmp) {
2271 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2272 }
2273 return -ENOTSUP;
2274}
2275
bellardfaea38e2006-08-05 21:31:00 +00002276#define NB_SUFFIXES 4
2277
2278char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2279{
2280 static const char suffixes[NB_SUFFIXES] = "KMGT";
2281 int64_t base;
2282 int i;
2283
2284 if (size <= 999) {
2285 snprintf(buf, buf_size, "%" PRId64, size);
2286 } else {
2287 base = 1024;
2288 for(i = 0; i < NB_SUFFIXES; i++) {
2289 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00002290 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00002291 (double)size / base,
2292 suffixes[i]);
2293 break;
2294 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00002295 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00002296 ((size + (base >> 1)) / base),
2297 suffixes[i]);
2298 break;
2299 }
2300 base = base * 1024;
2301 }
2302 }
2303 return buf;
2304}
2305
2306char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2307{
2308 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00002309#ifdef _WIN32
2310 struct tm *ptm;
2311#else
bellardfaea38e2006-08-05 21:31:00 +00002312 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00002313#endif
bellardfaea38e2006-08-05 21:31:00 +00002314 time_t ti;
2315 int64_t secs;
2316
2317 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00002318 snprintf(buf, buf_size,
2319 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002320 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2321 } else {
2322 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00002323#ifdef _WIN32
2324 ptm = localtime(&ti);
2325 strftime(date_buf, sizeof(date_buf),
2326 "%Y-%m-%d %H:%M:%S", ptm);
2327#else
bellardfaea38e2006-08-05 21:31:00 +00002328 localtime_r(&ti, &tm);
2329 strftime(date_buf, sizeof(date_buf),
2330 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00002331#endif
bellardfaea38e2006-08-05 21:31:00 +00002332 secs = sn->vm_clock_nsec / 1000000000;
2333 snprintf(clock_buf, sizeof(clock_buf),
2334 "%02d:%02d:%02d.%03d",
2335 (int)(secs / 3600),
2336 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00002337 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00002338 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2339 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00002340 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002341 sn->id_str, sn->name,
2342 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2343 date_buf,
2344 clock_buf);
2345 }
2346 return buf;
2347}
2348
bellard83f64092006-08-01 16:21:11 +00002349/**************************************************************/
2350/* async I/Os */
2351
aliguori3b69e4b2009-01-22 16:59:24 +00002352BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00002353 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00002354 BlockDriverCompletionFunc *cb, void *opaque)
2355{
bellard83f64092006-08-01 16:21:11 +00002356 BlockDriver *drv = bs->drv;
bellard83f64092006-08-01 16:21:11 +00002357
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002358 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2359
bellard19cb3732006-08-19 11:45:59 +00002360 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002361 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002362 if (bdrv_check_request(bs, sector_num, nb_sectors))
2363 return NULL;
ths3b46e622007-09-17 08:09:54 +00002364
Christoph Hellwiga597e792011-08-25 08:26:01 +02002365 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2366 cb, opaque);
bellard83f64092006-08-01 16:21:11 +00002367}
2368
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002369typedef struct BlockCompleteData {
2370 BlockDriverCompletionFunc *cb;
2371 void *opaque;
2372 BlockDriverState *bs;
2373 int64_t sector_num;
2374 int nb_sectors;
2375} BlockCompleteData;
2376
2377static void block_complete_cb(void *opaque, int ret)
2378{
2379 BlockCompleteData *b = opaque;
2380
2381 if (b->bs->dirty_bitmap) {
2382 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2383 }
2384 b->cb(b->opaque, ret);
Anthony Liguori7267c092011-08-20 22:09:37 -05002385 g_free(b);
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002386}
2387
2388static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2389 int64_t sector_num,
2390 int nb_sectors,
2391 BlockDriverCompletionFunc *cb,
2392 void *opaque)
2393{
Anthony Liguori7267c092011-08-20 22:09:37 -05002394 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002395
2396 blkdata->bs = bs;
2397 blkdata->cb = cb;
2398 blkdata->opaque = opaque;
2399 blkdata->sector_num = sector_num;
2400 blkdata->nb_sectors = nb_sectors;
2401
2402 return blkdata;
2403}
2404
aliguorif141eaf2009-04-07 18:43:24 +00002405BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2406 QEMUIOVector *qiov, int nb_sectors,
2407 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002408{
bellard83f64092006-08-01 16:21:11 +00002409 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002410 BlockDriverAIOCB *ret;
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002411 BlockCompleteData *blk_cb_data;
bellard83f64092006-08-01 16:21:11 +00002412
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002413 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2414
bellard19cb3732006-08-19 11:45:59 +00002415 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002416 return NULL;
bellard83f64092006-08-01 16:21:11 +00002417 if (bs->read_only)
pbrookce1a14d2006-08-07 02:38:06 +00002418 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002419 if (bdrv_check_request(bs, sector_num, nb_sectors))
2420 return NULL;
bellard83f64092006-08-01 16:21:11 +00002421
Jan Kiszkac6d22832009-11-30 18:21:20 +01002422 if (bs->dirty_bitmap) {
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002423 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2424 opaque);
2425 cb = &block_complete_cb;
2426 opaque = blk_cb_data;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002427 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002428
aliguorif141eaf2009-04-07 18:43:24 +00002429 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2430 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002431
2432 if (ret) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002433 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2434 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2435 }
thsa36e69d2007-12-02 05:18:19 +00002436 }
2437
2438 return ret;
bellard83f64092006-08-01 16:21:11 +00002439}
2440
Kevin Wolf40b4f532009-09-09 17:53:37 +02002441
2442typedef struct MultiwriteCB {
2443 int error;
2444 int num_requests;
2445 int num_callbacks;
2446 struct {
2447 BlockDriverCompletionFunc *cb;
2448 void *opaque;
2449 QEMUIOVector *free_qiov;
2450 void *free_buf;
2451 } callbacks[];
2452} MultiwriteCB;
2453
2454static void multiwrite_user_cb(MultiwriteCB *mcb)
2455{
2456 int i;
2457
2458 for (i = 0; i < mcb->num_callbacks; i++) {
2459 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01002460 if (mcb->callbacks[i].free_qiov) {
2461 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2462 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002463 g_free(mcb->callbacks[i].free_qiov);
Herve Poussineauf8a83242010-01-24 21:23:56 +00002464 qemu_vfree(mcb->callbacks[i].free_buf);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002465 }
2466}
2467
2468static void multiwrite_cb(void *opaque, int ret)
2469{
2470 MultiwriteCB *mcb = opaque;
2471
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002472 trace_multiwrite_cb(mcb, ret);
2473
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02002474 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02002475 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002476 }
2477
2478 mcb->num_requests--;
2479 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02002480 multiwrite_user_cb(mcb);
Anthony Liguori7267c092011-08-20 22:09:37 -05002481 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002482 }
2483}
2484
2485static int multiwrite_req_compare(const void *a, const void *b)
2486{
Christoph Hellwig77be4362010-05-19 20:53:10 +02002487 const BlockRequest *req1 = a, *req2 = b;
2488
2489 /*
2490 * Note that we can't simply subtract req2->sector from req1->sector
2491 * here as that could overflow the return value.
2492 */
2493 if (req1->sector > req2->sector) {
2494 return 1;
2495 } else if (req1->sector < req2->sector) {
2496 return -1;
2497 } else {
2498 return 0;
2499 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002500}
2501
2502/*
2503 * Takes a bunch of requests and tries to merge them. Returns the number of
2504 * requests that remain after merging.
2505 */
2506static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2507 int num_reqs, MultiwriteCB *mcb)
2508{
2509 int i, outidx;
2510
2511 // Sort requests by start sector
2512 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2513
2514 // Check if adjacent requests touch the same clusters. If so, combine them,
2515 // filling up gaps with zero sectors.
2516 outidx = 0;
2517 for (i = 1; i < num_reqs; i++) {
2518 int merge = 0;
2519 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2520
2521 // This handles the cases that are valid for all block drivers, namely
2522 // exactly sequential writes and overlapping writes.
2523 if (reqs[i].sector <= oldreq_last) {
2524 merge = 1;
2525 }
2526
2527 // The block driver may decide that it makes sense to combine requests
2528 // even if there is a gap of some sectors between them. In this case,
2529 // the gap is filled with zeros (therefore only applicable for yet
2530 // unused space in format like qcow2).
2531 if (!merge && bs->drv->bdrv_merge_requests) {
2532 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2533 }
2534
Christoph Hellwige2a305f2010-01-26 14:49:08 +01002535 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2536 merge = 0;
2537 }
2538
Kevin Wolf40b4f532009-09-09 17:53:37 +02002539 if (merge) {
2540 size_t size;
Anthony Liguori7267c092011-08-20 22:09:37 -05002541 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002542 qemu_iovec_init(qiov,
2543 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2544
2545 // Add the first request to the merged one. If the requests are
2546 // overlapping, drop the last sectors of the first request.
2547 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2548 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2549
2550 // We might need to add some zeros between the two requests
2551 if (reqs[i].sector > oldreq_last) {
2552 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2553 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2554 memset(buf, 0, zero_bytes);
2555 qemu_iovec_add(qiov, buf, zero_bytes);
2556 mcb->callbacks[i].free_buf = buf;
2557 }
2558
2559 // Add the second request
2560 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2561
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02002562 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002563 reqs[outidx].qiov = qiov;
2564
2565 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2566 } else {
2567 outidx++;
2568 reqs[outidx].sector = reqs[i].sector;
2569 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2570 reqs[outidx].qiov = reqs[i].qiov;
2571 }
2572 }
2573
2574 return outidx + 1;
2575}
2576
2577/*
2578 * Submit multiple AIO write requests at once.
2579 *
2580 * On success, the function returns 0 and all requests in the reqs array have
2581 * been submitted. In error case this function returns -1, and any of the
2582 * requests may or may not be submitted yet. In particular, this means that the
2583 * callback will be called for some of the requests, for others it won't. The
2584 * caller must check the error field of the BlockRequest to wait for the right
2585 * callbacks (if error != 0, no callback will be called).
2586 *
2587 * The implementation may modify the contents of the reqs array, e.g. to merge
2588 * requests. However, the fields opaque and error are left unmodified as they
2589 * are used to signal failure for a single request to the caller.
2590 */
2591int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2592{
2593 BlockDriverAIOCB *acb;
2594 MultiwriteCB *mcb;
2595 int i;
2596
Ryan Harper301db7c2011-03-07 10:01:04 -06002597 /* don't submit writes if we don't have a medium */
2598 if (bs->drv == NULL) {
2599 for (i = 0; i < num_reqs; i++) {
2600 reqs[i].error = -ENOMEDIUM;
2601 }
2602 return -1;
2603 }
2604
Kevin Wolf40b4f532009-09-09 17:53:37 +02002605 if (num_reqs == 0) {
2606 return 0;
2607 }
2608
2609 // Create MultiwriteCB structure
Anthony Liguori7267c092011-08-20 22:09:37 -05002610 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
Kevin Wolf40b4f532009-09-09 17:53:37 +02002611 mcb->num_requests = 0;
2612 mcb->num_callbacks = num_reqs;
2613
2614 for (i = 0; i < num_reqs; i++) {
2615 mcb->callbacks[i].cb = reqs[i].cb;
2616 mcb->callbacks[i].opaque = reqs[i].opaque;
2617 }
2618
2619 // Check for mergable requests
2620 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2621
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002622 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2623
Kevin Wolf453f9a12010-07-02 14:01:21 +02002624 /*
2625 * Run the aio requests. As soon as one request can't be submitted
2626 * successfully, fail all requests that are not yet submitted (we must
2627 * return failure for all requests anyway)
2628 *
2629 * num_requests cannot be set to the right value immediately: If
2630 * bdrv_aio_writev fails for some request, num_requests would be too high
2631 * and therefore multiwrite_cb() would never recognize the multiwrite
2632 * request as completed. We also cannot use the loop variable i to set it
2633 * when the first request fails because the callback may already have been
2634 * called for previously submitted requests. Thus, num_requests must be
2635 * incremented for each request that is submitted.
2636 *
2637 * The problem that callbacks may be called early also means that we need
2638 * to take care that num_requests doesn't become 0 before all requests are
2639 * submitted - multiwrite_cb() would consider the multiwrite request
2640 * completed. A dummy request that is "completed" by a manual call to
2641 * multiwrite_cb() takes care of this.
2642 */
2643 mcb->num_requests = 1;
2644
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002645 // Run the aio requests
Kevin Wolf40b4f532009-09-09 17:53:37 +02002646 for (i = 0; i < num_reqs; i++) {
Kevin Wolf453f9a12010-07-02 14:01:21 +02002647 mcb->num_requests++;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002648 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2649 reqs[i].nb_sectors, multiwrite_cb, mcb);
2650
2651 if (acb == NULL) {
2652 // We can only fail the whole thing if no request has been
2653 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2654 // complete and report the error in the callback.
Kevin Wolf453f9a12010-07-02 14:01:21 +02002655 if (i == 0) {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002656 trace_bdrv_aio_multiwrite_earlyfail(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002657 goto fail;
2658 } else {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002659 trace_bdrv_aio_multiwrite_latefail(mcb, i);
Kevin Wolf7eb58a62010-04-06 18:24:07 +02002660 multiwrite_cb(mcb, -EIO);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002661 break;
2662 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002663 }
2664 }
2665
Kevin Wolf453f9a12010-07-02 14:01:21 +02002666 /* Complete the dummy request */
2667 multiwrite_cb(mcb, 0);
2668
Kevin Wolf40b4f532009-09-09 17:53:37 +02002669 return 0;
2670
2671fail:
Kevin Wolf453f9a12010-07-02 14:01:21 +02002672 for (i = 0; i < mcb->num_callbacks; i++) {
2673 reqs[i].error = -EIO;
2674 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002675 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002676 return -1;
2677}
2678
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002679BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2680 BlockDriverCompletionFunc *cb, void *opaque)
2681{
2682 BlockDriver *drv = bs->drv;
2683
Stefan Hajnoczia13aac02011-03-07 07:58:04 +00002684 trace_bdrv_aio_flush(bs, opaque);
2685
Alexander Graf016f5cf2010-05-26 17:51:49 +02002686 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2687 return bdrv_aio_noop_em(bs, cb, opaque);
2688 }
2689
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002690 if (!drv)
2691 return NULL;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002692 return drv->bdrv_aio_flush(bs, cb, opaque);
2693}
2694
bellard83f64092006-08-01 16:21:11 +00002695void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00002696{
aliguori6bbff9a2009-03-20 18:25:59 +00002697 acb->pool->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00002698}
2699
pbrookce1a14d2006-08-07 02:38:06 +00002700
bellard83f64092006-08-01 16:21:11 +00002701/**************************************************************/
2702/* async block device emulation */
2703
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002704typedef struct BlockDriverAIOCBSync {
2705 BlockDriverAIOCB common;
2706 QEMUBH *bh;
2707 int ret;
2708 /* vector translation state */
2709 QEMUIOVector *qiov;
2710 uint8_t *bounce;
2711 int is_write;
2712} BlockDriverAIOCBSync;
2713
2714static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2715{
Kevin Wolfb666d232010-05-05 11:44:39 +02002716 BlockDriverAIOCBSync *acb =
2717 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03002718 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002719 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002720 qemu_aio_release(acb);
2721}
2722
2723static AIOPool bdrv_em_aio_pool = {
2724 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2725 .cancel = bdrv_aio_cancel_em,
2726};
2727
bellard83f64092006-08-01 16:21:11 +00002728static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00002729{
pbrookce1a14d2006-08-07 02:38:06 +00002730 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00002731
aliguorif141eaf2009-04-07 18:43:24 +00002732 if (!acb->is_write)
2733 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00002734 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00002735 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03002736 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002737 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00002738 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00002739}
bellardbeac80c2006-06-26 20:08:57 +00002740
aliguorif141eaf2009-04-07 18:43:24 +00002741static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2742 int64_t sector_num,
2743 QEMUIOVector *qiov,
2744 int nb_sectors,
2745 BlockDriverCompletionFunc *cb,
2746 void *opaque,
2747 int is_write)
2748
bellardea2384d2004-08-01 21:59:26 +00002749{
pbrookce1a14d2006-08-07 02:38:06 +00002750 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00002751
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002752 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00002753 acb->is_write = is_write;
2754 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00002755 acb->bounce = qemu_blockalign(bs, qiov->size);
aliguorif141eaf2009-04-07 18:43:24 +00002756
pbrookce1a14d2006-08-07 02:38:06 +00002757 if (!acb->bh)
2758 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00002759
2760 if (is_write) {
2761 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
Stefan Hajnoczi1ed20ac2011-10-13 13:08:21 +01002762 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
aliguorif141eaf2009-04-07 18:43:24 +00002763 } else {
Stefan Hajnoczi1ed20ac2011-10-13 13:08:21 +01002764 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
aliguorif141eaf2009-04-07 18:43:24 +00002765 }
2766
pbrookce1a14d2006-08-07 02:38:06 +00002767 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00002768
pbrookce1a14d2006-08-07 02:38:06 +00002769 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00002770}
2771
aliguorif141eaf2009-04-07 18:43:24 +00002772static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2773 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00002774 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002775{
aliguorif141eaf2009-04-07 18:43:24 +00002776 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00002777}
2778
aliguorif141eaf2009-04-07 18:43:24 +00002779static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2780 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2781 BlockDriverCompletionFunc *cb, void *opaque)
2782{
2783 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2784}
2785
Kevin Wolf68485422011-06-30 10:05:46 +02002786
2787typedef struct BlockDriverAIOCBCoroutine {
2788 BlockDriverAIOCB common;
2789 BlockRequest req;
2790 bool is_write;
2791 QEMUBH* bh;
2792} BlockDriverAIOCBCoroutine;
2793
2794static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2795{
2796 qemu_aio_flush();
2797}
2798
2799static AIOPool bdrv_em_co_aio_pool = {
2800 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2801 .cancel = bdrv_aio_co_cancel_em,
2802};
2803
2804static void bdrv_co_rw_bh(void *opaque)
2805{
2806 BlockDriverAIOCBCoroutine *acb = opaque;
2807
2808 acb->common.cb(acb->common.opaque, acb->req.error);
2809 qemu_bh_delete(acb->bh);
2810 qemu_aio_release(acb);
2811}
2812
2813static void coroutine_fn bdrv_co_rw(void *opaque)
2814{
2815 BlockDriverAIOCBCoroutine *acb = opaque;
2816 BlockDriverState *bs = acb->common.bs;
2817
2818 if (!acb->is_write) {
2819 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2820 acb->req.nb_sectors, acb->req.qiov);
2821 } else {
2822 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2823 acb->req.nb_sectors, acb->req.qiov);
2824 }
2825
2826 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2827 qemu_bh_schedule(acb->bh);
2828}
2829
2830static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2831 int64_t sector_num,
2832 QEMUIOVector *qiov,
2833 int nb_sectors,
2834 BlockDriverCompletionFunc *cb,
2835 void *opaque,
2836 bool is_write)
2837{
2838 Coroutine *co;
2839 BlockDriverAIOCBCoroutine *acb;
2840
2841 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2842 acb->req.sector = sector_num;
2843 acb->req.nb_sectors = nb_sectors;
2844 acb->req.qiov = qiov;
2845 acb->is_write = is_write;
2846
2847 co = qemu_coroutine_create(bdrv_co_rw);
2848 qemu_coroutine_enter(co, acb);
2849
2850 return &acb->common;
2851}
2852
2853static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2854 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2855 BlockDriverCompletionFunc *cb, void *opaque)
2856{
2857 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2858 false);
2859}
2860
2861static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2862 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2863 BlockDriverCompletionFunc *cb, void *opaque)
2864{
2865 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2866 true);
2867}
2868
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002869static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2870 BlockDriverCompletionFunc *cb, void *opaque)
2871{
2872 BlockDriverAIOCBSync *acb;
2873
2874 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2875 acb->is_write = 1; /* don't bounce in the completion hadler */
2876 acb->qiov = NULL;
2877 acb->bounce = NULL;
2878 acb->ret = 0;
2879
2880 if (!acb->bh)
2881 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2882
2883 bdrv_flush(bs);
2884 qemu_bh_schedule(acb->bh);
2885 return &acb->common;
2886}
2887
Alexander Graf016f5cf2010-05-26 17:51:49 +02002888static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2889 BlockDriverCompletionFunc *cb, void *opaque)
2890{
2891 BlockDriverAIOCBSync *acb;
2892
2893 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2894 acb->is_write = 1; /* don't bounce in the completion handler */
2895 acb->qiov = NULL;
2896 acb->bounce = NULL;
2897 acb->ret = 0;
2898
2899 if (!acb->bh) {
2900 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2901 }
2902
2903 qemu_bh_schedule(acb->bh);
2904 return &acb->common;
2905}
2906
bellard83f64092006-08-01 16:21:11 +00002907/**************************************************************/
2908/* sync block device emulation */
2909
2910static void bdrv_rw_em_cb(void *opaque, int ret)
2911{
2912 *(int *)opaque = ret;
2913}
2914
2915#define NOT_DONE 0x7fffffff
2916
ths5fafdf22007-09-16 21:08:06 +00002917static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +00002918 uint8_t *buf, int nb_sectors)
2919{
pbrookce1a14d2006-08-07 02:38:06 +00002920 int async_ret;
2921 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002922 struct iovec iov;
2923 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002924
bellard83f64092006-08-01 16:21:11 +00002925 async_ret = NOT_DONE;
blueswir13f4cb3d2009-04-13 16:31:01 +00002926 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002927 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002928 qemu_iovec_init_external(&qiov, &iov, 1);
Stefan Hajnoczi1ed20ac2011-10-13 13:08:21 +01002929
2930 acb = bs->drv->bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2931 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002932 if (acb == NULL) {
2933 async_ret = -1;
2934 goto fail;
2935 }
aliguoribaf35cb2008-09-10 15:45:19 +00002936
bellard83f64092006-08-01 16:21:11 +00002937 while (async_ret == NOT_DONE) {
2938 qemu_aio_wait();
2939 }
aliguoribaf35cb2008-09-10 15:45:19 +00002940
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002941
2942fail:
bellard83f64092006-08-01 16:21:11 +00002943 return async_ret;
2944}
2945
2946static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2947 const uint8_t *buf, int nb_sectors)
2948{
pbrookce1a14d2006-08-07 02:38:06 +00002949 int async_ret;
2950 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002951 struct iovec iov;
2952 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002953
bellard83f64092006-08-01 16:21:11 +00002954 async_ret = NOT_DONE;
aliguorif141eaf2009-04-07 18:43:24 +00002955 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002956 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002957 qemu_iovec_init_external(&qiov, &iov, 1);
Stefan Hajnoczi1ed20ac2011-10-13 13:08:21 +01002958
2959 acb = bs->drv->bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2960 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002961 if (acb == NULL) {
2962 async_ret = -1;
2963 goto fail;
2964 }
bellard83f64092006-08-01 16:21:11 +00002965 while (async_ret == NOT_DONE) {
2966 qemu_aio_wait();
2967 }
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002968
2969fail:
bellard83f64092006-08-01 16:21:11 +00002970 return async_ret;
2971}
bellardea2384d2004-08-01 21:59:26 +00002972
2973void bdrv_init(void)
2974{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05002975 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00002976}
pbrookce1a14d2006-08-07 02:38:06 +00002977
Markus Armbrustereb852012009-10-27 18:41:44 +01002978void bdrv_init_with_whitelist(void)
2979{
2980 use_bdrv_whitelist = 1;
2981 bdrv_init();
2982}
2983
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002984void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2985 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00002986{
pbrookce1a14d2006-08-07 02:38:06 +00002987 BlockDriverAIOCB *acb;
2988
aliguori6bbff9a2009-03-20 18:25:59 +00002989 if (pool->free_aiocb) {
2990 acb = pool->free_aiocb;
2991 pool->free_aiocb = acb->next;
pbrookce1a14d2006-08-07 02:38:06 +00002992 } else {
Anthony Liguori7267c092011-08-20 22:09:37 -05002993 acb = g_malloc0(pool->aiocb_size);
aliguori6bbff9a2009-03-20 18:25:59 +00002994 acb->pool = pool;
pbrookce1a14d2006-08-07 02:38:06 +00002995 }
2996 acb->bs = bs;
2997 acb->cb = cb;
2998 acb->opaque = opaque;
2999 return acb;
3000}
3001
3002void qemu_aio_release(void *p)
3003{
aliguori6bbff9a2009-03-20 18:25:59 +00003004 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
3005 AIOPool *pool = acb->pool;
3006 acb->next = pool->free_aiocb;
3007 pool->free_aiocb = acb;
pbrookce1a14d2006-08-07 02:38:06 +00003008}
bellard19cb3732006-08-19 11:45:59 +00003009
3010/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003011/* Coroutine block device emulation */
3012
3013typedef struct CoroutineIOCompletion {
3014 Coroutine *coroutine;
3015 int ret;
3016} CoroutineIOCompletion;
3017
3018static void bdrv_co_io_em_complete(void *opaque, int ret)
3019{
3020 CoroutineIOCompletion *co = opaque;
3021
3022 co->ret = ret;
3023 qemu_coroutine_enter(co->coroutine, NULL);
3024}
3025
3026static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
3027 int nb_sectors, QEMUIOVector *iov,
3028 bool is_write)
3029{
3030 CoroutineIOCompletion co = {
3031 .coroutine = qemu_coroutine_self(),
3032 };
3033 BlockDriverAIOCB *acb;
3034
3035 if (is_write) {
Stefan Hajnoczia652d162011-10-05 17:17:02 +01003036 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
3037 bdrv_co_io_em_complete, &co);
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003038 } else {
Stefan Hajnoczia652d162011-10-05 17:17:02 +01003039 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
3040 bdrv_co_io_em_complete, &co);
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003041 }
3042
Stefan Hajnoczi59370aa2011-09-30 17:34:58 +01003043 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003044 if (!acb) {
3045 return -EIO;
3046 }
3047 qemu_coroutine_yield();
3048
3049 return co.ret;
3050}
3051
3052static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3053 int64_t sector_num, int nb_sectors,
3054 QEMUIOVector *iov)
3055{
3056 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3057}
3058
3059static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3060 int64_t sector_num, int nb_sectors,
3061 QEMUIOVector *iov)
3062{
3063 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3064}
3065
Kevin Wolfe7a8a782011-07-15 16:05:00 +02003066static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3067{
3068 CoroutineIOCompletion co = {
3069 .coroutine = qemu_coroutine_self(),
3070 };
3071 BlockDriverAIOCB *acb;
3072
3073 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3074 if (!acb) {
3075 return -EIO;
3076 }
3077 qemu_coroutine_yield();
3078 return co.ret;
3079}
3080
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003081/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00003082/* removable device support */
3083
3084/**
3085 * Return TRUE if the media is present
3086 */
3087int bdrv_is_inserted(BlockDriverState *bs)
3088{
3089 BlockDriver *drv = bs->drv;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003090
bellard19cb3732006-08-19 11:45:59 +00003091 if (!drv)
3092 return 0;
3093 if (!drv->bdrv_is_inserted)
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02003094 return 1;
3095 return drv->bdrv_is_inserted(bs);
bellard19cb3732006-08-19 11:45:59 +00003096}
3097
3098/**
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003099 * Return whether the media changed since the last call to this
3100 * function, or -ENOTSUP if we don't know. Most drivers don't know.
bellard19cb3732006-08-19 11:45:59 +00003101 */
3102int bdrv_media_changed(BlockDriverState *bs)
3103{
3104 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003105
Markus Armbruster8e49ca42011-08-03 15:08:08 +02003106 if (drv && drv->bdrv_media_changed) {
3107 return drv->bdrv_media_changed(bs);
3108 }
3109 return -ENOTSUP;
bellard19cb3732006-08-19 11:45:59 +00003110}
3111
3112/**
3113 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3114 */
Markus Armbrusterfdec4402011-09-06 18:58:45 +02003115void bdrv_eject(BlockDriverState *bs, int eject_flag)
bellard19cb3732006-08-19 11:45:59 +00003116{
3117 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00003118
Markus Armbruster822e1cd2011-07-20 18:23:42 +02003119 if (drv && drv->bdrv_eject) {
3120 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00003121 }
bellard19cb3732006-08-19 11:45:59 +00003122}
3123
bellard19cb3732006-08-19 11:45:59 +00003124/**
3125 * Lock or unlock the media (if it is locked, the user won't be able
3126 * to eject it manually).
3127 */
Markus Armbruster025e8492011-09-06 18:58:47 +02003128void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00003129{
3130 BlockDriver *drv = bs->drv;
3131
Markus Armbruster025e8492011-09-06 18:58:47 +02003132 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01003133
Markus Armbruster025e8492011-09-06 18:58:47 +02003134 if (drv && drv->bdrv_lock_medium) {
3135 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00003136 }
3137}
ths985a03b2007-12-24 16:10:43 +00003138
3139/* needed for generic scsi interface */
3140
3141int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3142{
3143 BlockDriver *drv = bs->drv;
3144
3145 if (drv && drv->bdrv_ioctl)
3146 return drv->bdrv_ioctl(bs, req, buf);
3147 return -ENOTSUP;
3148}
aliguori7d780662009-03-12 19:57:08 +00003149
aliguori221f7152009-03-28 17:28:41 +00003150BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3151 unsigned long int req, void *buf,
3152 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00003153{
aliguori221f7152009-03-28 17:28:41 +00003154 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00003155
aliguori221f7152009-03-28 17:28:41 +00003156 if (drv && drv->bdrv_aio_ioctl)
3157 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3158 return NULL;
aliguori7d780662009-03-12 19:57:08 +00003159}
aliguorie268ca52009-04-22 20:20:00 +00003160
Markus Armbruster7b6f9302011-09-06 18:58:56 +02003161void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
3162{
3163 bs->buffer_alignment = align;
3164}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003165
aliguorie268ca52009-04-22 20:20:00 +00003166void *qemu_blockalign(BlockDriverState *bs, size_t size)
3167{
3168 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3169}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003170
3171void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3172{
3173 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003174
Liran Schouraaa0eb72010-01-26 10:31:48 +02003175 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003176 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003177 if (!bs->dirty_bitmap) {
3178 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3179 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3180 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003181
Anthony Liguori7267c092011-08-20 22:09:37 -05003182 bs->dirty_bitmap = g_malloc0(bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003183 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003184 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003185 if (bs->dirty_bitmap) {
Anthony Liguori7267c092011-08-20 22:09:37 -05003186 g_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01003187 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003188 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003189 }
3190}
3191
3192int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3193{
Jan Kiszka6ea44302009-11-30 18:21:19 +01003194 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003195
Jan Kiszkac6d22832009-11-30 18:21:20 +01003196 if (bs->dirty_bitmap &&
3197 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02003198 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3199 (1UL << (chunk % (sizeof(unsigned long) * 8))));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003200 } else {
3201 return 0;
3202 }
3203}
3204
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003205void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3206 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003207{
3208 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3209}
Liran Schouraaa0eb72010-01-26 10:31:48 +02003210
3211int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3212{
3213 return bs->dirty_count;
3214}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003215
Marcelo Tosattidb593f22011-01-26 12:12:34 -02003216void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3217{
3218 assert(bs->in_use != in_use);
3219 bs->in_use = in_use;
3220}
3221
3222int bdrv_in_use(BlockDriverState *bs)
3223{
3224 return bs->in_use;
3225}
3226
Luiz Capitulino28a72822011-09-26 17:43:50 -03003227void bdrv_iostatus_enable(BlockDriverState *bs)
3228{
3229 bs->iostatus = BDRV_IOS_OK;
3230}
3231
3232/* The I/O status is only enabled if the drive explicitly
3233 * enables it _and_ the VM is configured to stop on errors */
3234bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
3235{
3236 return (bs->iostatus != BDRV_IOS_INVAL &&
3237 (bs->on_write_error == BLOCK_ERR_STOP_ENOSPC ||
3238 bs->on_write_error == BLOCK_ERR_STOP_ANY ||
3239 bs->on_read_error == BLOCK_ERR_STOP_ANY));
3240}
3241
3242void bdrv_iostatus_disable(BlockDriverState *bs)
3243{
3244 bs->iostatus = BDRV_IOS_INVAL;
3245}
3246
3247void bdrv_iostatus_reset(BlockDriverState *bs)
3248{
3249 if (bdrv_iostatus_is_enabled(bs)) {
3250 bs->iostatus = BDRV_IOS_OK;
3251 }
3252}
3253
3254/* XXX: Today this is set by device models because it makes the implementation
3255 quite simple. However, the block layer knows about the error, so it's
3256 possible to implement this without device models being involved */
3257void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
3258{
3259 if (bdrv_iostatus_is_enabled(bs) && bs->iostatus == BDRV_IOS_OK) {
3260 assert(error >= 0);
3261 bs->iostatus = error == ENOSPC ? BDRV_IOS_ENOSPC : BDRV_IOS_FAILED;
3262 }
3263}
3264
Christoph Hellwiga597e792011-08-25 08:26:01 +02003265void
3266bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3267 enum BlockAcctType type)
3268{
3269 assert(type < BDRV_MAX_IOTYPE);
3270
3271 cookie->bytes = bytes;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003272 cookie->start_time_ns = get_clock();
Christoph Hellwiga597e792011-08-25 08:26:01 +02003273 cookie->type = type;
3274}
3275
3276void
3277bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3278{
3279 assert(cookie->type < BDRV_MAX_IOTYPE);
3280
3281 bs->nr_bytes[cookie->type] += cookie->bytes;
3282 bs->nr_ops[cookie->type]++;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02003283 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
Christoph Hellwiga597e792011-08-25 08:26:01 +02003284}
3285
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003286int bdrv_img_create(const char *filename, const char *fmt,
3287 const char *base_filename, const char *base_fmt,
3288 char *options, uint64_t img_size, int flags)
3289{
3290 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02003291 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003292 BlockDriverState *bs = NULL;
3293 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003294 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003295 int ret = 0;
3296
3297 /* Find driver and parse its options */
3298 drv = bdrv_find_format(fmt);
3299 if (!drv) {
3300 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003301 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003302 goto out;
3303 }
3304
3305 proto_drv = bdrv_find_protocol(filename);
3306 if (!proto_drv) {
3307 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003308 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003309 goto out;
3310 }
3311
3312 create_options = append_option_parameters(create_options,
3313 drv->create_options);
3314 create_options = append_option_parameters(create_options,
3315 proto_drv->create_options);
3316
3317 /* Create parameter list with default values */
3318 param = parse_option_parameters("", create_options, param);
3319
3320 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3321
3322 /* Parse -o options */
3323 if (options) {
3324 param = parse_option_parameters(options, create_options, param);
3325 if (param == NULL) {
3326 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003327 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003328 goto out;
3329 }
3330 }
3331
3332 if (base_filename) {
3333 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3334 base_filename)) {
3335 error_report("Backing file not supported for file format '%s'",
3336 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003337 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003338 goto out;
3339 }
3340 }
3341
3342 if (base_fmt) {
3343 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3344 error_report("Backing file format not supported for file "
3345 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003346 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003347 goto out;
3348 }
3349 }
3350
Jes Sorensen792da932010-12-16 13:52:17 +01003351 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3352 if (backing_file && backing_file->value.s) {
3353 if (!strcmp(filename, backing_file->value.s)) {
3354 error_report("Error: Trying to create an image with the "
3355 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003356 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01003357 goto out;
3358 }
3359 }
3360
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003361 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3362 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003363 backing_drv = bdrv_find_format(backing_fmt->value.s);
3364 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003365 error_report("Unknown backing file format '%s'",
3366 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003367 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003368 goto out;
3369 }
3370 }
3371
3372 // The size for the image must always be specified, with one exception:
3373 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02003374 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3375 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003376 if (backing_file && backing_file->value.s) {
3377 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003378 char buf[32];
3379
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003380 bs = bdrv_new("");
3381
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003382 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003383 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003384 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003385 goto out;
3386 }
3387 bdrv_get_geometry(bs, &size);
3388 size *= 512;
3389
3390 snprintf(buf, sizeof(buf), "%" PRId64, size);
3391 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3392 } else {
3393 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003394 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003395 goto out;
3396 }
3397 }
3398
3399 printf("Formatting '%s', fmt=%s ", filename, fmt);
3400 print_option_parameters(param);
3401 puts("");
3402
3403 ret = bdrv_create(drv, filename, param);
3404
3405 if (ret < 0) {
3406 if (ret == -ENOTSUP) {
3407 error_report("Formatting or formatting option not supported for "
3408 "file format '%s'", fmt);
3409 } else if (ret == -EFBIG) {
3410 error_report("The image size is too large for file format '%s'",
3411 fmt);
3412 } else {
3413 error_report("%s: error while creating %s: %s", filename, fmt,
3414 strerror(-ret));
3415 }
3416 }
3417
3418out:
3419 free_option_parameters(create_options);
3420 free_option_parameters(param);
3421
3422 if (bs) {
3423 bdrv_delete(bs);
3424 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01003425
3426 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003427}