blob: e6abea85df8bef915b783021336caf123678bc1d [file] [log] [blame]
bellardfc01f7e2003-06-30 10:03:06 +00001/*
2 * QEMU System Emulator block driver
ths5fafdf22007-09-16 21:08:06 +00003 *
bellardfc01f7e2003-06-30 10:03:06 +00004 * Copyright (c) 2003 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardfc01f7e2003-06-30 10:03:06 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
blueswir13990d092008-12-05 17:53:21 +000024#include "config-host.h"
pbrookfaf07962007-11-11 02:51:17 +000025#include "qemu-common.h"
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +010026#include "trace.h"
aliguori376253e2009-03-05 23:01:23 +000027#include "monitor.h"
bellardea2384d2004-08-01 21:59:26 +000028#include "block_int.h"
Anthony Liguori5efa9d52009-05-09 17:03:42 -050029#include "module.h"
Luiz Capitulinod15e5462009-12-10 17:16:06 -020030#include "qemu-objects.h"
Kevin Wolf68485422011-06-30 10:05:46 +020031#include "qemu-coroutine.h"
bellardfc01f7e2003-06-30 10:03:06 +000032
Juan Quintela71e72a12009-07-27 16:12:56 +020033#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000034#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000037#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000038#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000039#include <sys/disk.h>
40#endif
blueswir1c5e97232009-03-07 20:06:23 +000041#endif
bellard7674e7b2005-04-26 21:59:26 +000042
aliguori49dc7682009-03-08 16:26:59 +000043#ifdef _WIN32
44#include <windows.h>
45#endif
46
aliguorif141eaf2009-04-07 18:43:24 +000047static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
48 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
aliguoric87c0672009-04-07 18:43:20 +000049 BlockDriverCompletionFunc *cb, void *opaque);
aliguorif141eaf2009-04-07 18:43:24 +000050static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
51 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +000052 BlockDriverCompletionFunc *cb, void *opaque);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +020053static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
Alexander Graf016f5cf2010-05-26 17:51:49 +020055static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
56 BlockDriverCompletionFunc *cb, void *opaque);
ths5fafdf22007-09-16 21:08:06 +000057static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +000058 uint8_t *buf, int nb_sectors);
59static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
60 const uint8_t *buf, int nb_sectors);
Kevin Wolf68485422011-06-30 10:05:46 +020061static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
62 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63 BlockDriverCompletionFunc *cb, void *opaque);
64static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
65 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66 BlockDriverCompletionFunc *cb, void *opaque);
Kevin Wolff9f05dc2011-07-15 13:50:26 +020067static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
68 int64_t sector_num, int nb_sectors,
69 QEMUIOVector *iov);
70static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
71 int64_t sector_num, int nb_sectors,
72 QEMUIOVector *iov);
bellardec530c82006-04-25 22:36:06 +000073
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +010074static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
75 QTAILQ_HEAD_INITIALIZER(bdrv_states);
blueswir17ee930d2008-09-17 19:04:14 +000076
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010077static QLIST_HEAD(, BlockDriver) bdrv_drivers =
78 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000079
Markus Armbrusterf9092b12010-06-25 10:33:39 +020080/* The device to use for VM snapshots */
81static BlockDriverState *bs_snapshots;
82
Markus Armbrustereb852012009-10-27 18:41:44 +010083/* If non-zero, use only whitelisted block drivers */
84static int use_bdrv_whitelist;
85
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000086#ifdef _WIN32
87static int is_windows_drive_prefix(const char *filename)
88{
89 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
90 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
91 filename[1] == ':');
92}
93
94int is_windows_drive(const char *filename)
95{
96 if (is_windows_drive_prefix(filename) &&
97 filename[2] == '\0')
98 return 1;
99 if (strstart(filename, "\\\\.\\", NULL) ||
100 strstart(filename, "//./", NULL))
101 return 1;
102 return 0;
103}
104#endif
105
106/* check if the path starts with "<protocol>:" */
107static int path_has_protocol(const char *path)
108{
109#ifdef _WIN32
110 if (is_windows_drive(path) ||
111 is_windows_drive_prefix(path)) {
112 return 0;
113 }
114#endif
115
116 return strchr(path, ':') != NULL;
117}
118
bellard83f64092006-08-01 16:21:11 +0000119int path_is_absolute(const char *path)
120{
121 const char *p;
bellard21664422007-01-07 18:22:37 +0000122#ifdef _WIN32
123 /* specific case for names like: "\\.\d:" */
124 if (*path == '/' || *path == '\\')
125 return 1;
126#endif
bellard83f64092006-08-01 16:21:11 +0000127 p = strchr(path, ':');
128 if (p)
129 p++;
130 else
131 p = path;
bellard3b9f94e2007-01-07 17:27:07 +0000132#ifdef _WIN32
133 return (*p == '/' || *p == '\\');
134#else
135 return (*p == '/');
136#endif
bellard83f64092006-08-01 16:21:11 +0000137}
138
139/* if filename is absolute, just copy it to dest. Otherwise, build a
140 path to it by considering it is relative to base_path. URL are
141 supported. */
142void path_combine(char *dest, int dest_size,
143 const char *base_path,
144 const char *filename)
145{
146 const char *p, *p1;
147 int len;
148
149 if (dest_size <= 0)
150 return;
151 if (path_is_absolute(filename)) {
152 pstrcpy(dest, dest_size, filename);
153 } else {
154 p = strchr(base_path, ':');
155 if (p)
156 p++;
157 else
158 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000159 p1 = strrchr(base_path, '/');
160#ifdef _WIN32
161 {
162 const char *p2;
163 p2 = strrchr(base_path, '\\');
164 if (!p1 || p2 > p1)
165 p1 = p2;
166 }
167#endif
bellard83f64092006-08-01 16:21:11 +0000168 if (p1)
169 p1++;
170 else
171 p1 = base_path;
172 if (p1 > p)
173 p = p1;
174 len = p - base_path;
175 if (len > dest_size - 1)
176 len = dest_size - 1;
177 memcpy(dest, base_path, len);
178 dest[len] = '\0';
179 pstrcat(dest, dest_size, filename);
180 }
181}
182
Anthony Liguori5efa9d52009-05-09 17:03:42 -0500183void bdrv_register(BlockDriver *bdrv)
bellardea2384d2004-08-01 21:59:26 +0000184{
Kevin Wolf68485422011-06-30 10:05:46 +0200185 if (bdrv->bdrv_co_readv) {
186 /* Emulate AIO by coroutines, and sync by AIO */
187 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
188 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
189 bdrv->bdrv_read = bdrv_read_em;
190 bdrv->bdrv_write = bdrv_write_em;
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200191 } else {
192 bdrv->bdrv_co_readv = bdrv_co_readv_em;
193 bdrv->bdrv_co_writev = bdrv_co_writev_em;
194
195 if (!bdrv->bdrv_aio_readv) {
196 /* add AIO emulation layer */
197 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
198 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
199 } else if (!bdrv->bdrv_read) {
200 /* add synchronous IO emulation layer */
201 bdrv->bdrv_read = bdrv_read_em;
202 bdrv->bdrv_write = bdrv_write_em;
203 }
bellard83f64092006-08-01 16:21:11 +0000204 }
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +0200205
206 if (!bdrv->bdrv_aio_flush)
207 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
208
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100209 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000210}
bellardb3380822004-03-14 21:38:54 +0000211
212/* create a new block device (by default it is empty) */
213BlockDriverState *bdrv_new(const char *device_name)
bellardfc01f7e2003-06-30 10:03:06 +0000214{
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100215 BlockDriverState *bs;
bellardb3380822004-03-14 21:38:54 +0000216
217 bs = qemu_mallocz(sizeof(BlockDriverState));
bellardb3380822004-03-14 21:38:54 +0000218 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellardea2384d2004-08-01 21:59:26 +0000219 if (device_name[0] != '\0') {
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100220 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellardea2384d2004-08-01 21:59:26 +0000221 }
bellardb3380822004-03-14 21:38:54 +0000222 return bs;
223}
224
bellardea2384d2004-08-01 21:59:26 +0000225BlockDriver *bdrv_find_format(const char *format_name)
226{
227 BlockDriver *drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100228 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
229 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000230 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100231 }
bellardea2384d2004-08-01 21:59:26 +0000232 }
233 return NULL;
234}
235
Markus Armbrustereb852012009-10-27 18:41:44 +0100236static int bdrv_is_whitelisted(BlockDriver *drv)
237{
238 static const char *whitelist[] = {
239 CONFIG_BDRV_WHITELIST
240 };
241 const char **p;
242
243 if (!whitelist[0])
244 return 1; /* no whitelist, anything goes */
245
246 for (p = whitelist; *p; p++) {
247 if (!strcmp(drv->format_name, *p)) {
248 return 1;
249 }
250 }
251 return 0;
252}
253
254BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
255{
256 BlockDriver *drv = bdrv_find_format(format_name);
257 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
258}
259
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200260int bdrv_create(BlockDriver *drv, const char* filename,
261 QEMUOptionParameter *options)
bellardea2384d2004-08-01 21:59:26 +0000262{
263 if (!drv->bdrv_create)
264 return -ENOTSUP;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200265
266 return drv->bdrv_create(filename, options);
bellardea2384d2004-08-01 21:59:26 +0000267}
268
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200269int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
270{
271 BlockDriver *drv;
272
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900273 drv = bdrv_find_protocol(filename);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200274 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000275 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200276 }
277
278 return bdrv_create(drv, filename, options);
279}
280
bellardd5249392004-08-03 21:14:23 +0000281#ifdef _WIN32
bellard95389c82005-12-18 18:28:15 +0000282void get_tmp_filename(char *filename, int size)
bellardd5249392004-08-03 21:14:23 +0000283{
bellard3b9f94e2007-01-07 17:27:07 +0000284 char temp_dir[MAX_PATH];
ths3b46e622007-09-17 08:09:54 +0000285
bellard3b9f94e2007-01-07 17:27:07 +0000286 GetTempPath(MAX_PATH, temp_dir);
287 GetTempFileName(temp_dir, "qem", 0, filename);
bellardd5249392004-08-03 21:14:23 +0000288}
289#else
bellard95389c82005-12-18 18:28:15 +0000290void get_tmp_filename(char *filename, int size)
bellardea2384d2004-08-01 21:59:26 +0000291{
292 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000293 const char *tmpdir;
bellardd5249392004-08-03 21:14:23 +0000294 /* XXX: race condition possible */
aurel320badc1e2008-03-10 00:05:34 +0000295 tmpdir = getenv("TMPDIR");
296 if (!tmpdir)
297 tmpdir = "/tmp";
298 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
bellardea2384d2004-08-01 21:59:26 +0000299 fd = mkstemp(filename);
300 close(fd);
301}
bellardd5249392004-08-03 21:14:23 +0000302#endif
bellardea2384d2004-08-01 21:59:26 +0000303
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200304/*
305 * Detect host devices. By convention, /dev/cdrom[N] is always
306 * recognized as a host CDROM.
307 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200308static BlockDriver *find_hdev_driver(const char *filename)
309{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200310 int score_max = 0, score;
311 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200312
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100313 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200314 if (d->bdrv_probe_device) {
315 score = d->bdrv_probe_device(filename);
316 if (score > score_max) {
317 score_max = score;
318 drv = d;
319 }
320 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200321 }
322
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200323 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200324}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200325
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900326BlockDriver *bdrv_find_protocol(const char *filename)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200327{
328 BlockDriver *drv1;
329 char protocol[128];
330 int len;
331 const char *p;
332
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200333 /* TODO Drivers without bdrv_file_open must be specified explicitly */
334
Christoph Hellwig39508e72010-06-23 12:25:17 +0200335 /*
336 * XXX(hch): we really should not let host device detection
337 * override an explicit protocol specification, but moving this
338 * later breaks access to device names with colons in them.
339 * Thanks to the brain-dead persistent naming schemes on udev-
340 * based Linux systems those actually are quite common.
341 */
342 drv1 = find_hdev_driver(filename);
343 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200344 return drv1;
345 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200346
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000347 if (!path_has_protocol(filename)) {
Christoph Hellwig39508e72010-06-23 12:25:17 +0200348 return bdrv_find_format("file");
349 }
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000350 p = strchr(filename, ':');
351 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200352 len = p - filename;
353 if (len > sizeof(protocol) - 1)
354 len = sizeof(protocol) - 1;
355 memcpy(protocol, filename, len);
356 protocol[len] = '\0';
357 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
358 if (drv1->protocol_name &&
359 !strcmp(drv1->protocol_name, protocol)) {
360 return drv1;
361 }
362 }
363 return NULL;
364}
365
Stefan Weilc98ac352010-07-21 21:51:51 +0200366static int find_image_format(const char *filename, BlockDriver **pdrv)
bellardea2384d2004-08-01 21:59:26 +0000367{
bellard83f64092006-08-01 16:21:11 +0000368 int ret, score, score_max;
bellardea2384d2004-08-01 21:59:26 +0000369 BlockDriver *drv1, *drv;
bellard83f64092006-08-01 16:21:11 +0000370 uint8_t buf[2048];
371 BlockDriverState *bs;
ths3b46e622007-09-17 08:09:54 +0000372
Naphtali Spreif5edb012010-01-17 16:48:13 +0200373 ret = bdrv_file_open(&bs, filename, 0);
Stefan Weilc98ac352010-07-21 21:51:51 +0200374 if (ret < 0) {
375 *pdrv = NULL;
376 return ret;
377 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700378
Kevin Wolf08a00552010-06-01 18:37:31 +0200379 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
380 if (bs->sg || !bdrv_is_inserted(bs)) {
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700381 bdrv_delete(bs);
Stefan Weilc98ac352010-07-21 21:51:51 +0200382 drv = bdrv_find_format("raw");
383 if (!drv) {
384 ret = -ENOENT;
385 }
386 *pdrv = drv;
387 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700388 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700389
bellard83f64092006-08-01 16:21:11 +0000390 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
391 bdrv_delete(bs);
392 if (ret < 0) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200393 *pdrv = NULL;
394 return ret;
bellard83f64092006-08-01 16:21:11 +0000395 }
396
bellardea2384d2004-08-01 21:59:26 +0000397 score_max = 0;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200398 drv = NULL;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100399 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard83f64092006-08-01 16:21:11 +0000400 if (drv1->bdrv_probe) {
401 score = drv1->bdrv_probe(buf, ret, filename);
402 if (score > score_max) {
403 score_max = score;
404 drv = drv1;
405 }
bellardea2384d2004-08-01 21:59:26 +0000406 }
407 }
Stefan Weilc98ac352010-07-21 21:51:51 +0200408 if (!drv) {
409 ret = -ENOENT;
410 }
411 *pdrv = drv;
412 return ret;
bellardea2384d2004-08-01 21:59:26 +0000413}
414
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100415/**
416 * Set the current 'total_sectors' value
417 */
418static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
419{
420 BlockDriver *drv = bs->drv;
421
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700422 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
423 if (bs->sg)
424 return 0;
425
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100426 /* query actual device if possible, otherwise just trust the hint */
427 if (drv->bdrv_getlength) {
428 int64_t length = drv->bdrv_getlength(bs);
429 if (length < 0) {
430 return length;
431 }
432 hint = length >> BDRV_SECTOR_BITS;
433 }
434
435 bs->total_sectors = hint;
436 return 0;
437}
438
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200439/*
Kevin Wolf57915332010-04-14 15:24:50 +0200440 * Common part for opening disk images and files
441 */
442static int bdrv_open_common(BlockDriverState *bs, const char *filename,
443 int flags, BlockDriver *drv)
444{
445 int ret, open_flags;
446
447 assert(drv != NULL);
448
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200449 bs->file = NULL;
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100450 bs->total_sectors = 0;
Kevin Wolf57915332010-04-14 15:24:50 +0200451 bs->encrypted = 0;
452 bs->valid_key = 0;
453 bs->open_flags = flags;
454 /* buffer_alignment defaulted to 512, drivers can change this value */
455 bs->buffer_alignment = 512;
456
457 pstrcpy(bs->filename, sizeof(bs->filename), filename);
458
459 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
460 return -ENOTSUP;
461 }
462
463 bs->drv = drv;
464 bs->opaque = qemu_mallocz(drv->instance_size);
465
Christoph Hellwiga6599792011-05-17 18:04:06 +0200466 if (flags & BDRV_O_CACHE_WB)
Kevin Wolf57915332010-04-14 15:24:50 +0200467 bs->enable_write_cache = 1;
468
469 /*
470 * Clear flags that are internal to the block layer before opening the
471 * image.
472 */
473 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
474
475 /*
Stefan Weilebabb672011-04-26 10:29:36 +0200476 * Snapshots should be writable.
Kevin Wolf57915332010-04-14 15:24:50 +0200477 */
478 if (bs->is_temporary) {
479 open_flags |= BDRV_O_RDWR;
480 }
481
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200482 /* Open the image, either directly or using a protocol */
483 if (drv->bdrv_file_open) {
484 ret = drv->bdrv_file_open(bs, filename, open_flags);
485 } else {
486 ret = bdrv_file_open(&bs->file, filename, open_flags);
487 if (ret >= 0) {
488 ret = drv->bdrv_open(bs, open_flags);
489 }
490 }
491
Kevin Wolf57915332010-04-14 15:24:50 +0200492 if (ret < 0) {
493 goto free_and_fail;
494 }
495
496 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100497
498 ret = refresh_total_sectors(bs, bs->total_sectors);
499 if (ret < 0) {
500 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200501 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100502
Kevin Wolf57915332010-04-14 15:24:50 +0200503#ifndef _WIN32
504 if (bs->is_temporary) {
505 unlink(filename);
506 }
507#endif
508 return 0;
509
510free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200511 if (bs->file) {
512 bdrv_delete(bs->file);
513 bs->file = NULL;
514 }
Kevin Wolf57915332010-04-14 15:24:50 +0200515 qemu_free(bs->opaque);
516 bs->opaque = NULL;
517 bs->drv = NULL;
518 return ret;
519}
520
521/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200522 * Opens a file using a protocol (file, host_device, nbd, ...)
523 */
bellard83f64092006-08-01 16:21:11 +0000524int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000525{
bellard83f64092006-08-01 16:21:11 +0000526 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200527 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000528 int ret;
529
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900530 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200531 if (!drv) {
532 return -ENOENT;
533 }
534
bellard83f64092006-08-01 16:21:11 +0000535 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200536 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000537 if (ret < 0) {
538 bdrv_delete(bs);
539 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000540 }
aliguori71d07702009-03-03 17:37:16 +0000541 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000542 *pbs = bs;
543 return 0;
bellardea2384d2004-08-01 21:59:26 +0000544}
bellardfc01f7e2003-06-30 10:03:06 +0000545
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200546/*
547 * Opens a disk image (raw, qcow2, vmdk, ...)
548 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200549int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
550 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000551{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200552 int ret;
bellard712e7872005-04-28 21:09:32 +0000553
bellard83f64092006-08-01 16:21:11 +0000554 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000555 BlockDriverState *bs1;
556 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000557 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200558 BlockDriver *bdrv_qcow2;
559 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200560 char tmp_filename[PATH_MAX];
561 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000562
bellardea2384d2004-08-01 21:59:26 +0000563 /* if snapshot, we create a temporary backing file and open it
564 instead of opening 'filename' directly */
565
566 /* if there is a backing file, use it */
567 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200568 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000569 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000570 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000571 return ret;
bellardea2384d2004-08-01 21:59:26 +0000572 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200573 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000574
575 if (bs1->drv && bs1->drv->protocol_name)
576 is_protocol = 1;
577
bellardea2384d2004-08-01 21:59:26 +0000578 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000579
bellardea2384d2004-08-01 21:59:26 +0000580 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
aliguori7c96d462008-09-12 17:54:13 +0000581
582 /* Real path is meaningless for protocols */
583 if (is_protocol)
584 snprintf(backing_filename, sizeof(backing_filename),
585 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000586 else if (!realpath(filename, backing_filename))
587 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000588
Kevin Wolf91a073a2009-05-27 14:48:06 +0200589 bdrv_qcow2 = bdrv_find_format("qcow2");
590 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
591
Jes Sorensen3e829902010-05-27 16:20:30 +0200592 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200593 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
594 if (drv) {
595 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
596 drv->format_name);
597 }
598
599 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200600 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000601 if (ret < 0) {
602 return ret;
bellardea2384d2004-08-01 21:59:26 +0000603 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200604
bellardea2384d2004-08-01 21:59:26 +0000605 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200606 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000607 bs->is_temporary = 1;
608 }
bellard712e7872005-04-28 21:09:32 +0000609
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200610 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200611 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200612 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000613 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100614
aliguori51d7c002009-03-05 23:00:29 +0000615 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000616 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000617 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200618
619 /* Open the image */
620 ret = bdrv_open_common(bs, filename, flags, drv);
621 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100622 goto unlink_and_fail;
623 }
624
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200625 /* If there is a backing file, use it */
626 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
627 char backing_filename[PATH_MAX];
628 int back_flags;
629 BlockDriver *back_drv = NULL;
630
631 bs->backing_hd = bdrv_new("");
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000632
633 if (path_has_protocol(bs->backing_file)) {
634 pstrcpy(backing_filename, sizeof(backing_filename),
635 bs->backing_file);
636 } else {
637 path_combine(backing_filename, sizeof(backing_filename),
638 filename, bs->backing_file);
639 }
640
641 if (bs->backing_format[0] != '\0') {
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200642 back_drv = bdrv_find_format(bs->backing_format);
Stefan Hajnoczidf2dbb42010-12-02 16:54:13 +0000643 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200644
645 /* backing files always opened read-only */
646 back_flags =
647 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
648
649 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
650 if (ret < 0) {
651 bdrv_close(bs);
652 return ret;
653 }
654 if (bs->is_temporary) {
655 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
656 } else {
657 /* base image inherits from "parent" */
658 bs->backing_hd->keep_read_only = bs->keep_read_only;
659 }
660 }
661
662 if (!bdrv_key_required(bs)) {
663 /* call the change callback */
664 bs->media_changed = 1;
665 if (bs->change_cb)
Christoph Hellwigdb97ee62011-01-24 13:32:41 +0100666 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200667 }
668
669 return 0;
670
671unlink_and_fail:
672 if (bs->is_temporary) {
673 unlink(filename);
674 }
675 return ret;
676}
677
bellardfc01f7e2003-06-30 10:03:06 +0000678void bdrv_close(BlockDriverState *bs)
679{
bellard19cb3732006-08-19 11:45:59 +0000680 if (bs->drv) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200681 if (bs == bs_snapshots) {
682 bs_snapshots = NULL;
683 }
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100684 if (bs->backing_hd) {
bellardea2384d2004-08-01 21:59:26 +0000685 bdrv_delete(bs->backing_hd);
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +0100686 bs->backing_hd = NULL;
687 }
bellardea2384d2004-08-01 21:59:26 +0000688 bs->drv->bdrv_close(bs);
689 qemu_free(bs->opaque);
690#ifdef _WIN32
691 if (bs->is_temporary) {
692 unlink(bs->filename);
693 }
bellard67b915a2004-03-31 23:37:16 +0000694#endif
bellardea2384d2004-08-01 21:59:26 +0000695 bs->opaque = NULL;
696 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +0000697
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200698 if (bs->file != NULL) {
699 bdrv_close(bs->file);
700 }
701
bellardb3380822004-03-14 21:38:54 +0000702 /* call the change callback */
bellard19cb3732006-08-19 11:45:59 +0000703 bs->media_changed = 1;
bellardb3380822004-03-14 21:38:54 +0000704 if (bs->change_cb)
Christoph Hellwigdb97ee62011-01-24 13:32:41 +0100705 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
bellardb3380822004-03-14 21:38:54 +0000706 }
707}
708
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +0900709void bdrv_close_all(void)
710{
711 BlockDriverState *bs;
712
713 QTAILQ_FOREACH(bs, &bdrv_states, list) {
714 bdrv_close(bs);
715 }
716}
717
Ryan Harperd22b2f42011-03-29 20:51:47 -0500718/* make a BlockDriverState anonymous by removing from bdrv_state list.
719 Also, NULL terminate the device_name to prevent double remove */
720void bdrv_make_anon(BlockDriverState *bs)
721{
722 if (bs->device_name[0] != '\0') {
723 QTAILQ_REMOVE(&bdrv_states, bs, list);
724 }
725 bs->device_name[0] = '\0';
726}
727
bellardb3380822004-03-14 21:38:54 +0000728void bdrv_delete(BlockDriverState *bs)
729{
Markus Armbruster18846de2010-06-29 16:58:30 +0200730 assert(!bs->peer);
731
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100732 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -0500733 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +0000734
bellardb3380822004-03-14 21:38:54 +0000735 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200736 if (bs->file != NULL) {
737 bdrv_delete(bs->file);
738 }
739
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200740 assert(bs != bs_snapshots);
bellardb3380822004-03-14 21:38:54 +0000741 qemu_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +0000742}
743
Markus Armbruster18846de2010-06-29 16:58:30 +0200744int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
745{
746 if (bs->peer) {
747 return -EBUSY;
748 }
749 bs->peer = qdev;
750 return 0;
751}
752
753void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
754{
755 assert(bs->peer == qdev);
756 bs->peer = NULL;
Markus Armbrustera19712b2011-07-20 18:23:36 +0200757 bs->change_cb = NULL;
758 bs->change_opaque = NULL;
Markus Armbruster18846de2010-06-29 16:58:30 +0200759}
760
761DeviceState *bdrv_get_attached(BlockDriverState *bs)
762{
763 return bs->peer;
764}
765
aliguorie97fc192009-04-21 23:11:50 +0000766/*
767 * Run consistency checks on an image
768 *
Kevin Wolfe076f332010-06-29 11:43:13 +0200769 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +0200770 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +0200771 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +0000772 */
Kevin Wolfe076f332010-06-29 11:43:13 +0200773int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
aliguorie97fc192009-04-21 23:11:50 +0000774{
775 if (bs->drv->bdrv_check == NULL) {
776 return -ENOTSUP;
777 }
778
Kevin Wolfe076f332010-06-29 11:43:13 +0200779 memset(res, 0, sizeof(*res));
Kevin Wolf9ac228e2010-06-29 12:37:54 +0200780 return bs->drv->bdrv_check(bs, res);
aliguorie97fc192009-04-21 23:11:50 +0000781}
782
Kevin Wolf8a426612010-07-16 17:17:01 +0200783#define COMMIT_BUF_SECTORS 2048
784
bellard33e39632003-07-06 17:15:21 +0000785/* commit COW file into the raw image */
786int bdrv_commit(BlockDriverState *bs)
787{
bellard19cb3732006-08-19 11:45:59 +0000788 BlockDriver *drv = bs->drv;
Kevin Wolfee181192010-08-05 13:05:22 +0200789 BlockDriver *backing_drv;
Kevin Wolf8a426612010-07-16 17:17:01 +0200790 int64_t sector, total_sectors;
791 int n, ro, open_flags;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200792 int ret = 0, rw_ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +0200793 uint8_t *buf;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200794 char filename[1024];
795 BlockDriverState *bs_rw, *bs_ro;
bellard33e39632003-07-06 17:15:21 +0000796
bellard19cb3732006-08-19 11:45:59 +0000797 if (!drv)
798 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200799
800 if (!bs->backing_hd) {
801 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +0000802 }
803
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200804 if (bs->backing_hd->keep_read_only) {
805 return -EACCES;
806 }
Kevin Wolfee181192010-08-05 13:05:22 +0200807
808 backing_drv = bs->backing_hd->drv;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200809 ro = bs->backing_hd->read_only;
810 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
811 open_flags = bs->backing_hd->open_flags;
812
813 if (ro) {
814 /* re-open as RW */
815 bdrv_delete(bs->backing_hd);
816 bs->backing_hd = NULL;
817 bs_rw = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200818 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
819 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200820 if (rw_ret < 0) {
821 bdrv_delete(bs_rw);
822 /* try to re-open read-only */
823 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200824 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
825 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200826 if (ret < 0) {
827 bdrv_delete(bs_ro);
828 /* drive not functional anymore */
829 bs->drv = NULL;
830 return ret;
831 }
832 bs->backing_hd = bs_ro;
833 return rw_ret;
834 }
835 bs->backing_hd = bs_rw;
bellard33e39632003-07-06 17:15:21 +0000836 }
bellardea2384d2004-08-01 21:59:26 +0000837
Jan Kiszka6ea44302009-11-30 18:21:19 +0100838 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Kevin Wolf8a426612010-07-16 17:17:01 +0200839 buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +0000840
Kevin Wolf8a426612010-07-16 17:17:01 +0200841 for (sector = 0; sector < total_sectors; sector += n) {
842 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
843
844 if (bdrv_read(bs, sector, buf, n) != 0) {
845 ret = -EIO;
846 goto ro_cleanup;
847 }
848
849 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
850 ret = -EIO;
851 goto ro_cleanup;
852 }
bellardea2384d2004-08-01 21:59:26 +0000853 }
854 }
bellard95389c82005-12-18 18:28:15 +0000855
Christoph Hellwig1d449522010-01-17 12:32:30 +0100856 if (drv->bdrv_make_empty) {
857 ret = drv->bdrv_make_empty(bs);
858 bdrv_flush(bs);
859 }
bellard95389c82005-12-18 18:28:15 +0000860
Christoph Hellwig3f5075a2010-01-12 13:49:23 +0100861 /*
862 * Make sure all data we wrote to the backing device is actually
863 * stable on disk.
864 */
865 if (bs->backing_hd)
866 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200867
868ro_cleanup:
Kevin Wolf8a426612010-07-16 17:17:01 +0200869 qemu_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200870
871 if (ro) {
872 /* re-open as RO */
873 bdrv_delete(bs->backing_hd);
874 bs->backing_hd = NULL;
875 bs_ro = bdrv_new("");
Kevin Wolfee181192010-08-05 13:05:22 +0200876 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
877 backing_drv);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +0200878 if (ret < 0) {
879 bdrv_delete(bs_ro);
880 /* drive not functional anymore */
881 bs->drv = NULL;
882 return ret;
883 }
884 bs->backing_hd = bs_ro;
885 bs->backing_hd->keep_read_only = 0;
886 }
887
Christoph Hellwig1d449522010-01-17 12:32:30 +0100888 return ret;
bellard33e39632003-07-06 17:15:21 +0000889}
890
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +0200891void bdrv_commit_all(void)
892{
893 BlockDriverState *bs;
894
895 QTAILQ_FOREACH(bs, &bdrv_states, list) {
896 bdrv_commit(bs);
897 }
898}
899
Kevin Wolf756e6732010-01-12 12:55:17 +0100900/*
901 * Return values:
902 * 0 - success
903 * -EINVAL - backing format specified, but no file
904 * -ENOSPC - can't update the backing file because no space is left in the
905 * image file header
906 * -ENOTSUP - format driver doesn't support changing the backing file
907 */
908int bdrv_change_backing_file(BlockDriverState *bs,
909 const char *backing_file, const char *backing_fmt)
910{
911 BlockDriver *drv = bs->drv;
912
913 if (drv->bdrv_change_backing_file != NULL) {
914 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
915 } else {
916 return -ENOTSUP;
917 }
918}
919
aliguori71d07702009-03-03 17:37:16 +0000920static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
921 size_t size)
922{
923 int64_t len;
924
925 if (!bdrv_is_inserted(bs))
926 return -ENOMEDIUM;
927
928 if (bs->growable)
929 return 0;
930
931 len = bdrv_getlength(bs);
932
Kevin Wolffbb7b4e2009-05-08 14:47:24 +0200933 if (offset < 0)
934 return -EIO;
935
936 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +0000937 return -EIO;
938
939 return 0;
940}
941
942static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
943 int nb_sectors)
944{
Jes Sorenseneb5a3162010-05-27 16:20:31 +0200945 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
946 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +0000947}
948
bellard19cb3732006-08-19 11:45:59 +0000949/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +0000950int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +0000951 uint8_t *buf, int nb_sectors)
952{
bellardea2384d2004-08-01 21:59:26 +0000953 BlockDriver *drv = bs->drv;
954
bellard19cb3732006-08-19 11:45:59 +0000955 if (!drv)
956 return -ENOMEDIUM;
aliguori71d07702009-03-03 17:37:16 +0000957 if (bdrv_check_request(bs, sector_num, nb_sectors))
958 return -EIO;
bellardb3380822004-03-14 21:38:54 +0000959
aliguorieda578e2009-03-12 19:57:16 +0000960 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
bellardfc01f7e2003-06-30 10:03:06 +0000961}
962
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +0200963static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +0100964 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +0200965{
966 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +0100967 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +0100968
Jan Kiszka6ea44302009-11-30 18:21:19 +0100969 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +0100970 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +0100971
972 for (; start <= end; start++) {
Jan Kiszkac6d22832009-11-30 18:21:20 +0100973 idx = start / (sizeof(unsigned long) * 8);
974 bit = start % (sizeof(unsigned long) * 8);
975 val = bs->dirty_bitmap[idx];
976 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -0200977 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +0200978 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -0200979 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +0200980 }
Jan Kiszkac6d22832009-11-30 18:21:20 +0100981 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -0200982 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +0200983 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -0200984 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +0200985 }
Jan Kiszkac6d22832009-11-30 18:21:20 +0100986 }
987 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +0200988 }
989}
990
ths5fafdf22007-09-16 21:08:06 +0000991/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +0000992 -EIO generic I/O error (may happen for all errors)
993 -ENOMEDIUM No media inserted.
994 -EINVAL Invalid sector number or nb_sectors
995 -EACCES Trying to write a read-only device
996*/
ths5fafdf22007-09-16 21:08:06 +0000997int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +0000998 const uint8_t *buf, int nb_sectors)
999{
bellard83f64092006-08-01 16:21:11 +00001000 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00001001 if (!bs->drv)
1002 return -ENOMEDIUM;
bellard0849bf02003-06-30 23:17:31 +00001003 if (bs->read_only)
bellard19cb3732006-08-19 11:45:59 +00001004 return -EACCES;
aliguori71d07702009-03-03 17:37:16 +00001005 if (bdrv_check_request(bs, sector_num, nb_sectors))
1006 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001007
Jan Kiszkac6d22832009-11-30 18:21:20 +01001008 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001009 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1010 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001011
Kevin Wolf294cc352010-04-28 14:34:01 +02001012 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1013 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1014 }
1015
aliguori42fb2802009-01-15 20:43:39 +00001016 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
bellard83f64092006-08-01 16:21:11 +00001017}
1018
aliguorieda578e2009-03-12 19:57:16 +00001019int bdrv_pread(BlockDriverState *bs, int64_t offset,
1020 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001021{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001022 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001023 int len, nb_sectors, count;
1024 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001025 int ret;
bellard83f64092006-08-01 16:21:11 +00001026
1027 count = count1;
1028 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001029 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001030 if (len > count)
1031 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001032 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001033 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001034 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1035 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001036 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00001037 count -= len;
1038 if (count == 0)
1039 return count1;
1040 sector_num++;
1041 buf += len;
1042 }
1043
1044 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001045 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001046 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001047 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1048 return ret;
bellard83f64092006-08-01 16:21:11 +00001049 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001050 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001051 buf += len;
1052 count -= len;
1053 }
1054
1055 /* add data from the last sector */
1056 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001057 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1058 return ret;
bellard83f64092006-08-01 16:21:11 +00001059 memcpy(buf, tmp_buf, count);
1060 }
1061 return count1;
1062}
1063
aliguorieda578e2009-03-12 19:57:16 +00001064int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1065 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00001066{
Jan Kiszka6ea44302009-11-30 18:21:19 +01001067 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00001068 int len, nb_sectors, count;
1069 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001070 int ret;
bellard83f64092006-08-01 16:21:11 +00001071
1072 count = count1;
1073 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001074 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00001075 if (len > count)
1076 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001077 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001078 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001079 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1080 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001081 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001082 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1083 return ret;
bellard83f64092006-08-01 16:21:11 +00001084 count -= len;
1085 if (count == 0)
1086 return count1;
1087 sector_num++;
1088 buf += len;
1089 }
1090
1091 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01001092 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001093 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001094 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1095 return ret;
bellard83f64092006-08-01 16:21:11 +00001096 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01001097 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00001098 buf += len;
1099 count -= len;
1100 }
1101
1102 /* add data from the last sector */
1103 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001104 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1105 return ret;
bellard83f64092006-08-01 16:21:11 +00001106 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01001107 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1108 return ret;
bellard83f64092006-08-01 16:21:11 +00001109 }
1110 return count1;
1111}
bellard83f64092006-08-01 16:21:11 +00001112
Kevin Wolff08145f2010-06-16 16:38:15 +02001113/*
1114 * Writes to the file and ensures that no writes are reordered across this
1115 * request (acts as a barrier)
1116 *
1117 * Returns 0 on success, -errno in error cases.
1118 */
1119int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1120 const void *buf, int count)
1121{
1122 int ret;
1123
1124 ret = bdrv_pwrite(bs, offset, buf, count);
1125 if (ret < 0) {
1126 return ret;
1127 }
1128
1129 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1130 if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1131 bdrv_flush(bs);
1132 }
1133
1134 return 0;
1135}
1136
Kevin Wolfda1fa912011-07-14 17:27:13 +02001137int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1138 int nb_sectors, QEMUIOVector *qiov)
1139{
1140 BlockDriver *drv = bs->drv;
1141
1142 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1143
1144 if (!drv) {
1145 return -ENOMEDIUM;
1146 }
1147 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1148 return -EIO;
1149 }
1150
1151 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1152}
1153
1154int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1155 int nb_sectors, QEMUIOVector *qiov)
1156{
1157 BlockDriver *drv = bs->drv;
1158
1159 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1160
1161 if (!bs->drv) {
1162 return -ENOMEDIUM;
1163 }
1164 if (bs->read_only) {
1165 return -EACCES;
1166 }
1167 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1168 return -EIO;
1169 }
1170
1171 if (bs->dirty_bitmap) {
1172 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1173 }
1174
1175 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1176 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1177 }
1178
1179 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1180}
1181
bellard83f64092006-08-01 16:21:11 +00001182/**
bellard83f64092006-08-01 16:21:11 +00001183 * Truncate file to 'offset' bytes (needed only for file protocols)
1184 */
1185int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1186{
1187 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001188 int ret;
bellard83f64092006-08-01 16:21:11 +00001189 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001190 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00001191 if (!drv->bdrv_truncate)
1192 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02001193 if (bs->read_only)
1194 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02001195 if (bdrv_in_use(bs))
1196 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001197 ret = drv->bdrv_truncate(bs, offset);
1198 if (ret == 0) {
1199 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Christoph Hellwigdb97ee62011-01-24 13:32:41 +01001200 if (bs->change_cb) {
1201 bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1202 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001203 }
1204 return ret;
bellard83f64092006-08-01 16:21:11 +00001205}
1206
1207/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08001208 * Length of a allocated file in bytes. Sparse files are counted by actual
1209 * allocated space. Return < 0 if error or unknown.
1210 */
1211int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1212{
1213 BlockDriver *drv = bs->drv;
1214 if (!drv) {
1215 return -ENOMEDIUM;
1216 }
1217 if (drv->bdrv_get_allocated_file_size) {
1218 return drv->bdrv_get_allocated_file_size(bs);
1219 }
1220 if (bs->file) {
1221 return bdrv_get_allocated_file_size(bs->file);
1222 }
1223 return -ENOTSUP;
1224}
1225
1226/**
bellard83f64092006-08-01 16:21:11 +00001227 * Length of a file in bytes. Return < 0 if error or unknown.
1228 */
1229int64_t bdrv_getlength(BlockDriverState *bs)
1230{
1231 BlockDriver *drv = bs->drv;
1232 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001233 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001234
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001235 if (bs->growable || bs->removable) {
1236 if (drv->bdrv_getlength) {
1237 return drv->bdrv_getlength(bs);
1238 }
bellard83f64092006-08-01 16:21:11 +00001239 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01001240 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00001241}
1242
bellard19cb3732006-08-19 11:45:59 +00001243/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00001244void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00001245{
bellard19cb3732006-08-19 11:45:59 +00001246 int64_t length;
1247 length = bdrv_getlength(bs);
1248 if (length < 0)
1249 length = 0;
1250 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01001251 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00001252 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00001253}
bellardcf989512004-02-16 21:56:36 +00001254
aliguorif3d54fc2008-11-25 21:50:24 +00001255struct partition {
1256 uint8_t boot_ind; /* 0x80 - active */
1257 uint8_t head; /* starting head */
1258 uint8_t sector; /* starting sector */
1259 uint8_t cyl; /* starting cylinder */
1260 uint8_t sys_ind; /* What partition type */
1261 uint8_t end_head; /* end head */
1262 uint8_t end_sector; /* end sector */
1263 uint8_t end_cyl; /* end cylinder */
1264 uint32_t start_sect; /* starting sector counting from 0 */
1265 uint32_t nr_sects; /* nr of sectors in partition */
1266} __attribute__((packed));
1267
1268/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1269static int guess_disk_lchs(BlockDriverState *bs,
1270 int *pcylinders, int *pheads, int *psectors)
1271{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001272 uint8_t buf[BDRV_SECTOR_SIZE];
aliguorif3d54fc2008-11-25 21:50:24 +00001273 int ret, i, heads, sectors, cylinders;
1274 struct partition *p;
1275 uint32_t nr_sects;
blueswir1a38131b2008-12-05 17:56:40 +00001276 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001277
1278 bdrv_get_geometry(bs, &nb_sectors);
1279
1280 ret = bdrv_read(bs, 0, buf, 1);
1281 if (ret < 0)
1282 return -1;
1283 /* test msdos magic */
1284 if (buf[510] != 0x55 || buf[511] != 0xaa)
1285 return -1;
1286 for(i = 0; i < 4; i++) {
1287 p = ((struct partition *)(buf + 0x1be)) + i;
1288 nr_sects = le32_to_cpu(p->nr_sects);
1289 if (nr_sects && p->end_head) {
1290 /* We make the assumption that the partition terminates on
1291 a cylinder boundary */
1292 heads = p->end_head + 1;
1293 sectors = p->end_sector & 63;
1294 if (sectors == 0)
1295 continue;
1296 cylinders = nb_sectors / (heads * sectors);
1297 if (cylinders < 1 || cylinders > 16383)
1298 continue;
1299 *pheads = heads;
1300 *psectors = sectors;
1301 *pcylinders = cylinders;
1302#if 0
1303 printf("guessed geometry: LCHS=%d %d %d\n",
1304 cylinders, heads, sectors);
1305#endif
1306 return 0;
1307 }
1308 }
1309 return -1;
1310}
1311
1312void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1313{
1314 int translation, lba_detected = 0;
1315 int cylinders, heads, secs;
blueswir1a38131b2008-12-05 17:56:40 +00001316 uint64_t nb_sectors;
aliguorif3d54fc2008-11-25 21:50:24 +00001317
1318 /* if a geometry hint is available, use it */
1319 bdrv_get_geometry(bs, &nb_sectors);
1320 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1321 translation = bdrv_get_translation_hint(bs);
1322 if (cylinders != 0) {
1323 *pcyls = cylinders;
1324 *pheads = heads;
1325 *psecs = secs;
1326 } else {
1327 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1328 if (heads > 16) {
1329 /* if heads > 16, it means that a BIOS LBA
1330 translation was active, so the default
1331 hardware geometry is OK */
1332 lba_detected = 1;
1333 goto default_geometry;
1334 } else {
1335 *pcyls = cylinders;
1336 *pheads = heads;
1337 *psecs = secs;
1338 /* disable any translation to be in sync with
1339 the logical geometry */
1340 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1341 bdrv_set_translation_hint(bs,
1342 BIOS_ATA_TRANSLATION_NONE);
1343 }
1344 }
1345 } else {
1346 default_geometry:
1347 /* if no geometry, use a standard physical disk geometry */
1348 cylinders = nb_sectors / (16 * 63);
1349
1350 if (cylinders > 16383)
1351 cylinders = 16383;
1352 else if (cylinders < 2)
1353 cylinders = 2;
1354 *pcyls = cylinders;
1355 *pheads = 16;
1356 *psecs = 63;
1357 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1358 if ((*pcyls * *pheads) <= 131072) {
1359 bdrv_set_translation_hint(bs,
1360 BIOS_ATA_TRANSLATION_LARGE);
1361 } else {
1362 bdrv_set_translation_hint(bs,
1363 BIOS_ATA_TRANSLATION_LBA);
1364 }
1365 }
1366 }
1367 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1368 }
1369}
1370
ths5fafdf22007-09-16 21:08:06 +00001371void bdrv_set_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001372 int cyls, int heads, int secs)
1373{
1374 bs->cyls = cyls;
1375 bs->heads = heads;
1376 bs->secs = secs;
1377}
1378
bellard46d47672004-11-16 01:45:27 +00001379void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1380{
1381 bs->translation = translation;
1382}
1383
ths5fafdf22007-09-16 21:08:06 +00001384void bdrv_get_geometry_hint(BlockDriverState *bs,
bellardb3380822004-03-14 21:38:54 +00001385 int *pcyls, int *pheads, int *psecs)
1386{
1387 *pcyls = bs->cyls;
1388 *pheads = bs->heads;
1389 *psecs = bs->secs;
1390}
1391
Blue Swirl5bbdbb42011-02-12 20:43:32 +00001392/* Recognize floppy formats */
1393typedef struct FDFormat {
1394 FDriveType drive;
1395 uint8_t last_sect;
1396 uint8_t max_track;
1397 uint8_t max_head;
1398} FDFormat;
1399
1400static const FDFormat fd_formats[] = {
1401 /* First entry is default format */
1402 /* 1.44 MB 3"1/2 floppy disks */
1403 { FDRIVE_DRV_144, 18, 80, 1, },
1404 { FDRIVE_DRV_144, 20, 80, 1, },
1405 { FDRIVE_DRV_144, 21, 80, 1, },
1406 { FDRIVE_DRV_144, 21, 82, 1, },
1407 { FDRIVE_DRV_144, 21, 83, 1, },
1408 { FDRIVE_DRV_144, 22, 80, 1, },
1409 { FDRIVE_DRV_144, 23, 80, 1, },
1410 { FDRIVE_DRV_144, 24, 80, 1, },
1411 /* 2.88 MB 3"1/2 floppy disks */
1412 { FDRIVE_DRV_288, 36, 80, 1, },
1413 { FDRIVE_DRV_288, 39, 80, 1, },
1414 { FDRIVE_DRV_288, 40, 80, 1, },
1415 { FDRIVE_DRV_288, 44, 80, 1, },
1416 { FDRIVE_DRV_288, 48, 80, 1, },
1417 /* 720 kB 3"1/2 floppy disks */
1418 { FDRIVE_DRV_144, 9, 80, 1, },
1419 { FDRIVE_DRV_144, 10, 80, 1, },
1420 { FDRIVE_DRV_144, 10, 82, 1, },
1421 { FDRIVE_DRV_144, 10, 83, 1, },
1422 { FDRIVE_DRV_144, 13, 80, 1, },
1423 { FDRIVE_DRV_144, 14, 80, 1, },
1424 /* 1.2 MB 5"1/4 floppy disks */
1425 { FDRIVE_DRV_120, 15, 80, 1, },
1426 { FDRIVE_DRV_120, 18, 80, 1, },
1427 { FDRIVE_DRV_120, 18, 82, 1, },
1428 { FDRIVE_DRV_120, 18, 83, 1, },
1429 { FDRIVE_DRV_120, 20, 80, 1, },
1430 /* 720 kB 5"1/4 floppy disks */
1431 { FDRIVE_DRV_120, 9, 80, 1, },
1432 { FDRIVE_DRV_120, 11, 80, 1, },
1433 /* 360 kB 5"1/4 floppy disks */
1434 { FDRIVE_DRV_120, 9, 40, 1, },
1435 { FDRIVE_DRV_120, 9, 40, 0, },
1436 { FDRIVE_DRV_120, 10, 41, 1, },
1437 { FDRIVE_DRV_120, 10, 42, 1, },
1438 /* 320 kB 5"1/4 floppy disks */
1439 { FDRIVE_DRV_120, 8, 40, 1, },
1440 { FDRIVE_DRV_120, 8, 40, 0, },
1441 /* 360 kB must match 5"1/4 better than 3"1/2... */
1442 { FDRIVE_DRV_144, 9, 80, 0, },
1443 /* end */
1444 { FDRIVE_DRV_NONE, -1, -1, 0, },
1445};
1446
1447void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1448 int *max_track, int *last_sect,
1449 FDriveType drive_in, FDriveType *drive)
1450{
1451 const FDFormat *parse;
1452 uint64_t nb_sectors, size;
1453 int i, first_match, match;
1454
1455 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1456 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1457 /* User defined disk */
1458 } else {
1459 bdrv_get_geometry(bs, &nb_sectors);
1460 match = -1;
1461 first_match = -1;
1462 for (i = 0; ; i++) {
1463 parse = &fd_formats[i];
1464 if (parse->drive == FDRIVE_DRV_NONE) {
1465 break;
1466 }
1467 if (drive_in == parse->drive ||
1468 drive_in == FDRIVE_DRV_NONE) {
1469 size = (parse->max_head + 1) * parse->max_track *
1470 parse->last_sect;
1471 if (nb_sectors == size) {
1472 match = i;
1473 break;
1474 }
1475 if (first_match == -1) {
1476 first_match = i;
1477 }
1478 }
1479 }
1480 if (match == -1) {
1481 if (first_match == -1) {
1482 match = 1;
1483 } else {
1484 match = first_match;
1485 }
1486 parse = &fd_formats[match];
1487 }
1488 *nb_heads = parse->max_head + 1;
1489 *max_track = parse->max_track;
1490 *last_sect = parse->last_sect;
1491 *drive = parse->drive;
1492 }
1493}
1494
bellard46d47672004-11-16 01:45:27 +00001495int bdrv_get_translation_hint(BlockDriverState *bs)
1496{
1497 return bs->translation;
1498}
1499
Markus Armbrusterabd7f682010-06-02 18:55:17 +02001500void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1501 BlockErrorAction on_write_error)
1502{
1503 bs->on_read_error = on_read_error;
1504 bs->on_write_error = on_write_error;
1505}
1506
1507BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1508{
1509 return is_read ? bs->on_read_error : bs->on_write_error;
1510}
1511
Markus Armbruster7d0d6952010-06-25 13:42:14 +02001512void bdrv_set_removable(BlockDriverState *bs, int removable)
1513{
1514 bs->removable = removable;
1515 if (removable && bs == bs_snapshots) {
1516 bs_snapshots = NULL;
1517 }
1518}
1519
bellardb3380822004-03-14 21:38:54 +00001520int bdrv_is_removable(BlockDriverState *bs)
1521{
1522 return bs->removable;
1523}
1524
1525int bdrv_is_read_only(BlockDriverState *bs)
1526{
1527 return bs->read_only;
1528}
1529
ths985a03b2007-12-24 16:10:43 +00001530int bdrv_is_sg(BlockDriverState *bs)
1531{
1532 return bs->sg;
1533}
1534
Christoph Hellwige900a7b2009-09-04 19:01:15 +02001535int bdrv_enable_write_cache(BlockDriverState *bs)
1536{
1537 return bs->enable_write_cache;
1538}
1539
bellard19cb3732006-08-19 11:45:59 +00001540/* XXX: no longer used */
ths5fafdf22007-09-16 21:08:06 +00001541void bdrv_set_change_cb(BlockDriverState *bs,
Christoph Hellwigdb97ee62011-01-24 13:32:41 +01001542 void (*change_cb)(void *opaque, int reason),
1543 void *opaque)
bellardb3380822004-03-14 21:38:54 +00001544{
1545 bs->change_cb = change_cb;
1546 bs->change_opaque = opaque;
1547}
1548
bellardea2384d2004-08-01 21:59:26 +00001549int bdrv_is_encrypted(BlockDriverState *bs)
1550{
1551 if (bs->backing_hd && bs->backing_hd->encrypted)
1552 return 1;
1553 return bs->encrypted;
1554}
1555
aliguoric0f4ce72009-03-05 23:01:01 +00001556int bdrv_key_required(BlockDriverState *bs)
1557{
1558 BlockDriverState *backing_hd = bs->backing_hd;
1559
1560 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1561 return 1;
1562 return (bs->encrypted && !bs->valid_key);
1563}
1564
bellardea2384d2004-08-01 21:59:26 +00001565int bdrv_set_key(BlockDriverState *bs, const char *key)
1566{
1567 int ret;
1568 if (bs->backing_hd && bs->backing_hd->encrypted) {
1569 ret = bdrv_set_key(bs->backing_hd, key);
1570 if (ret < 0)
1571 return ret;
1572 if (!bs->encrypted)
1573 return 0;
1574 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02001575 if (!bs->encrypted) {
1576 return -EINVAL;
1577 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1578 return -ENOMEDIUM;
1579 }
aliguoric0f4ce72009-03-05 23:01:01 +00001580 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00001581 if (ret < 0) {
1582 bs->valid_key = 0;
1583 } else if (!bs->valid_key) {
1584 bs->valid_key = 1;
1585 /* call the change callback now, we skipped it on open */
1586 bs->media_changed = 1;
1587 if (bs->change_cb)
Christoph Hellwigdb97ee62011-01-24 13:32:41 +01001588 bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
aliguoribb5fc202009-03-05 23:01:15 +00001589 }
aliguoric0f4ce72009-03-05 23:01:01 +00001590 return ret;
bellardea2384d2004-08-01 21:59:26 +00001591}
1592
1593void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1594{
bellard19cb3732006-08-19 11:45:59 +00001595 if (!bs->drv) {
bellardea2384d2004-08-01 21:59:26 +00001596 buf[0] = '\0';
1597 } else {
1598 pstrcpy(buf, buf_size, bs->drv->format_name);
1599 }
1600}
1601
ths5fafdf22007-09-16 21:08:06 +00001602void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00001603 void *opaque)
1604{
1605 BlockDriver *drv;
1606
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01001607 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00001608 it(opaque, drv->format_name);
1609 }
1610}
1611
bellardb3380822004-03-14 21:38:54 +00001612BlockDriverState *bdrv_find(const char *name)
1613{
1614 BlockDriverState *bs;
1615
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001616 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1617 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00001618 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001619 }
bellardb3380822004-03-14 21:38:54 +00001620 }
1621 return NULL;
1622}
1623
Markus Armbruster2f399b02010-06-02 18:55:20 +02001624BlockDriverState *bdrv_next(BlockDriverState *bs)
1625{
1626 if (!bs) {
1627 return QTAILQ_FIRST(&bdrv_states);
1628 }
1629 return QTAILQ_NEXT(bs, list);
1630}
1631
aliguori51de9762009-03-05 23:00:43 +00001632void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00001633{
1634 BlockDriverState *bs;
1635
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001636 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00001637 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00001638 }
1639}
1640
bellardea2384d2004-08-01 21:59:26 +00001641const char *bdrv_get_device_name(BlockDriverState *bs)
1642{
1643 return bs->device_name;
1644}
1645
Kevin Wolf205ef792010-10-21 16:43:43 +02001646int bdrv_flush(BlockDriverState *bs)
pbrook7a6cba62006-06-04 11:39:07 +00001647{
Alexander Graf016f5cf2010-05-26 17:51:49 +02001648 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolf205ef792010-10-21 16:43:43 +02001649 return 0;
Alexander Graf016f5cf2010-05-26 17:51:49 +02001650 }
1651
Kevin Wolf205ef792010-10-21 16:43:43 +02001652 if (bs->drv && bs->drv->bdrv_flush) {
1653 return bs->drv->bdrv_flush(bs);
1654 }
1655
1656 /*
1657 * Some block drivers always operate in either writethrough or unsafe mode
1658 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1659 * the server works (because the behaviour is hardcoded or depends on
1660 * server-side configuration), so we can't ensure that everything is safe
1661 * on disk. Returning an error doesn't work because that would break guests
1662 * even if the server operates in writethrough mode.
1663 *
1664 * Let's hope the user knows what he's doing.
1665 */
1666 return 0;
pbrook7a6cba62006-06-04 11:39:07 +00001667}
1668
aliguoric6ca28d2008-10-06 13:55:43 +00001669void bdrv_flush_all(void)
1670{
1671 BlockDriverState *bs;
1672
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001673 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1674 if (bs->drv && !bdrv_is_read_only(bs) &&
1675 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
aliguoric6ca28d2008-10-06 13:55:43 +00001676 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001677 }
1678 }
aliguoric6ca28d2008-10-06 13:55:43 +00001679}
1680
Kevin Wolff2feebb2010-04-14 17:30:35 +02001681int bdrv_has_zero_init(BlockDriverState *bs)
1682{
1683 assert(bs->drv);
1684
Kevin Wolf336c1c12010-07-28 11:26:29 +02001685 if (bs->drv->bdrv_has_zero_init) {
1686 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02001687 }
1688
1689 return 1;
1690}
1691
Christoph Hellwigbb8bf762010-12-16 19:36:31 +01001692int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1693{
1694 if (!bs->drv) {
1695 return -ENOMEDIUM;
1696 }
1697 if (!bs->drv->bdrv_discard) {
1698 return 0;
1699 }
1700 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1701}
1702
thsf58c7b32008-06-05 21:53:49 +00001703/*
1704 * Returns true iff the specified sector is present in the disk image. Drivers
1705 * not implementing the functionality are assumed to not support backing files,
1706 * hence all their sectors are reported as allocated.
1707 *
1708 * 'pnum' is set to the number of sectors (including and immediately following
1709 * the specified sector) that are known to be in the same
1710 * allocated/unallocated state.
1711 *
1712 * 'nb_sectors' is the max value 'pnum' should be set to.
1713 */
1714int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1715 int *pnum)
1716{
1717 int64_t n;
1718 if (!bs->drv->bdrv_is_allocated) {
1719 if (sector_num >= bs->total_sectors) {
1720 *pnum = 0;
1721 return 0;
1722 }
1723 n = bs->total_sectors - sector_num;
1724 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1725 return 1;
1726 }
1727 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1728}
1729
Luiz Capitulino2582bfe2010-02-03 12:41:01 -02001730void bdrv_mon_event(const BlockDriverState *bdrv,
1731 BlockMonEventAction action, int is_read)
1732{
1733 QObject *data;
1734 const char *action_str;
1735
1736 switch (action) {
1737 case BDRV_ACTION_REPORT:
1738 action_str = "report";
1739 break;
1740 case BDRV_ACTION_IGNORE:
1741 action_str = "ignore";
1742 break;
1743 case BDRV_ACTION_STOP:
1744 action_str = "stop";
1745 break;
1746 default:
1747 abort();
1748 }
1749
1750 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1751 bdrv->device_name,
1752 action_str,
1753 is_read ? "read" : "write");
1754 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1755
1756 qobject_decref(data);
1757}
1758
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001759static void bdrv_print_dict(QObject *obj, void *opaque)
bellardb3380822004-03-14 21:38:54 +00001760{
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001761 QDict *bs_dict;
1762 Monitor *mon = opaque;
1763
1764 bs_dict = qobject_to_qdict(obj);
1765
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001766 monitor_printf(mon, "%s: removable=%d",
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001767 qdict_get_str(bs_dict, "device"),
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001768 qdict_get_bool(bs_dict, "removable"));
1769
1770 if (qdict_get_bool(bs_dict, "removable")) {
1771 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1772 }
1773
1774 if (qdict_haskey(bs_dict, "inserted")) {
1775 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1776
1777 monitor_printf(mon, " file=");
1778 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1779 if (qdict_haskey(qdict, "backing_file")) {
1780 monitor_printf(mon, " backing_file=");
1781 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1782 }
1783 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1784 qdict_get_bool(qdict, "ro"),
1785 qdict_get_str(qdict, "drv"),
1786 qdict_get_bool(qdict, "encrypted"));
1787 } else {
1788 monitor_printf(mon, " [not inserted]");
1789 }
1790
1791 monitor_printf(mon, "\n");
1792}
1793
1794void bdrv_info_print(Monitor *mon, const QObject *data)
1795{
1796 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1797}
1798
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001799void bdrv_info(Monitor *mon, QObject **ret_data)
1800{
1801 QList *bs_list;
bellardb3380822004-03-14 21:38:54 +00001802 BlockDriverState *bs;
1803
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001804 bs_list = qlist_new();
1805
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001806 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001807 QObject *bs_obj;
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001808
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001809 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001810 "'removable': %i, 'locked': %i }",
Markus Armbrusterd8aeeb32011-05-16 15:04:55 +02001811 bs->device_name, bs->removable,
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001812 bs->locked);
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001813
bellard19cb3732006-08-19 11:45:59 +00001814 if (bs->drv) {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001815 QObject *obj;
1816 QDict *bs_dict = qobject_to_qdict(bs_obj);
1817
1818 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1819 "'encrypted': %i }",
1820 bs->filename, bs->read_only,
1821 bs->drv->format_name,
1822 bdrv_is_encrypted(bs));
thsfef30742006-12-22 14:11:32 +00001823 if (bs->backing_file[0] != '\0') {
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001824 QDict *qdict = qobject_to_qdict(obj);
1825 qdict_put(qdict, "backing_file",
1826 qstring_from_str(bs->backing_file));
aliguori376253e2009-03-05 23:01:23 +00001827 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001828
1829 qdict_put_obj(bs_dict, "inserted", obj);
bellardb3380822004-03-14 21:38:54 +00001830 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001831 qlist_append_obj(bs_list, bs_obj);
bellardb3380822004-03-14 21:38:54 +00001832 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02001833
1834 *ret_data = QOBJECT(bs_list);
bellardb3380822004-03-14 21:38:54 +00001835}
thsa36e69d2007-12-02 05:18:19 +00001836
Luiz Capitulino218a5362009-12-10 17:16:07 -02001837static void bdrv_stats_iter(QObject *data, void *opaque)
thsa36e69d2007-12-02 05:18:19 +00001838{
Luiz Capitulino218a5362009-12-10 17:16:07 -02001839 QDict *qdict;
1840 Monitor *mon = opaque;
1841
1842 qdict = qobject_to_qdict(data);
1843 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1844
1845 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1846 monitor_printf(mon, " rd_bytes=%" PRId64
1847 " wr_bytes=%" PRId64
1848 " rd_operations=%" PRId64
1849 " wr_operations=%" PRId64
1850 "\n",
1851 qdict_get_int(qdict, "rd_bytes"),
1852 qdict_get_int(qdict, "wr_bytes"),
1853 qdict_get_int(qdict, "rd_operations"),
1854 qdict_get_int(qdict, "wr_operations"));
1855}
1856
1857void bdrv_stats_print(Monitor *mon, const QObject *data)
1858{
1859 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1860}
1861
Kevin Wolf294cc352010-04-28 14:34:01 +02001862static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1863{
1864 QObject *res;
1865 QDict *dict;
1866
1867 res = qobject_from_jsonf("{ 'stats': {"
1868 "'rd_bytes': %" PRId64 ","
1869 "'wr_bytes': %" PRId64 ","
1870 "'rd_operations': %" PRId64 ","
1871 "'wr_operations': %" PRId64 ","
1872 "'wr_highest_offset': %" PRId64
1873 "} }",
1874 bs->rd_bytes, bs->wr_bytes,
1875 bs->rd_ops, bs->wr_ops,
Blue Swirl5ffbbc62010-06-14 18:55:33 +00001876 bs->wr_highest_sector *
1877 (uint64_t)BDRV_SECTOR_SIZE);
Kevin Wolf294cc352010-04-28 14:34:01 +02001878 dict = qobject_to_qdict(res);
1879
1880 if (*bs->device_name) {
1881 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1882 }
1883
1884 if (bs->file) {
1885 QObject *parent = bdrv_info_stats_bs(bs->file);
1886 qdict_put_obj(dict, "parent", parent);
1887 }
1888
1889 return res;
1890}
1891
Luiz Capitulino218a5362009-12-10 17:16:07 -02001892void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1893{
1894 QObject *obj;
1895 QList *devices;
thsa36e69d2007-12-02 05:18:19 +00001896 BlockDriverState *bs;
1897
Luiz Capitulino218a5362009-12-10 17:16:07 -02001898 devices = qlist_new();
1899
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001900 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Kevin Wolf294cc352010-04-28 14:34:01 +02001901 obj = bdrv_info_stats_bs(bs);
Luiz Capitulino218a5362009-12-10 17:16:07 -02001902 qlist_append_obj(devices, obj);
thsa36e69d2007-12-02 05:18:19 +00001903 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02001904
1905 *ret_data = QOBJECT(devices);
thsa36e69d2007-12-02 05:18:19 +00001906}
bellardea2384d2004-08-01 21:59:26 +00001907
aliguori045df332009-03-05 23:00:48 +00001908const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1909{
1910 if (bs->backing_hd && bs->backing_hd->encrypted)
1911 return bs->backing_file;
1912 else if (bs->encrypted)
1913 return bs->filename;
1914 else
1915 return NULL;
1916}
1917
ths5fafdf22007-09-16 21:08:06 +00001918void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00001919 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00001920{
Kevin Wolfb783e402010-01-12 12:55:16 +01001921 if (!bs->backing_file) {
bellard83f64092006-08-01 16:21:11 +00001922 pstrcpy(filename, filename_size, "");
1923 } else {
1924 pstrcpy(filename, filename_size, bs->backing_file);
1925 }
bellardea2384d2004-08-01 21:59:26 +00001926}
1927
ths5fafdf22007-09-16 21:08:06 +00001928int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00001929 const uint8_t *buf, int nb_sectors)
1930{
1931 BlockDriver *drv = bs->drv;
1932 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001933 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00001934 if (!drv->bdrv_write_compressed)
1935 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02001936 if (bdrv_check_request(bs, sector_num, nb_sectors))
1937 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001938
Jan Kiszkac6d22832009-11-30 18:21:20 +01001939 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02001940 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1941 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01001942
bellardfaea38e2006-08-05 21:31:00 +00001943 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1944}
ths3b46e622007-09-17 08:09:54 +00001945
bellardfaea38e2006-08-05 21:31:00 +00001946int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1947{
1948 BlockDriver *drv = bs->drv;
1949 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00001950 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00001951 if (!drv->bdrv_get_info)
1952 return -ENOTSUP;
1953 memset(bdi, 0, sizeof(*bdi));
1954 return drv->bdrv_get_info(bs, bdi);
1955}
1956
Christoph Hellwig45566e92009-07-10 23:11:57 +02001957int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1958 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00001959{
1960 BlockDriver *drv = bs->drv;
1961 if (!drv)
1962 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09001963 if (drv->bdrv_save_vmstate)
1964 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1965 if (bs->file)
1966 return bdrv_save_vmstate(bs->file, buf, pos, size);
1967 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00001968}
1969
Christoph Hellwig45566e92009-07-10 23:11:57 +02001970int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1971 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00001972{
1973 BlockDriver *drv = bs->drv;
1974 if (!drv)
1975 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09001976 if (drv->bdrv_load_vmstate)
1977 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1978 if (bs->file)
1979 return bdrv_load_vmstate(bs->file, buf, pos, size);
1980 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00001981}
1982
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01001983void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1984{
1985 BlockDriver *drv = bs->drv;
1986
1987 if (!drv || !drv->bdrv_debug_event) {
1988 return;
1989 }
1990
1991 return drv->bdrv_debug_event(bs, event);
1992
1993}
1994
bellardfaea38e2006-08-05 21:31:00 +00001995/**************************************************************/
1996/* handling of snapshots */
1997
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03001998int bdrv_can_snapshot(BlockDriverState *bs)
1999{
2000 BlockDriver *drv = bs->drv;
2001 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
2002 return 0;
2003 }
2004
2005 if (!drv->bdrv_snapshot_create) {
2006 if (bs->file != NULL) {
2007 return bdrv_can_snapshot(bs->file);
2008 }
2009 return 0;
2010 }
2011
2012 return 1;
2013}
2014
Blue Swirl199630b2010-07-25 20:49:34 +00002015int bdrv_is_snapshot(BlockDriverState *bs)
2016{
2017 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2018}
2019
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002020BlockDriverState *bdrv_snapshots(void)
2021{
2022 BlockDriverState *bs;
2023
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002024 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002025 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002026 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002027
2028 bs = NULL;
2029 while ((bs = bdrv_next(bs))) {
2030 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02002031 bs_snapshots = bs;
2032 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002033 }
2034 }
2035 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02002036}
2037
ths5fafdf22007-09-16 21:08:06 +00002038int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002039 QEMUSnapshotInfo *sn_info)
2040{
2041 BlockDriver *drv = bs->drv;
2042 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002043 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002044 if (drv->bdrv_snapshot_create)
2045 return drv->bdrv_snapshot_create(bs, sn_info);
2046 if (bs->file)
2047 return bdrv_snapshot_create(bs->file, sn_info);
2048 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002049}
2050
ths5fafdf22007-09-16 21:08:06 +00002051int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002052 const char *snapshot_id)
2053{
2054 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002055 int ret, open_ret;
2056
bellardfaea38e2006-08-05 21:31:00 +00002057 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002058 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002059 if (drv->bdrv_snapshot_goto)
2060 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2061
2062 if (bs->file) {
2063 drv->bdrv_close(bs);
2064 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2065 open_ret = drv->bdrv_open(bs, bs->open_flags);
2066 if (open_ret < 0) {
2067 bdrv_delete(bs->file);
2068 bs->drv = NULL;
2069 return open_ret;
2070 }
2071 return ret;
2072 }
2073
2074 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002075}
2076
2077int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2078{
2079 BlockDriver *drv = bs->drv;
2080 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002081 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002082 if (drv->bdrv_snapshot_delete)
2083 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2084 if (bs->file)
2085 return bdrv_snapshot_delete(bs->file, snapshot_id);
2086 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002087}
2088
ths5fafdf22007-09-16 21:08:06 +00002089int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00002090 QEMUSnapshotInfo **psn_info)
2091{
2092 BlockDriver *drv = bs->drv;
2093 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002094 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09002095 if (drv->bdrv_snapshot_list)
2096 return drv->bdrv_snapshot_list(bs, psn_info);
2097 if (bs->file)
2098 return bdrv_snapshot_list(bs->file, psn_info);
2099 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00002100}
2101
edison51ef6722010-09-21 19:58:41 -07002102int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2103 const char *snapshot_name)
2104{
2105 BlockDriver *drv = bs->drv;
2106 if (!drv) {
2107 return -ENOMEDIUM;
2108 }
2109 if (!bs->read_only) {
2110 return -EINVAL;
2111 }
2112 if (drv->bdrv_snapshot_load_tmp) {
2113 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2114 }
2115 return -ENOTSUP;
2116}
2117
bellardfaea38e2006-08-05 21:31:00 +00002118#define NB_SUFFIXES 4
2119
2120char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2121{
2122 static const char suffixes[NB_SUFFIXES] = "KMGT";
2123 int64_t base;
2124 int i;
2125
2126 if (size <= 999) {
2127 snprintf(buf, buf_size, "%" PRId64, size);
2128 } else {
2129 base = 1024;
2130 for(i = 0; i < NB_SUFFIXES; i++) {
2131 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00002132 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00002133 (double)size / base,
2134 suffixes[i]);
2135 break;
2136 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00002137 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00002138 ((size + (base >> 1)) / base),
2139 suffixes[i]);
2140 break;
2141 }
2142 base = base * 1024;
2143 }
2144 }
2145 return buf;
2146}
2147
2148char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2149{
2150 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00002151#ifdef _WIN32
2152 struct tm *ptm;
2153#else
bellardfaea38e2006-08-05 21:31:00 +00002154 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00002155#endif
bellardfaea38e2006-08-05 21:31:00 +00002156 time_t ti;
2157 int64_t secs;
2158
2159 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00002160 snprintf(buf, buf_size,
2161 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002162 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2163 } else {
2164 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00002165#ifdef _WIN32
2166 ptm = localtime(&ti);
2167 strftime(date_buf, sizeof(date_buf),
2168 "%Y-%m-%d %H:%M:%S", ptm);
2169#else
bellardfaea38e2006-08-05 21:31:00 +00002170 localtime_r(&ti, &tm);
2171 strftime(date_buf, sizeof(date_buf),
2172 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00002173#endif
bellardfaea38e2006-08-05 21:31:00 +00002174 secs = sn->vm_clock_nsec / 1000000000;
2175 snprintf(clock_buf, sizeof(clock_buf),
2176 "%02d:%02d:%02d.%03d",
2177 (int)(secs / 3600),
2178 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00002179 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00002180 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2181 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00002182 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00002183 sn->id_str, sn->name,
2184 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2185 date_buf,
2186 clock_buf);
2187 }
2188 return buf;
2189}
2190
bellardea2384d2004-08-01 21:59:26 +00002191
bellard83f64092006-08-01 16:21:11 +00002192/**************************************************************/
2193/* async I/Os */
2194
aliguori3b69e4b2009-01-22 16:59:24 +00002195BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00002196 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00002197 BlockDriverCompletionFunc *cb, void *opaque)
2198{
bellard83f64092006-08-01 16:21:11 +00002199 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002200 BlockDriverAIOCB *ret;
bellard83f64092006-08-01 16:21:11 +00002201
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002202 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2203
bellard19cb3732006-08-19 11:45:59 +00002204 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002205 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002206 if (bdrv_check_request(bs, sector_num, nb_sectors))
2207 return NULL;
ths3b46e622007-09-17 08:09:54 +00002208
aliguorif141eaf2009-04-07 18:43:24 +00002209 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2210 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002211
2212 if (ret) {
2213 /* Update stats even though technically transfer has not happened. */
Jan Kiszka6ea44302009-11-30 18:21:19 +01002214 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
thsa36e69d2007-12-02 05:18:19 +00002215 bs->rd_ops ++;
2216 }
2217
2218 return ret;
bellard83f64092006-08-01 16:21:11 +00002219}
2220
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002221typedef struct BlockCompleteData {
2222 BlockDriverCompletionFunc *cb;
2223 void *opaque;
2224 BlockDriverState *bs;
2225 int64_t sector_num;
2226 int nb_sectors;
2227} BlockCompleteData;
2228
2229static void block_complete_cb(void *opaque, int ret)
2230{
2231 BlockCompleteData *b = opaque;
2232
2233 if (b->bs->dirty_bitmap) {
2234 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2235 }
2236 b->cb(b->opaque, ret);
2237 qemu_free(b);
2238}
2239
2240static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2241 int64_t sector_num,
2242 int nb_sectors,
2243 BlockDriverCompletionFunc *cb,
2244 void *opaque)
2245{
2246 BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
2247
2248 blkdata->bs = bs;
2249 blkdata->cb = cb;
2250 blkdata->opaque = opaque;
2251 blkdata->sector_num = sector_num;
2252 blkdata->nb_sectors = nb_sectors;
2253
2254 return blkdata;
2255}
2256
aliguorif141eaf2009-04-07 18:43:24 +00002257BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2258 QEMUIOVector *qiov, int nb_sectors,
2259 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002260{
bellard83f64092006-08-01 16:21:11 +00002261 BlockDriver *drv = bs->drv;
thsa36e69d2007-12-02 05:18:19 +00002262 BlockDriverAIOCB *ret;
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002263 BlockCompleteData *blk_cb_data;
bellard83f64092006-08-01 16:21:11 +00002264
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01002265 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2266
bellard19cb3732006-08-19 11:45:59 +00002267 if (!drv)
pbrookce1a14d2006-08-07 02:38:06 +00002268 return NULL;
bellard83f64092006-08-01 16:21:11 +00002269 if (bs->read_only)
pbrookce1a14d2006-08-07 02:38:06 +00002270 return NULL;
aliguori71d07702009-03-03 17:37:16 +00002271 if (bdrv_check_request(bs, sector_num, nb_sectors))
2272 return NULL;
bellard83f64092006-08-01 16:21:11 +00002273
Jan Kiszkac6d22832009-11-30 18:21:20 +01002274 if (bs->dirty_bitmap) {
Marcelo Tosatti4dcafbb2010-11-08 17:02:55 -02002275 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2276 opaque);
2277 cb = &block_complete_cb;
2278 opaque = blk_cb_data;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002279 }
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002280
aliguorif141eaf2009-04-07 18:43:24 +00002281 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2282 cb, opaque);
thsa36e69d2007-12-02 05:18:19 +00002283
2284 if (ret) {
Kevin Wolf294cc352010-04-28 14:34:01 +02002285 /* Update stats even though technically transfer has not happened. */
2286 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2287 bs->wr_ops ++;
2288 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2289 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2290 }
thsa36e69d2007-12-02 05:18:19 +00002291 }
2292
2293 return ret;
bellard83f64092006-08-01 16:21:11 +00002294}
2295
Kevin Wolf40b4f532009-09-09 17:53:37 +02002296
2297typedef struct MultiwriteCB {
2298 int error;
2299 int num_requests;
2300 int num_callbacks;
2301 struct {
2302 BlockDriverCompletionFunc *cb;
2303 void *opaque;
2304 QEMUIOVector *free_qiov;
2305 void *free_buf;
2306 } callbacks[];
2307} MultiwriteCB;
2308
2309static void multiwrite_user_cb(MultiwriteCB *mcb)
2310{
2311 int i;
2312
2313 for (i = 0; i < mcb->num_callbacks; i++) {
2314 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01002315 if (mcb->callbacks[i].free_qiov) {
2316 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2317 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002318 qemu_free(mcb->callbacks[i].free_qiov);
Herve Poussineauf8a83242010-01-24 21:23:56 +00002319 qemu_vfree(mcb->callbacks[i].free_buf);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002320 }
2321}
2322
2323static void multiwrite_cb(void *opaque, int ret)
2324{
2325 MultiwriteCB *mcb = opaque;
2326
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002327 trace_multiwrite_cb(mcb, ret);
2328
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02002329 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02002330 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002331 }
2332
2333 mcb->num_requests--;
2334 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02002335 multiwrite_user_cb(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002336 qemu_free(mcb);
2337 }
2338}
2339
2340static int multiwrite_req_compare(const void *a, const void *b)
2341{
Christoph Hellwig77be4362010-05-19 20:53:10 +02002342 const BlockRequest *req1 = a, *req2 = b;
2343
2344 /*
2345 * Note that we can't simply subtract req2->sector from req1->sector
2346 * here as that could overflow the return value.
2347 */
2348 if (req1->sector > req2->sector) {
2349 return 1;
2350 } else if (req1->sector < req2->sector) {
2351 return -1;
2352 } else {
2353 return 0;
2354 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002355}
2356
2357/*
2358 * Takes a bunch of requests and tries to merge them. Returns the number of
2359 * requests that remain after merging.
2360 */
2361static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2362 int num_reqs, MultiwriteCB *mcb)
2363{
2364 int i, outidx;
2365
2366 // Sort requests by start sector
2367 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2368
2369 // Check if adjacent requests touch the same clusters. If so, combine them,
2370 // filling up gaps with zero sectors.
2371 outidx = 0;
2372 for (i = 1; i < num_reqs; i++) {
2373 int merge = 0;
2374 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2375
2376 // This handles the cases that are valid for all block drivers, namely
2377 // exactly sequential writes and overlapping writes.
2378 if (reqs[i].sector <= oldreq_last) {
2379 merge = 1;
2380 }
2381
2382 // The block driver may decide that it makes sense to combine requests
2383 // even if there is a gap of some sectors between them. In this case,
2384 // the gap is filled with zeros (therefore only applicable for yet
2385 // unused space in format like qcow2).
2386 if (!merge && bs->drv->bdrv_merge_requests) {
2387 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2388 }
2389
Christoph Hellwige2a305f2010-01-26 14:49:08 +01002390 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2391 merge = 0;
2392 }
2393
Kevin Wolf40b4f532009-09-09 17:53:37 +02002394 if (merge) {
2395 size_t size;
2396 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2397 qemu_iovec_init(qiov,
2398 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2399
2400 // Add the first request to the merged one. If the requests are
2401 // overlapping, drop the last sectors of the first request.
2402 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2403 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2404
2405 // We might need to add some zeros between the two requests
2406 if (reqs[i].sector > oldreq_last) {
2407 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2408 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2409 memset(buf, 0, zero_bytes);
2410 qemu_iovec_add(qiov, buf, zero_bytes);
2411 mcb->callbacks[i].free_buf = buf;
2412 }
2413
2414 // Add the second request
2415 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2416
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02002417 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002418 reqs[outidx].qiov = qiov;
2419
2420 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2421 } else {
2422 outidx++;
2423 reqs[outidx].sector = reqs[i].sector;
2424 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2425 reqs[outidx].qiov = reqs[i].qiov;
2426 }
2427 }
2428
2429 return outidx + 1;
2430}
2431
2432/*
2433 * Submit multiple AIO write requests at once.
2434 *
2435 * On success, the function returns 0 and all requests in the reqs array have
2436 * been submitted. In error case this function returns -1, and any of the
2437 * requests may or may not be submitted yet. In particular, this means that the
2438 * callback will be called for some of the requests, for others it won't. The
2439 * caller must check the error field of the BlockRequest to wait for the right
2440 * callbacks (if error != 0, no callback will be called).
2441 *
2442 * The implementation may modify the contents of the reqs array, e.g. to merge
2443 * requests. However, the fields opaque and error are left unmodified as they
2444 * are used to signal failure for a single request to the caller.
2445 */
2446int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2447{
2448 BlockDriverAIOCB *acb;
2449 MultiwriteCB *mcb;
2450 int i;
2451
Ryan Harper301db7c2011-03-07 10:01:04 -06002452 /* don't submit writes if we don't have a medium */
2453 if (bs->drv == NULL) {
2454 for (i = 0; i < num_reqs; i++) {
2455 reqs[i].error = -ENOMEDIUM;
2456 }
2457 return -1;
2458 }
2459
Kevin Wolf40b4f532009-09-09 17:53:37 +02002460 if (num_reqs == 0) {
2461 return 0;
2462 }
2463
2464 // Create MultiwriteCB structure
2465 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2466 mcb->num_requests = 0;
2467 mcb->num_callbacks = num_reqs;
2468
2469 for (i = 0; i < num_reqs; i++) {
2470 mcb->callbacks[i].cb = reqs[i].cb;
2471 mcb->callbacks[i].opaque = reqs[i].opaque;
2472 }
2473
2474 // Check for mergable requests
2475 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2476
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002477 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2478
Kevin Wolf453f9a12010-07-02 14:01:21 +02002479 /*
2480 * Run the aio requests. As soon as one request can't be submitted
2481 * successfully, fail all requests that are not yet submitted (we must
2482 * return failure for all requests anyway)
2483 *
2484 * num_requests cannot be set to the right value immediately: If
2485 * bdrv_aio_writev fails for some request, num_requests would be too high
2486 * and therefore multiwrite_cb() would never recognize the multiwrite
2487 * request as completed. We also cannot use the loop variable i to set it
2488 * when the first request fails because the callback may already have been
2489 * called for previously submitted requests. Thus, num_requests must be
2490 * incremented for each request that is submitted.
2491 *
2492 * The problem that callbacks may be called early also means that we need
2493 * to take care that num_requests doesn't become 0 before all requests are
2494 * submitted - multiwrite_cb() would consider the multiwrite request
2495 * completed. A dummy request that is "completed" by a manual call to
2496 * multiwrite_cb() takes care of this.
2497 */
2498 mcb->num_requests = 1;
2499
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002500 // Run the aio requests
Kevin Wolf40b4f532009-09-09 17:53:37 +02002501 for (i = 0; i < num_reqs; i++) {
Kevin Wolf453f9a12010-07-02 14:01:21 +02002502 mcb->num_requests++;
Kevin Wolf40b4f532009-09-09 17:53:37 +02002503 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2504 reqs[i].nb_sectors, multiwrite_cb, mcb);
2505
2506 if (acb == NULL) {
2507 // We can only fail the whole thing if no request has been
2508 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2509 // complete and report the error in the callback.
Kevin Wolf453f9a12010-07-02 14:01:21 +02002510 if (i == 0) {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002511 trace_bdrv_aio_multiwrite_earlyfail(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002512 goto fail;
2513 } else {
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01002514 trace_bdrv_aio_multiwrite_latefail(mcb, i);
Kevin Wolf7eb58a62010-04-06 18:24:07 +02002515 multiwrite_cb(mcb, -EIO);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002516 break;
2517 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02002518 }
2519 }
2520
Kevin Wolf453f9a12010-07-02 14:01:21 +02002521 /* Complete the dummy request */
2522 multiwrite_cb(mcb, 0);
2523
Kevin Wolf40b4f532009-09-09 17:53:37 +02002524 return 0;
2525
2526fail:
Kevin Wolf453f9a12010-07-02 14:01:21 +02002527 for (i = 0; i < mcb->num_callbacks; i++) {
2528 reqs[i].error = -EIO;
2529 }
Bruce Rogersaf474592010-05-13 15:14:33 -06002530 qemu_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02002531 return -1;
2532}
2533
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002534BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2535 BlockDriverCompletionFunc *cb, void *opaque)
2536{
2537 BlockDriver *drv = bs->drv;
2538
Stefan Hajnoczia13aac02011-03-07 07:58:04 +00002539 trace_bdrv_aio_flush(bs, opaque);
2540
Alexander Graf016f5cf2010-05-26 17:51:49 +02002541 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2542 return bdrv_aio_noop_em(bs, cb, opaque);
2543 }
2544
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002545 if (!drv)
2546 return NULL;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002547 return drv->bdrv_aio_flush(bs, cb, opaque);
2548}
2549
bellard83f64092006-08-01 16:21:11 +00002550void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00002551{
aliguori6bbff9a2009-03-20 18:25:59 +00002552 acb->pool->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00002553}
2554
pbrookce1a14d2006-08-07 02:38:06 +00002555
bellard83f64092006-08-01 16:21:11 +00002556/**************************************************************/
2557/* async block device emulation */
2558
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002559typedef struct BlockDriverAIOCBSync {
2560 BlockDriverAIOCB common;
2561 QEMUBH *bh;
2562 int ret;
2563 /* vector translation state */
2564 QEMUIOVector *qiov;
2565 uint8_t *bounce;
2566 int is_write;
2567} BlockDriverAIOCBSync;
2568
2569static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2570{
Kevin Wolfb666d232010-05-05 11:44:39 +02002571 BlockDriverAIOCBSync *acb =
2572 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03002573 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002574 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002575 qemu_aio_release(acb);
2576}
2577
2578static AIOPool bdrv_em_aio_pool = {
2579 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2580 .cancel = bdrv_aio_cancel_em,
2581};
2582
bellard83f64092006-08-01 16:21:11 +00002583static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00002584{
pbrookce1a14d2006-08-07 02:38:06 +00002585 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00002586
aliguorif141eaf2009-04-07 18:43:24 +00002587 if (!acb->is_write)
2588 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00002589 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00002590 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03002591 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03002592 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00002593 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00002594}
bellardbeac80c2006-06-26 20:08:57 +00002595
aliguorif141eaf2009-04-07 18:43:24 +00002596static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2597 int64_t sector_num,
2598 QEMUIOVector *qiov,
2599 int nb_sectors,
2600 BlockDriverCompletionFunc *cb,
2601 void *opaque,
2602 int is_write)
2603
bellardea2384d2004-08-01 21:59:26 +00002604{
pbrookce1a14d2006-08-07 02:38:06 +00002605 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00002606
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002607 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00002608 acb->is_write = is_write;
2609 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00002610 acb->bounce = qemu_blockalign(bs, qiov->size);
aliguorif141eaf2009-04-07 18:43:24 +00002611
pbrookce1a14d2006-08-07 02:38:06 +00002612 if (!acb->bh)
2613 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00002614
2615 if (is_write) {
2616 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2617 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2618 } else {
2619 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2620 }
2621
pbrookce1a14d2006-08-07 02:38:06 +00002622 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00002623
pbrookce1a14d2006-08-07 02:38:06 +00002624 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00002625}
2626
aliguorif141eaf2009-04-07 18:43:24 +00002627static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2628 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00002629 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00002630{
aliguorif141eaf2009-04-07 18:43:24 +00002631 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00002632}
2633
aliguorif141eaf2009-04-07 18:43:24 +00002634static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2635 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2636 BlockDriverCompletionFunc *cb, void *opaque)
2637{
2638 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2639}
2640
Kevin Wolf68485422011-06-30 10:05:46 +02002641
2642typedef struct BlockDriverAIOCBCoroutine {
2643 BlockDriverAIOCB common;
2644 BlockRequest req;
2645 bool is_write;
2646 QEMUBH* bh;
2647} BlockDriverAIOCBCoroutine;
2648
2649static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2650{
2651 qemu_aio_flush();
2652}
2653
2654static AIOPool bdrv_em_co_aio_pool = {
2655 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2656 .cancel = bdrv_aio_co_cancel_em,
2657};
2658
2659static void bdrv_co_rw_bh(void *opaque)
2660{
2661 BlockDriverAIOCBCoroutine *acb = opaque;
2662
2663 acb->common.cb(acb->common.opaque, acb->req.error);
2664 qemu_bh_delete(acb->bh);
2665 qemu_aio_release(acb);
2666}
2667
2668static void coroutine_fn bdrv_co_rw(void *opaque)
2669{
2670 BlockDriverAIOCBCoroutine *acb = opaque;
2671 BlockDriverState *bs = acb->common.bs;
2672
2673 if (!acb->is_write) {
2674 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2675 acb->req.nb_sectors, acb->req.qiov);
2676 } else {
2677 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2678 acb->req.nb_sectors, acb->req.qiov);
2679 }
2680
2681 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2682 qemu_bh_schedule(acb->bh);
2683}
2684
2685static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2686 int64_t sector_num,
2687 QEMUIOVector *qiov,
2688 int nb_sectors,
2689 BlockDriverCompletionFunc *cb,
2690 void *opaque,
2691 bool is_write)
2692{
2693 Coroutine *co;
2694 BlockDriverAIOCBCoroutine *acb;
2695
2696 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2697 acb->req.sector = sector_num;
2698 acb->req.nb_sectors = nb_sectors;
2699 acb->req.qiov = qiov;
2700 acb->is_write = is_write;
2701
2702 co = qemu_coroutine_create(bdrv_co_rw);
2703 qemu_coroutine_enter(co, acb);
2704
2705 return &acb->common;
2706}
2707
2708static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2709 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2710 BlockDriverCompletionFunc *cb, void *opaque)
2711{
2712 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2713 false);
2714}
2715
2716static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2717 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2718 BlockDriverCompletionFunc *cb, void *opaque)
2719{
2720 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2721 true);
2722}
2723
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02002724static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2725 BlockDriverCompletionFunc *cb, void *opaque)
2726{
2727 BlockDriverAIOCBSync *acb;
2728
2729 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2730 acb->is_write = 1; /* don't bounce in the completion hadler */
2731 acb->qiov = NULL;
2732 acb->bounce = NULL;
2733 acb->ret = 0;
2734
2735 if (!acb->bh)
2736 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2737
2738 bdrv_flush(bs);
2739 qemu_bh_schedule(acb->bh);
2740 return &acb->common;
2741}
2742
Alexander Graf016f5cf2010-05-26 17:51:49 +02002743static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2744 BlockDriverCompletionFunc *cb, void *opaque)
2745{
2746 BlockDriverAIOCBSync *acb;
2747
2748 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2749 acb->is_write = 1; /* don't bounce in the completion handler */
2750 acb->qiov = NULL;
2751 acb->bounce = NULL;
2752 acb->ret = 0;
2753
2754 if (!acb->bh) {
2755 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2756 }
2757
2758 qemu_bh_schedule(acb->bh);
2759 return &acb->common;
2760}
2761
bellard83f64092006-08-01 16:21:11 +00002762/**************************************************************/
2763/* sync block device emulation */
2764
2765static void bdrv_rw_em_cb(void *opaque, int ret)
2766{
2767 *(int *)opaque = ret;
2768}
2769
2770#define NOT_DONE 0x7fffffff
2771
ths5fafdf22007-09-16 21:08:06 +00002772static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
bellard83f64092006-08-01 16:21:11 +00002773 uint8_t *buf, int nb_sectors)
2774{
pbrookce1a14d2006-08-07 02:38:06 +00002775 int async_ret;
2776 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002777 struct iovec iov;
2778 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002779
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002780 async_context_push();
2781
bellard83f64092006-08-01 16:21:11 +00002782 async_ret = NOT_DONE;
blueswir13f4cb3d2009-04-13 16:31:01 +00002783 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002784 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002785 qemu_iovec_init_external(&qiov, &iov, 1);
2786 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2787 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002788 if (acb == NULL) {
2789 async_ret = -1;
2790 goto fail;
2791 }
aliguoribaf35cb2008-09-10 15:45:19 +00002792
bellard83f64092006-08-01 16:21:11 +00002793 while (async_ret == NOT_DONE) {
2794 qemu_aio_wait();
2795 }
aliguoribaf35cb2008-09-10 15:45:19 +00002796
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002797
2798fail:
2799 async_context_pop();
bellard83f64092006-08-01 16:21:11 +00002800 return async_ret;
2801}
2802
2803static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2804 const uint8_t *buf, int nb_sectors)
2805{
pbrookce1a14d2006-08-07 02:38:06 +00002806 int async_ret;
2807 BlockDriverAIOCB *acb;
aliguorif141eaf2009-04-07 18:43:24 +00002808 struct iovec iov;
2809 QEMUIOVector qiov;
bellard83f64092006-08-01 16:21:11 +00002810
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002811 async_context_push();
2812
bellard83f64092006-08-01 16:21:11 +00002813 async_ret = NOT_DONE;
aliguorif141eaf2009-04-07 18:43:24 +00002814 iov.iov_base = (void *)buf;
Jes Sorenseneb5a3162010-05-27 16:20:31 +02002815 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
aliguorif141eaf2009-04-07 18:43:24 +00002816 qemu_iovec_init_external(&qiov, &iov, 1);
2817 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2818 bdrv_rw_em_cb, &async_ret);
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002819 if (acb == NULL) {
2820 async_ret = -1;
2821 goto fail;
2822 }
bellard83f64092006-08-01 16:21:11 +00002823 while (async_ret == NOT_DONE) {
2824 qemu_aio_wait();
2825 }
Kevin Wolf65d6b3d2009-10-22 17:54:39 +02002826
2827fail:
2828 async_context_pop();
bellard83f64092006-08-01 16:21:11 +00002829 return async_ret;
2830}
bellardea2384d2004-08-01 21:59:26 +00002831
2832void bdrv_init(void)
2833{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05002834 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00002835}
pbrookce1a14d2006-08-07 02:38:06 +00002836
Markus Armbrustereb852012009-10-27 18:41:44 +01002837void bdrv_init_with_whitelist(void)
2838{
2839 use_bdrv_whitelist = 1;
2840 bdrv_init();
2841}
2842
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02002843void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2844 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00002845{
pbrookce1a14d2006-08-07 02:38:06 +00002846 BlockDriverAIOCB *acb;
2847
aliguori6bbff9a2009-03-20 18:25:59 +00002848 if (pool->free_aiocb) {
2849 acb = pool->free_aiocb;
2850 pool->free_aiocb = acb->next;
pbrookce1a14d2006-08-07 02:38:06 +00002851 } else {
aliguori6bbff9a2009-03-20 18:25:59 +00002852 acb = qemu_mallocz(pool->aiocb_size);
2853 acb->pool = pool;
pbrookce1a14d2006-08-07 02:38:06 +00002854 }
2855 acb->bs = bs;
2856 acb->cb = cb;
2857 acb->opaque = opaque;
2858 return acb;
2859}
2860
2861void qemu_aio_release(void *p)
2862{
aliguori6bbff9a2009-03-20 18:25:59 +00002863 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2864 AIOPool *pool = acb->pool;
2865 acb->next = pool->free_aiocb;
2866 pool->free_aiocb = acb;
pbrookce1a14d2006-08-07 02:38:06 +00002867}
bellard19cb3732006-08-19 11:45:59 +00002868
2869/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02002870/* Coroutine block device emulation */
2871
2872typedef struct CoroutineIOCompletion {
2873 Coroutine *coroutine;
2874 int ret;
2875} CoroutineIOCompletion;
2876
2877static void bdrv_co_io_em_complete(void *opaque, int ret)
2878{
2879 CoroutineIOCompletion *co = opaque;
2880
2881 co->ret = ret;
2882 qemu_coroutine_enter(co->coroutine, NULL);
2883}
2884
2885static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2886 int nb_sectors, QEMUIOVector *iov,
2887 bool is_write)
2888{
2889 CoroutineIOCompletion co = {
2890 .coroutine = qemu_coroutine_self(),
2891 };
2892 BlockDriverAIOCB *acb;
2893
2894 if (is_write) {
2895 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2896 bdrv_co_io_em_complete, &co);
2897 } else {
2898 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2899 bdrv_co_io_em_complete, &co);
2900 }
2901
2902 trace_bdrv_co_io(is_write, acb);
2903 if (!acb) {
2904 return -EIO;
2905 }
2906 qemu_coroutine_yield();
2907
2908 return co.ret;
2909}
2910
2911static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2912 int64_t sector_num, int nb_sectors,
2913 QEMUIOVector *iov)
2914{
2915 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2916}
2917
2918static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2919 int64_t sector_num, int nb_sectors,
2920 QEMUIOVector *iov)
2921{
2922 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
2923}
2924
2925/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00002926/* removable device support */
2927
2928/**
2929 * Return TRUE if the media is present
2930 */
2931int bdrv_is_inserted(BlockDriverState *bs)
2932{
2933 BlockDriver *drv = bs->drv;
2934 int ret;
2935 if (!drv)
2936 return 0;
2937 if (!drv->bdrv_is_inserted)
Markus Armbruster4be97622010-07-27 14:02:01 +02002938 return !bs->tray_open;
bellard19cb3732006-08-19 11:45:59 +00002939 ret = drv->bdrv_is_inserted(bs);
2940 return ret;
2941}
2942
2943/**
2944 * Return TRUE if the media changed since the last call to this
ths5fafdf22007-09-16 21:08:06 +00002945 * function. It is currently only used for floppy disks
bellard19cb3732006-08-19 11:45:59 +00002946 */
2947int bdrv_media_changed(BlockDriverState *bs)
2948{
2949 BlockDriver *drv = bs->drv;
2950 int ret;
2951
2952 if (!drv || !drv->bdrv_media_changed)
2953 ret = -ENOTSUP;
2954 else
2955 ret = drv->bdrv_media_changed(bs);
2956 if (ret == -ENOTSUP)
2957 ret = bs->media_changed;
2958 bs->media_changed = 0;
2959 return ret;
2960}
2961
2962/**
2963 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2964 */
Mark McLoughlinaea2a332009-05-27 10:06:11 +01002965int bdrv_eject(BlockDriverState *bs, int eject_flag)
bellard19cb3732006-08-19 11:45:59 +00002966{
2967 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00002968
Markus Armbruster49aa46b2011-07-20 18:23:43 +02002969 if (eject_flag && bs->locked) {
Mark McLoughlinaea2a332009-05-27 10:06:11 +01002970 return -EBUSY;
2971 }
2972
Markus Armbruster822e1cd2011-07-20 18:23:42 +02002973 if (drv && drv->bdrv_eject) {
2974 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00002975 }
Markus Armbruster822e1cd2011-07-20 18:23:42 +02002976 bs->tray_open = eject_flag;
2977 return 0;
bellard19cb3732006-08-19 11:45:59 +00002978}
2979
2980int bdrv_is_locked(BlockDriverState *bs)
2981{
2982 return bs->locked;
2983}
2984
2985/**
2986 * Lock or unlock the media (if it is locked, the user won't be able
2987 * to eject it manually).
2988 */
2989void bdrv_set_locked(BlockDriverState *bs, int locked)
2990{
2991 BlockDriver *drv = bs->drv;
2992
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01002993 trace_bdrv_set_locked(bs, locked);
2994
bellard19cb3732006-08-19 11:45:59 +00002995 bs->locked = locked;
2996 if (drv && drv->bdrv_set_locked) {
2997 drv->bdrv_set_locked(bs, locked);
2998 }
2999}
ths985a03b2007-12-24 16:10:43 +00003000
3001/* needed for generic scsi interface */
3002
3003int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3004{
3005 BlockDriver *drv = bs->drv;
3006
3007 if (drv && drv->bdrv_ioctl)
3008 return drv->bdrv_ioctl(bs, req, buf);
3009 return -ENOTSUP;
3010}
aliguori7d780662009-03-12 19:57:08 +00003011
aliguori221f7152009-03-28 17:28:41 +00003012BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3013 unsigned long int req, void *buf,
3014 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00003015{
aliguori221f7152009-03-28 17:28:41 +00003016 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00003017
aliguori221f7152009-03-28 17:28:41 +00003018 if (drv && drv->bdrv_aio_ioctl)
3019 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3020 return NULL;
aliguori7d780662009-03-12 19:57:08 +00003021}
aliguorie268ca52009-04-22 20:20:00 +00003022
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003023
3024
aliguorie268ca52009-04-22 20:20:00 +00003025void *qemu_blockalign(BlockDriverState *bs, size_t size)
3026{
3027 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3028}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003029
3030void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3031{
3032 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003033
Liran Schouraaa0eb72010-01-26 10:31:48 +02003034 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003035 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003036 if (!bs->dirty_bitmap) {
3037 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3038 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3039 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003040
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003041 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003042 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003043 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01003044 if (bs->dirty_bitmap) {
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003045 qemu_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01003046 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003047 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003048 }
3049}
3050
3051int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3052{
Jan Kiszka6ea44302009-11-30 18:21:19 +01003053 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003054
Jan Kiszkac6d22832009-11-30 18:21:20 +01003055 if (bs->dirty_bitmap &&
3056 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02003057 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3058 (1UL << (chunk % (sizeof(unsigned long) * 8))));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003059 } else {
3060 return 0;
3061 }
3062}
3063
Jan Kiszkaa55eb922009-11-30 18:21:19 +01003064void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3065 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02003066{
3067 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3068}
Liran Schouraaa0eb72010-01-26 10:31:48 +02003069
3070int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3071{
3072 return bs->dirty_count;
3073}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003074
Marcelo Tosattidb593f22011-01-26 12:12:34 -02003075void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3076{
3077 assert(bs->in_use != in_use);
3078 bs->in_use = in_use;
3079}
3080
3081int bdrv_in_use(BlockDriverState *bs)
3082{
3083 return bs->in_use;
3084}
3085
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003086int bdrv_img_create(const char *filename, const char *fmt,
3087 const char *base_filename, const char *base_fmt,
3088 char *options, uint64_t img_size, int flags)
3089{
3090 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02003091 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003092 BlockDriverState *bs = NULL;
3093 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003094 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003095 int ret = 0;
3096
3097 /* Find driver and parse its options */
3098 drv = bdrv_find_format(fmt);
3099 if (!drv) {
3100 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003101 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003102 goto out;
3103 }
3104
3105 proto_drv = bdrv_find_protocol(filename);
3106 if (!proto_drv) {
3107 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003108 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003109 goto out;
3110 }
3111
3112 create_options = append_option_parameters(create_options,
3113 drv->create_options);
3114 create_options = append_option_parameters(create_options,
3115 proto_drv->create_options);
3116
3117 /* Create parameter list with default values */
3118 param = parse_option_parameters("", create_options, param);
3119
3120 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3121
3122 /* Parse -o options */
3123 if (options) {
3124 param = parse_option_parameters(options, create_options, param);
3125 if (param == NULL) {
3126 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003127 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003128 goto out;
3129 }
3130 }
3131
3132 if (base_filename) {
3133 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3134 base_filename)) {
3135 error_report("Backing file not supported for file format '%s'",
3136 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003137 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003138 goto out;
3139 }
3140 }
3141
3142 if (base_fmt) {
3143 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3144 error_report("Backing file format not supported for file "
3145 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003146 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003147 goto out;
3148 }
3149 }
3150
Jes Sorensen792da932010-12-16 13:52:17 +01003151 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3152 if (backing_file && backing_file->value.s) {
3153 if (!strcmp(filename, backing_file->value.s)) {
3154 error_report("Error: Trying to create an image with the "
3155 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003156 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01003157 goto out;
3158 }
3159 }
3160
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003161 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3162 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003163 backing_drv = bdrv_find_format(backing_fmt->value.s);
3164 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003165 error_report("Unknown backing file format '%s'",
3166 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01003167 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003168 goto out;
3169 }
3170 }
3171
3172 // The size for the image must always be specified, with one exception:
3173 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02003174 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3175 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003176 if (backing_file && backing_file->value.s) {
3177 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003178 char buf[32];
3179
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003180 bs = bdrv_new("");
3181
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003182 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003183 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00003184 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003185 goto out;
3186 }
3187 bdrv_get_geometry(bs, &size);
3188 size *= 512;
3189
3190 snprintf(buf, sizeof(buf), "%" PRId64, size);
3191 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3192 } else {
3193 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01003194 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003195 goto out;
3196 }
3197 }
3198
3199 printf("Formatting '%s', fmt=%s ", filename, fmt);
3200 print_option_parameters(param);
3201 puts("");
3202
3203 ret = bdrv_create(drv, filename, param);
3204
3205 if (ret < 0) {
3206 if (ret == -ENOTSUP) {
3207 error_report("Formatting or formatting option not supported for "
3208 "file format '%s'", fmt);
3209 } else if (ret == -EFBIG) {
3210 error_report("The image size is too large for file format '%s'",
3211 fmt);
3212 } else {
3213 error_report("%s: error while creating %s: %s", filename, fmt,
3214 strerror(-ret));
3215 }
3216 }
3217
3218out:
3219 free_option_parameters(create_options);
3220 free_option_parameters(param);
3221
3222 if (bs) {
3223 bdrv_delete(bs);
3224 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01003225
3226 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01003227}