]> git.proxmox.com Git - qemu.git/blame - block.c
qemu: init all queues to NO_VECTOR value
[qemu.git] / block.c
CommitLineData
fc01f7e7
FB
1/*
2 * QEMU System Emulator block driver
5fafdf24 3 *
fc01f7e7 4 * Copyright (c) 2003 Fabrice Bellard
5fafdf24 5 *
fc01f7e7
FB
6 * 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 */
3990d09a 24#include "config-host.h"
71e72a19 25#ifdef CONFIG_BSD
3990d09a
BS
26/* include native header before sys-queue.h */
27#include <sys/queue.h>
28#endif
29
faf07963 30#include "qemu-common.h"
376253ec 31#include "monitor.h"
ea2384d3 32#include "block_int.h"
5efa9d5a 33#include "module.h"
fc01f7e7 34
71e72a19 35#ifdef CONFIG_BSD
7674e7bf
FB
36#include <sys/types.h>
37#include <sys/stat.h>
38#include <sys/ioctl.h>
c5e97233 39#ifndef __DragonFly__
7674e7bf
FB
40#include <sys/disk.h>
41#endif
c5e97233 42#endif
7674e7bf 43
49dc768d
AL
44#ifdef _WIN32
45#include <windows.h>
46#endif
47
83f64091
FB
48#define SECTOR_BITS 9
49#define SECTOR_SIZE (1 << SECTOR_BITS)
50
f141eafe
AL
51static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
c87c0672 53 BlockDriverCompletionFunc *cb, void *opaque);
f141eafe
AL
54static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
55 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 56 BlockDriverCompletionFunc *cb, void *opaque);
5fafdf24 57static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
83f64091
FB
58 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);
ec530c81 61
7ee930d0
BS
62BlockDriverState *bdrv_first;
63
ea2384d3
FB
64static BlockDriver *first_drv;
65
83f64091 66int path_is_absolute(const char *path)
3b0d4f61 67{
83f64091 68 const char *p;
21664424
FB
69#ifdef _WIN32
70 /* specific case for names like: "\\.\d:" */
71 if (*path == '/' || *path == '\\')
72 return 1;
73#endif
83f64091
FB
74 p = strchr(path, ':');
75 if (p)
76 p++;
77 else
78 p = path;
3b9f94e1
FB
79#ifdef _WIN32
80 return (*p == '/' || *p == '\\');
81#else
82 return (*p == '/');
83#endif
3b0d4f61
FB
84}
85
83f64091
FB
86/* if filename is absolute, just copy it to dest. Otherwise, build a
87 path to it by considering it is relative to base_path. URL are
88 supported. */
89void path_combine(char *dest, int dest_size,
90 const char *base_path,
91 const char *filename)
3b0d4f61 92{
83f64091
FB
93 const char *p, *p1;
94 int len;
95
96 if (dest_size <= 0)
97 return;
98 if (path_is_absolute(filename)) {
99 pstrcpy(dest, dest_size, filename);
100 } else {
101 p = strchr(base_path, ':');
102 if (p)
103 p++;
104 else
105 p = base_path;
3b9f94e1
FB
106 p1 = strrchr(base_path, '/');
107#ifdef _WIN32
108 {
109 const char *p2;
110 p2 = strrchr(base_path, '\\');
111 if (!p1 || p2 > p1)
112 p1 = p2;
113 }
114#endif
83f64091
FB
115 if (p1)
116 p1++;
117 else
118 p1 = base_path;
119 if (p1 > p)
120 p = p1;
121 len = p - base_path;
122 if (len > dest_size - 1)
123 len = dest_size - 1;
124 memcpy(dest, base_path, len);
125 dest[len] = '\0';
126 pstrcat(dest, dest_size, filename);
3b0d4f61 127 }
3b0d4f61
FB
128}
129
5efa9d5a 130void bdrv_register(BlockDriver *bdrv)
ea2384d3 131{
f141eafe 132 if (!bdrv->bdrv_aio_readv) {
83f64091 133 /* add AIO emulation layer */
f141eafe
AL
134 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
135 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
eda578e5 136 } else if (!bdrv->bdrv_read) {
83f64091
FB
137 /* add synchronous IO emulation layer */
138 bdrv->bdrv_read = bdrv_read_em;
139 bdrv->bdrv_write = bdrv_write_em;
140 }
ea2384d3
FB
141 bdrv->next = first_drv;
142 first_drv = bdrv;
143}
b338082b
FB
144
145/* create a new block device (by default it is empty) */
146BlockDriverState *bdrv_new(const char *device_name)
147{
148 BlockDriverState **pbs, *bs;
149
150 bs = qemu_mallocz(sizeof(BlockDriverState));
b338082b 151 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
ea2384d3
FB
152 if (device_name[0] != '\0') {
153 /* insert at the end */
154 pbs = &bdrv_first;
155 while (*pbs != NULL)
156 pbs = &(*pbs)->next;
157 *pbs = bs;
158 }
b338082b
FB
159 return bs;
160}
161
ea2384d3
FB
162BlockDriver *bdrv_find_format(const char *format_name)
163{
164 BlockDriver *drv1;
165 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
166 if (!strcmp(drv1->format_name, format_name))
167 return drv1;
168 }
169 return NULL;
170}
171
0e7e1989
KW
172int bdrv_create(BlockDriver *drv, const char* filename,
173 QEMUOptionParameter *options)
ea2384d3
FB
174{
175 if (!drv->bdrv_create)
176 return -ENOTSUP;
0e7e1989
KW
177
178 return drv->bdrv_create(filename, options);
ea2384d3
FB
179}
180
d5249393 181#ifdef _WIN32
95389c86 182void get_tmp_filename(char *filename, int size)
d5249393 183{
3b9f94e1 184 char temp_dir[MAX_PATH];
3b46e624 185
3b9f94e1
FB
186 GetTempPath(MAX_PATH, temp_dir);
187 GetTempFileName(temp_dir, "qem", 0, filename);
d5249393
FB
188}
189#else
95389c86 190void get_tmp_filename(char *filename, int size)
fc01f7e7 191{
67b915a5 192 int fd;
7ccfb2eb 193 const char *tmpdir;
d5249393 194 /* XXX: race condition possible */
0badc1ee
AJ
195 tmpdir = getenv("TMPDIR");
196 if (!tmpdir)
197 tmpdir = "/tmp";
198 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
ea2384d3
FB
199 fd = mkstemp(filename);
200 close(fd);
201}
d5249393 202#endif
fc01f7e7 203
19cb3738 204#ifdef _WIN32
f45512fe
FB
205static int is_windows_drive_prefix(const char *filename)
206{
207 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
208 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
209 filename[1] == ':');
210}
3b46e624 211
508c7cb3 212int is_windows_drive(const char *filename)
19cb3738 213{
5fafdf24 214 if (is_windows_drive_prefix(filename) &&
f45512fe 215 filename[2] == '\0')
19cb3738
FB
216 return 1;
217 if (strstart(filename, "\\\\.\\", NULL) ||
218 strstart(filename, "//./", NULL))
219 return 1;
220 return 0;
221}
222#endif
223
83f64091
FB
224static BlockDriver *find_protocol(const char *filename)
225{
226 BlockDriver *drv1;
227 char protocol[128];
1cec71e3 228 int len;
83f64091 229 const char *p;
19cb3738
FB
230
231#ifdef _WIN32
f45512fe
FB
232 if (is_windows_drive(filename) ||
233 is_windows_drive_prefix(filename))
5efa9d5a 234 return bdrv_find_format("raw");
19cb3738 235#endif
1cec71e3
AL
236 p = strchr(filename, ':');
237 if (!p)
5efa9d5a 238 return bdrv_find_format("raw");
1cec71e3
AL
239 len = p - filename;
240 if (len > sizeof(protocol) - 1)
241 len = sizeof(protocol) - 1;
242 memcpy(protocol, filename, len);
243 protocol[len] = '\0';
83f64091 244 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
5fafdf24 245 if (drv1->protocol_name &&
83f64091
FB
246 !strcmp(drv1->protocol_name, protocol))
247 return drv1;
248 }
249 return NULL;
250}
251
f3a5d3f8
CH
252/*
253 * Detect host devices. By convention, /dev/cdrom[N] is always
254 * recognized as a host CDROM.
255 */
f3a5d3f8
CH
256static BlockDriver *find_hdev_driver(const char *filename)
257{
508c7cb3
CH
258 int score_max = 0, score;
259 BlockDriver *drv = NULL, *d;
f3a5d3f8 260
508c7cb3
CH
261 for (d = first_drv; d; d = d->next) {
262 if (d->bdrv_probe_device) {
263 score = d->bdrv_probe_device(filename);
264 if (score > score_max) {
265 score_max = score;
266 drv = d;
267 }
268 }
19cb3738 269 }
f3a5d3f8 270
508c7cb3 271 return drv;
f3a5d3f8 272}
3b46e624 273
f3a5d3f8
CH
274static BlockDriver *find_image_format(const char *filename)
275{
276 int ret, score, score_max;
277 BlockDriver *drv1, *drv;
278 uint8_t buf[2048];
279 BlockDriverState *bs;
280
83f64091 281 drv = find_protocol(filename);
19cb3738 282 /* no need to test disk image formats for vvfat */
c833ab73 283 if (drv && strcmp(drv->format_name, "vvfat") == 0)
83f64091 284 return drv;
19cb3738 285
83f64091
FB
286 ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
287 if (ret < 0)
288 return NULL;
289 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
290 bdrv_delete(bs);
291 if (ret < 0) {
292 return NULL;
293 }
294
ea2384d3
FB
295 score_max = 0;
296 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
83f64091
FB
297 if (drv1->bdrv_probe) {
298 score = drv1->bdrv_probe(buf, ret, filename);
299 if (score > score_max) {
300 score_max = score;
301 drv = drv1;
302 }
0849bf08 303 }
fc01f7e7 304 }
ea2384d3
FB
305 return drv;
306}
307
83f64091 308int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
ea2384d3 309{
83f64091
FB
310 BlockDriverState *bs;
311 int ret;
312
313 bs = bdrv_new("");
83f64091
FB
314 ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
315 if (ret < 0) {
316 bdrv_delete(bs);
317 return ret;
3b0d4f61 318 }
71d0770c 319 bs->growable = 1;
83f64091
FB
320 *pbs = bs;
321 return 0;
322}
323
324int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
325{
326 return bdrv_open2(bs, filename, flags, NULL);
ea2384d3
FB
327}
328
83f64091 329int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
ea2384d3
FB
330 BlockDriver *drv)
331{
83f64091 332 int ret, open_flags;
eb5c851f
TS
333 char tmp_filename[PATH_MAX];
334 char backing_filename[PATH_MAX];
3b46e624 335
ea2384d3
FB
336 bs->read_only = 0;
337 bs->is_temporary = 0;
338 bs->encrypted = 0;
c0f4ce77 339 bs->valid_key = 0;
e268ca52
AL
340 /* buffer_alignment defaulted to 512, drivers can change this value */
341 bs->buffer_alignment = 512;
712e7874 342
83f64091 343 if (flags & BDRV_O_SNAPSHOT) {
ea2384d3
FB
344 BlockDriverState *bs1;
345 int64_t total_size;
7c96d46e 346 int is_protocol = 0;
91a073a9
KW
347 BlockDriver *bdrv_qcow2;
348 QEMUOptionParameter *options;
3b46e624 349
ea2384d3
FB
350 /* if snapshot, we create a temporary backing file and open it
351 instead of opening 'filename' directly */
33e3963e 352
ea2384d3
FB
353 /* if there is a backing file, use it */
354 bs1 = bdrv_new("");
5eb45639 355 ret = bdrv_open2(bs1, filename, 0, drv);
51d7c00c 356 if (ret < 0) {
ea2384d3 357 bdrv_delete(bs1);
51d7c00c 358 return ret;
ea2384d3 359 }
83f64091 360 total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
7c96d46e
AL
361
362 if (bs1->drv && bs1->drv->protocol_name)
363 is_protocol = 1;
364
ea2384d3 365 bdrv_delete(bs1);
3b46e624 366
ea2384d3 367 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
7c96d46e
AL
368
369 /* Real path is meaningless for protocols */
370 if (is_protocol)
371 snprintf(backing_filename, sizeof(backing_filename),
372 "%s", filename);
373 else
374 realpath(filename, backing_filename);
375
91a073a9
KW
376 bdrv_qcow2 = bdrv_find_format("qcow2");
377 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
378
379 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
380 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
381 if (drv) {
382 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
383 drv->format_name);
384 }
385
386 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
51d7c00c
AL
387 if (ret < 0) {
388 return ret;
ea2384d3 389 }
91a073a9 390
ea2384d3 391 filename = tmp_filename;
91a073a9 392 drv = bdrv_qcow2;
ea2384d3
FB
393 bs->is_temporary = 1;
394 }
712e7874 395
ea2384d3 396 pstrcpy(bs->filename, sizeof(bs->filename), filename);
83f64091
FB
397 if (flags & BDRV_O_FILE) {
398 drv = find_protocol(filename);
51d7c00c 399 } else if (!drv) {
f3a5d3f8
CH
400 drv = find_hdev_driver(filename);
401 if (!drv) {
402 drv = find_image_format(filename);
403 }
51d7c00c
AL
404 }
405 if (!drv) {
406 ret = -ENOENT;
407 goto unlink_and_fail;
ea2384d3
FB
408 }
409 bs->drv = drv;
410 bs->opaque = qemu_mallocz(drv->instance_size);
83f64091
FB
411 /* Note: for compatibility, we open disk image files as RDWR, and
412 RDONLY as fallback */
413 if (!(flags & BDRV_O_FILE))
5c6c3a6c
CH
414 open_flags = BDRV_O_RDWR |
415 (flags & (BDRV_O_CACHE_MASK|BDRV_O_NATIVE_AIO));
83f64091
FB
416 else
417 open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
1cec71e3 418 ret = drv->bdrv_open(bs, filename, open_flags);
a0a83536 419 if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
1cec71e3 420 ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
83f64091
FB
421 bs->read_only = 1;
422 }
ea2384d3
FB
423 if (ret < 0) {
424 qemu_free(bs->opaque);
6b21b973
FB
425 bs->opaque = NULL;
426 bs->drv = NULL;
51d7c00c
AL
427 unlink_and_fail:
428 if (bs->is_temporary)
429 unlink(filename);
83f64091 430 return ret;
33e3963e 431 }
d15a771d
FB
432 if (drv->bdrv_getlength) {
433 bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
434 }
67b915a5 435#ifndef _WIN32
ea2384d3
FB
436 if (bs->is_temporary) {
437 unlink(filename);
438 }
439#endif
83f64091 440 if (bs->backing_file[0] != '\0') {
ea2384d3 441 /* if there is a backing file, use it */
5eb45639 442 BlockDriver *back_drv = NULL;
ea2384d3 443 bs->backing_hd = bdrv_new("");
83f64091
FB
444 path_combine(backing_filename, sizeof(backing_filename),
445 filename, bs->backing_file);
5eb45639
AL
446 if (bs->backing_format[0] != '\0')
447 back_drv = bdrv_find_format(bs->backing_format);
448 ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,
449 back_drv);
51d7c00c
AL
450 if (ret < 0) {
451 bdrv_close(bs);
452 return ret;
453 }
33e3963e
FB
454 }
455
bb5fc20f
AL
456 if (!bdrv_key_required(bs)) {
457 /* call the change callback */
458 bs->media_changed = 1;
459 if (bs->change_cb)
460 bs->change_cb(bs->change_opaque);
461 }
b338082b 462 return 0;
fc01f7e7
FB
463}
464
465void bdrv_close(BlockDriverState *bs)
466{
19cb3738 467 if (bs->drv) {
ea2384d3
FB
468 if (bs->backing_hd)
469 bdrv_delete(bs->backing_hd);
470 bs->drv->bdrv_close(bs);
471 qemu_free(bs->opaque);
472#ifdef _WIN32
473 if (bs->is_temporary) {
474 unlink(bs->filename);
475 }
67b915a5 476#endif
ea2384d3
FB
477 bs->opaque = NULL;
478 bs->drv = NULL;
b338082b
FB
479
480 /* call the change callback */
19cb3738 481 bs->media_changed = 1;
b338082b
FB
482 if (bs->change_cb)
483 bs->change_cb(bs->change_opaque);
484 }
485}
486
487void bdrv_delete(BlockDriverState *bs)
488{
34c6f050
AJ
489 BlockDriverState **pbs;
490
491 pbs = &bdrv_first;
492 while (*pbs != bs && *pbs != NULL)
493 pbs = &(*pbs)->next;
494 if (*pbs == bs)
495 *pbs = bs->next;
496
b338082b
FB
497 bdrv_close(bs);
498 qemu_free(bs);
fc01f7e7
FB
499}
500
e97fc193
AL
501/*
502 * Run consistency checks on an image
503 *
504 * Returns the number of errors or -errno when an internal error occurs
505 */
506int bdrv_check(BlockDriverState *bs)
507{
508 if (bs->drv->bdrv_check == NULL) {
509 return -ENOTSUP;
510 }
511
512 return bs->drv->bdrv_check(bs);
513}
514
33e3963e
FB
515/* commit COW file into the raw image */
516int bdrv_commit(BlockDriverState *bs)
517{
19cb3738 518 BlockDriver *drv = bs->drv;
83f64091 519 int64_t i, total_sectors;
ea2384d3
FB
520 int n, j;
521 unsigned char sector[512];
33e3963e 522
19cb3738
FB
523 if (!drv)
524 return -ENOMEDIUM;
33e3963e
FB
525
526 if (bs->read_only) {
ea2384d3 527 return -EACCES;
33e3963e
FB
528 }
529
ea2384d3
FB
530 if (!bs->backing_hd) {
531 return -ENOTSUP;
532 }
33e3963e 533
83f64091
FB
534 total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
535 for (i = 0; i < total_sectors;) {
19cb3738 536 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
ea2384d3
FB
537 for(j = 0; j < n; j++) {
538 if (bdrv_read(bs, i, sector, 1) != 0) {
539 return -EIO;
540 }
541
542 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
543 return -EIO;
544 }
545 i++;
33e3963e 546 }
ea2384d3
FB
547 } else {
548 i += n;
549 }
33e3963e 550 }
95389c86 551
19cb3738
FB
552 if (drv->bdrv_make_empty)
553 return drv->bdrv_make_empty(bs);
95389c86 554
33e3963e
FB
555 return 0;
556}
557
71d0770c
AL
558static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
559 size_t size)
560{
561 int64_t len;
562
563 if (!bdrv_is_inserted(bs))
564 return -ENOMEDIUM;
565
566 if (bs->growable)
567 return 0;
568
569 len = bdrv_getlength(bs);
570
fbb7b4e0
KW
571 if (offset < 0)
572 return -EIO;
573
574 if ((offset > len) || (len - offset < size))
71d0770c
AL
575 return -EIO;
576
577 return 0;
578}
579
580static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
581 int nb_sectors)
582{
999dec57 583 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
71d0770c
AL
584}
585
19cb3738 586/* return < 0 if error. See bdrv_write() for the return codes */
5fafdf24 587int bdrv_read(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
588 uint8_t *buf, int nb_sectors)
589{
ea2384d3
FB
590 BlockDriver *drv = bs->drv;
591
19cb3738
FB
592 if (!drv)
593 return -ENOMEDIUM;
71d0770c
AL
594 if (bdrv_check_request(bs, sector_num, nb_sectors))
595 return -EIO;
b338082b 596
eda578e5 597 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
fc01f7e7
FB
598}
599
5fafdf24 600/* Return < 0 if error. Important errors are:
19cb3738
FB
601 -EIO generic I/O error (may happen for all errors)
602 -ENOMEDIUM No media inserted.
603 -EINVAL Invalid sector number or nb_sectors
604 -EACCES Trying to write a read-only device
605*/
5fafdf24 606int bdrv_write(BlockDriverState *bs, int64_t sector_num,
fc01f7e7
FB
607 const uint8_t *buf, int nb_sectors)
608{
83f64091 609 BlockDriver *drv = bs->drv;
19cb3738
FB
610 if (!bs->drv)
611 return -ENOMEDIUM;
0849bf08 612 if (bs->read_only)
19cb3738 613 return -EACCES;
71d0770c
AL
614 if (bdrv_check_request(bs, sector_num, nb_sectors))
615 return -EIO;
616
42fb2807 617 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
83f64091
FB
618}
619
eda578e5
AL
620int bdrv_pread(BlockDriverState *bs, int64_t offset,
621 void *buf, int count1)
83f64091 622{
83f64091
FB
623 uint8_t tmp_buf[SECTOR_SIZE];
624 int len, nb_sectors, count;
625 int64_t sector_num;
626
627 count = count1;
628 /* first read to align to sector start */
629 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
630 if (len > count)
631 len = count;
632 sector_num = offset >> SECTOR_BITS;
633 if (len > 0) {
634 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
635 return -EIO;
636 memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
637 count -= len;
638 if (count == 0)
639 return count1;
640 sector_num++;
641 buf += len;
642 }
643
644 /* read the sectors "in place" */
645 nb_sectors = count >> SECTOR_BITS;
646 if (nb_sectors > 0) {
647 if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
648 return -EIO;
649 sector_num += nb_sectors;
650 len = nb_sectors << SECTOR_BITS;
651 buf += len;
652 count -= len;
653 }
654
655 /* add data from the last sector */
656 if (count > 0) {
657 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
658 return -EIO;
659 memcpy(buf, tmp_buf, count);
660 }
661 return count1;
662}
663
eda578e5
AL
664int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
665 const void *buf, int count1)
83f64091 666{
83f64091
FB
667 uint8_t tmp_buf[SECTOR_SIZE];
668 int len, nb_sectors, count;
669 int64_t sector_num;
670
671 count = count1;
672 /* first write to align to sector start */
673 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
674 if (len > count)
675 len = count;
676 sector_num = offset >> SECTOR_BITS;
677 if (len > 0) {
678 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
679 return -EIO;
680 memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
681 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
682 return -EIO;
683 count -= len;
684 if (count == 0)
685 return count1;
686 sector_num++;
687 buf += len;
688 }
689
690 /* write the sectors "in place" */
691 nb_sectors = count >> SECTOR_BITS;
692 if (nb_sectors > 0) {
693 if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
694 return -EIO;
695 sector_num += nb_sectors;
696 len = nb_sectors << SECTOR_BITS;
697 buf += len;
698 count -= len;
699 }
700
701 /* add data from the last sector */
702 if (count > 0) {
703 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
704 return -EIO;
705 memcpy(tmp_buf, buf, count);
706 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
707 return -EIO;
708 }
709 return count1;
710}
83f64091 711
83f64091
FB
712/**
713 * Truncate file to 'offset' bytes (needed only for file protocols)
714 */
715int bdrv_truncate(BlockDriverState *bs, int64_t offset)
716{
717 BlockDriver *drv = bs->drv;
718 if (!drv)
19cb3738 719 return -ENOMEDIUM;
83f64091
FB
720 if (!drv->bdrv_truncate)
721 return -ENOTSUP;
722 return drv->bdrv_truncate(bs, offset);
723}
724
725/**
726 * Length of a file in bytes. Return < 0 if error or unknown.
727 */
728int64_t bdrv_getlength(BlockDriverState *bs)
729{
730 BlockDriver *drv = bs->drv;
731 if (!drv)
19cb3738 732 return -ENOMEDIUM;
83f64091
FB
733 if (!drv->bdrv_getlength) {
734 /* legacy mode */
735 return bs->total_sectors * SECTOR_SIZE;
736 }
737 return drv->bdrv_getlength(bs);
fc01f7e7
FB
738}
739
19cb3738 740/* return 0 as number of sectors if no device present or error */
96b8f136 741void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
fc01f7e7 742{
19cb3738
FB
743 int64_t length;
744 length = bdrv_getlength(bs);
745 if (length < 0)
746 length = 0;
747 else
748 length = length >> SECTOR_BITS;
749 *nb_sectors_ptr = length;
fc01f7e7 750}
cf98951b 751
f3d54fc4
AL
752struct partition {
753 uint8_t boot_ind; /* 0x80 - active */
754 uint8_t head; /* starting head */
755 uint8_t sector; /* starting sector */
756 uint8_t cyl; /* starting cylinder */
757 uint8_t sys_ind; /* What partition type */
758 uint8_t end_head; /* end head */
759 uint8_t end_sector; /* end sector */
760 uint8_t end_cyl; /* end cylinder */
761 uint32_t start_sect; /* starting sector counting from 0 */
762 uint32_t nr_sects; /* nr of sectors in partition */
763} __attribute__((packed));
764
765/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
766static int guess_disk_lchs(BlockDriverState *bs,
767 int *pcylinders, int *pheads, int *psectors)
768{
769 uint8_t buf[512];
770 int ret, i, heads, sectors, cylinders;
771 struct partition *p;
772 uint32_t nr_sects;
a38131b6 773 uint64_t nb_sectors;
f3d54fc4
AL
774
775 bdrv_get_geometry(bs, &nb_sectors);
776
777 ret = bdrv_read(bs, 0, buf, 1);
778 if (ret < 0)
779 return -1;
780 /* test msdos magic */
781 if (buf[510] != 0x55 || buf[511] != 0xaa)
782 return -1;
783 for(i = 0; i < 4; i++) {
784 p = ((struct partition *)(buf + 0x1be)) + i;
785 nr_sects = le32_to_cpu(p->nr_sects);
786 if (nr_sects && p->end_head) {
787 /* We make the assumption that the partition terminates on
788 a cylinder boundary */
789 heads = p->end_head + 1;
790 sectors = p->end_sector & 63;
791 if (sectors == 0)
792 continue;
793 cylinders = nb_sectors / (heads * sectors);
794 if (cylinders < 1 || cylinders > 16383)
795 continue;
796 *pheads = heads;
797 *psectors = sectors;
798 *pcylinders = cylinders;
799#if 0
800 printf("guessed geometry: LCHS=%d %d %d\n",
801 cylinders, heads, sectors);
802#endif
803 return 0;
804 }
805 }
806 return -1;
807}
808
809void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
810{
811 int translation, lba_detected = 0;
812 int cylinders, heads, secs;
a38131b6 813 uint64_t nb_sectors;
f3d54fc4
AL
814
815 /* if a geometry hint is available, use it */
816 bdrv_get_geometry(bs, &nb_sectors);
817 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
818 translation = bdrv_get_translation_hint(bs);
819 if (cylinders != 0) {
820 *pcyls = cylinders;
821 *pheads = heads;
822 *psecs = secs;
823 } else {
824 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
825 if (heads > 16) {
826 /* if heads > 16, it means that a BIOS LBA
827 translation was active, so the default
828 hardware geometry is OK */
829 lba_detected = 1;
830 goto default_geometry;
831 } else {
832 *pcyls = cylinders;
833 *pheads = heads;
834 *psecs = secs;
835 /* disable any translation to be in sync with
836 the logical geometry */
837 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
838 bdrv_set_translation_hint(bs,
839 BIOS_ATA_TRANSLATION_NONE);
840 }
841 }
842 } else {
843 default_geometry:
844 /* if no geometry, use a standard physical disk geometry */
845 cylinders = nb_sectors / (16 * 63);
846
847 if (cylinders > 16383)
848 cylinders = 16383;
849 else if (cylinders < 2)
850 cylinders = 2;
851 *pcyls = cylinders;
852 *pheads = 16;
853 *psecs = 63;
854 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
855 if ((*pcyls * *pheads) <= 131072) {
856 bdrv_set_translation_hint(bs,
857 BIOS_ATA_TRANSLATION_LARGE);
858 } else {
859 bdrv_set_translation_hint(bs,
860 BIOS_ATA_TRANSLATION_LBA);
861 }
862 }
863 }
864 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
865 }
866}
867
5fafdf24 868void bdrv_set_geometry_hint(BlockDriverState *bs,
b338082b
FB
869 int cyls, int heads, int secs)
870{
871 bs->cyls = cyls;
872 bs->heads = heads;
873 bs->secs = secs;
874}
875
876void bdrv_set_type_hint(BlockDriverState *bs, int type)
877{
878 bs->type = type;
879 bs->removable = ((type == BDRV_TYPE_CDROM ||
880 type == BDRV_TYPE_FLOPPY));
881}
882
46d4767d
FB
883void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
884{
885 bs->translation = translation;
886}
887
5fafdf24 888void bdrv_get_geometry_hint(BlockDriverState *bs,
b338082b
FB
889 int *pcyls, int *pheads, int *psecs)
890{
891 *pcyls = bs->cyls;
892 *pheads = bs->heads;
893 *psecs = bs->secs;
894}
895
896int bdrv_get_type_hint(BlockDriverState *bs)
897{
898 return bs->type;
899}
900
46d4767d
FB
901int bdrv_get_translation_hint(BlockDriverState *bs)
902{
903 return bs->translation;
904}
905
b338082b
FB
906int bdrv_is_removable(BlockDriverState *bs)
907{
908 return bs->removable;
909}
910
911int bdrv_is_read_only(BlockDriverState *bs)
912{
913 return bs->read_only;
914}
915
985a03b0
TS
916int bdrv_is_sg(BlockDriverState *bs)
917{
918 return bs->sg;
919}
920
19cb3738 921/* XXX: no longer used */
5fafdf24 922void bdrv_set_change_cb(BlockDriverState *bs,
b338082b
FB
923 void (*change_cb)(void *opaque), void *opaque)
924{
925 bs->change_cb = change_cb;
926 bs->change_opaque = opaque;
927}
928
ea2384d3
FB
929int bdrv_is_encrypted(BlockDriverState *bs)
930{
931 if (bs->backing_hd && bs->backing_hd->encrypted)
932 return 1;
933 return bs->encrypted;
934}
935
c0f4ce77
AL
936int bdrv_key_required(BlockDriverState *bs)
937{
938 BlockDriverState *backing_hd = bs->backing_hd;
939
940 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
941 return 1;
942 return (bs->encrypted && !bs->valid_key);
943}
944
ea2384d3
FB
945int bdrv_set_key(BlockDriverState *bs, const char *key)
946{
947 int ret;
948 if (bs->backing_hd && bs->backing_hd->encrypted) {
949 ret = bdrv_set_key(bs->backing_hd, key);
950 if (ret < 0)
951 return ret;
952 if (!bs->encrypted)
953 return 0;
954 }
955 if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
956 return -1;
c0f4ce77 957 ret = bs->drv->bdrv_set_key(bs, key);
bb5fc20f
AL
958 if (ret < 0) {
959 bs->valid_key = 0;
960 } else if (!bs->valid_key) {
961 bs->valid_key = 1;
962 /* call the change callback now, we skipped it on open */
963 bs->media_changed = 1;
964 if (bs->change_cb)
965 bs->change_cb(bs->change_opaque);
966 }
c0f4ce77 967 return ret;
ea2384d3
FB
968}
969
970void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
971{
19cb3738 972 if (!bs->drv) {
ea2384d3
FB
973 buf[0] = '\0';
974 } else {
975 pstrcpy(buf, buf_size, bs->drv->format_name);
976 }
977}
978
5fafdf24 979void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
ea2384d3
FB
980 void *opaque)
981{
982 BlockDriver *drv;
983
984 for (drv = first_drv; drv != NULL; drv = drv->next) {
985 it(opaque, drv->format_name);
986 }
987}
988
b338082b
FB
989BlockDriverState *bdrv_find(const char *name)
990{
991 BlockDriverState *bs;
992
993 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
994 if (!strcmp(name, bs->device_name))
995 return bs;
996 }
997 return NULL;
998}
999
51de9760 1000void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
81d0912d
FB
1001{
1002 BlockDriverState *bs;
1003
1004 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
51de9760 1005 it(opaque, bs);
81d0912d
FB
1006 }
1007}
1008
ea2384d3
FB
1009const char *bdrv_get_device_name(BlockDriverState *bs)
1010{
1011 return bs->device_name;
1012}
1013
7a6cba61
PB
1014void bdrv_flush(BlockDriverState *bs)
1015{
081501da
AL
1016 if (!bs->drv)
1017 return;
7a6cba61
PB
1018 if (bs->drv->bdrv_flush)
1019 bs->drv->bdrv_flush(bs);
1020 if (bs->backing_hd)
1021 bdrv_flush(bs->backing_hd);
1022}
1023
c6ca28d6
AL
1024void bdrv_flush_all(void)
1025{
1026 BlockDriverState *bs;
1027
1028 for (bs = bdrv_first; bs != NULL; bs = bs->next)
1029 if (bs->drv && !bdrv_is_read_only(bs) &&
1030 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs)))
1031 bdrv_flush(bs);
1032}
1033
f58c7b35
TS
1034/*
1035 * Returns true iff the specified sector is present in the disk image. Drivers
1036 * not implementing the functionality are assumed to not support backing files,
1037 * hence all their sectors are reported as allocated.
1038 *
1039 * 'pnum' is set to the number of sectors (including and immediately following
1040 * the specified sector) that are known to be in the same
1041 * allocated/unallocated state.
1042 *
1043 * 'nb_sectors' is the max value 'pnum' should be set to.
1044 */
1045int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1046 int *pnum)
1047{
1048 int64_t n;
1049 if (!bs->drv->bdrv_is_allocated) {
1050 if (sector_num >= bs->total_sectors) {
1051 *pnum = 0;
1052 return 0;
1053 }
1054 n = bs->total_sectors - sector_num;
1055 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1056 return 1;
1057 }
1058 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1059}
1060
376253ec 1061void bdrv_info(Monitor *mon)
b338082b
FB
1062{
1063 BlockDriverState *bs;
1064
1065 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
376253ec
AL
1066 monitor_printf(mon, "%s:", bs->device_name);
1067 monitor_printf(mon, " type=");
b338082b
FB
1068 switch(bs->type) {
1069 case BDRV_TYPE_HD:
376253ec 1070 monitor_printf(mon, "hd");
b338082b
FB
1071 break;
1072 case BDRV_TYPE_CDROM:
376253ec 1073 monitor_printf(mon, "cdrom");
b338082b
FB
1074 break;
1075 case BDRV_TYPE_FLOPPY:
376253ec 1076 monitor_printf(mon, "floppy");
b338082b
FB
1077 break;
1078 }
376253ec 1079 monitor_printf(mon, " removable=%d", bs->removable);
b338082b 1080 if (bs->removable) {
376253ec 1081 monitor_printf(mon, " locked=%d", bs->locked);
b338082b 1082 }
19cb3738 1083 if (bs->drv) {
376253ec
AL
1084 monitor_printf(mon, " file=");
1085 monitor_print_filename(mon, bs->filename);
fef30743 1086 if (bs->backing_file[0] != '\0') {
376253ec
AL
1087 monitor_printf(mon, " backing_file=");
1088 monitor_print_filename(mon, bs->backing_file);
1089 }
1090 monitor_printf(mon, " ro=%d", bs->read_only);
1091 monitor_printf(mon, " drv=%s", bs->drv->format_name);
1092 monitor_printf(mon, " encrypted=%d", bdrv_is_encrypted(bs));
b338082b 1093 } else {
376253ec 1094 monitor_printf(mon, " [not inserted]");
b338082b 1095 }
376253ec 1096 monitor_printf(mon, "\n");
b338082b
FB
1097 }
1098}
a36e69dd
TS
1099
1100/* The "info blockstats" command. */
376253ec 1101void bdrv_info_stats(Monitor *mon)
a36e69dd
TS
1102{
1103 BlockDriverState *bs;
1104
1105 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
376253ec
AL
1106 monitor_printf(mon, "%s:"
1107 " rd_bytes=%" PRIu64
1108 " wr_bytes=%" PRIu64
1109 " rd_operations=%" PRIu64
1110 " wr_operations=%" PRIu64
ebf53fcd 1111 "\n",
376253ec
AL
1112 bs->device_name,
1113 bs->rd_bytes, bs->wr_bytes,
1114 bs->rd_ops, bs->wr_ops);
a36e69dd
TS
1115 }
1116}
ea2384d3 1117
045df330
AL
1118const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1119{
1120 if (bs->backing_hd && bs->backing_hd->encrypted)
1121 return bs->backing_file;
1122 else if (bs->encrypted)
1123 return bs->filename;
1124 else
1125 return NULL;
1126}
1127
5fafdf24 1128void bdrv_get_backing_filename(BlockDriverState *bs,
83f64091
FB
1129 char *filename, int filename_size)
1130{
1131 if (!bs->backing_hd) {
1132 pstrcpy(filename, filename_size, "");
1133 } else {
1134 pstrcpy(filename, filename_size, bs->backing_file);
1135 }
1136}
1137
5fafdf24 1138int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
faea38e7
FB
1139 const uint8_t *buf, int nb_sectors)
1140{
1141 BlockDriver *drv = bs->drv;
1142 if (!drv)
19cb3738 1143 return -ENOMEDIUM;
faea38e7
FB
1144 if (!drv->bdrv_write_compressed)
1145 return -ENOTSUP;
fbb7b4e0
KW
1146 if (bdrv_check_request(bs, sector_num, nb_sectors))
1147 return -EIO;
faea38e7
FB
1148 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1149}
3b46e624 1150
faea38e7
FB
1151int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1152{
1153 BlockDriver *drv = bs->drv;
1154 if (!drv)
19cb3738 1155 return -ENOMEDIUM;
faea38e7
FB
1156 if (!drv->bdrv_get_info)
1157 return -ENOTSUP;
1158 memset(bdi, 0, sizeof(*bdi));
1159 return drv->bdrv_get_info(bs, bdi);
1160}
1161
45566e9c
CH
1162int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1163 int64_t pos, int size)
178e08a5
AL
1164{
1165 BlockDriver *drv = bs->drv;
1166 if (!drv)
1167 return -ENOMEDIUM;
45566e9c 1168 if (!drv->bdrv_save_vmstate)
178e08a5 1169 return -ENOTSUP;
45566e9c 1170 return drv->bdrv_save_vmstate(bs, buf, pos, size);
178e08a5
AL
1171}
1172
45566e9c
CH
1173int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1174 int64_t pos, int size)
178e08a5
AL
1175{
1176 BlockDriver *drv = bs->drv;
1177 if (!drv)
1178 return -ENOMEDIUM;
45566e9c 1179 if (!drv->bdrv_load_vmstate)
178e08a5 1180 return -ENOTSUP;
45566e9c 1181 return drv->bdrv_load_vmstate(bs, buf, pos, size);
178e08a5
AL
1182}
1183
faea38e7
FB
1184/**************************************************************/
1185/* handling of snapshots */
1186
5fafdf24 1187int bdrv_snapshot_create(BlockDriverState *bs,
faea38e7
FB
1188 QEMUSnapshotInfo *sn_info)
1189{
1190 BlockDriver *drv = bs->drv;
1191 if (!drv)
19cb3738 1192 return -ENOMEDIUM;
faea38e7
FB
1193 if (!drv->bdrv_snapshot_create)
1194 return -ENOTSUP;
1195 return drv->bdrv_snapshot_create(bs, sn_info);
1196}
1197
5fafdf24 1198int bdrv_snapshot_goto(BlockDriverState *bs,
faea38e7
FB
1199 const char *snapshot_id)
1200{
1201 BlockDriver *drv = bs->drv;
1202 if (!drv)
19cb3738 1203 return -ENOMEDIUM;
faea38e7
FB
1204 if (!drv->bdrv_snapshot_goto)
1205 return -ENOTSUP;
1206 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1207}
1208
1209int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1210{
1211 BlockDriver *drv = bs->drv;
1212 if (!drv)
19cb3738 1213 return -ENOMEDIUM;
faea38e7
FB
1214 if (!drv->bdrv_snapshot_delete)
1215 return -ENOTSUP;
1216 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1217}
1218
5fafdf24 1219int bdrv_snapshot_list(BlockDriverState *bs,
faea38e7
FB
1220 QEMUSnapshotInfo **psn_info)
1221{
1222 BlockDriver *drv = bs->drv;
1223 if (!drv)
19cb3738 1224 return -ENOMEDIUM;
faea38e7
FB
1225 if (!drv->bdrv_snapshot_list)
1226 return -ENOTSUP;
1227 return drv->bdrv_snapshot_list(bs, psn_info);
1228}
1229
1230#define NB_SUFFIXES 4
1231
1232char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1233{
1234 static const char suffixes[NB_SUFFIXES] = "KMGT";
1235 int64_t base;
1236 int i;
1237
1238 if (size <= 999) {
1239 snprintf(buf, buf_size, "%" PRId64, size);
1240 } else {
1241 base = 1024;
1242 for(i = 0; i < NB_SUFFIXES; i++) {
1243 if (size < (10 * base)) {
5fafdf24 1244 snprintf(buf, buf_size, "%0.1f%c",
faea38e7
FB
1245 (double)size / base,
1246 suffixes[i]);
1247 break;
1248 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
5fafdf24 1249 snprintf(buf, buf_size, "%" PRId64 "%c",
faea38e7
FB
1250 ((size + (base >> 1)) / base),
1251 suffixes[i]);
1252 break;
1253 }
1254 base = base * 1024;
1255 }
1256 }
1257 return buf;
1258}
1259
1260char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1261{
1262 char buf1[128], date_buf[128], clock_buf[128];
3b9f94e1
FB
1263#ifdef _WIN32
1264 struct tm *ptm;
1265#else
faea38e7 1266 struct tm tm;
3b9f94e1 1267#endif
faea38e7
FB
1268 time_t ti;
1269 int64_t secs;
1270
1271 if (!sn) {
5fafdf24
TS
1272 snprintf(buf, buf_size,
1273 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
1274 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1275 } else {
1276 ti = sn->date_sec;
3b9f94e1
FB
1277#ifdef _WIN32
1278 ptm = localtime(&ti);
1279 strftime(date_buf, sizeof(date_buf),
1280 "%Y-%m-%d %H:%M:%S", ptm);
1281#else
faea38e7
FB
1282 localtime_r(&ti, &tm);
1283 strftime(date_buf, sizeof(date_buf),
1284 "%Y-%m-%d %H:%M:%S", &tm);
3b9f94e1 1285#endif
faea38e7
FB
1286 secs = sn->vm_clock_nsec / 1000000000;
1287 snprintf(clock_buf, sizeof(clock_buf),
1288 "%02d:%02d:%02d.%03d",
1289 (int)(secs / 3600),
1290 (int)((secs / 60) % 60),
5fafdf24 1291 (int)(secs % 60),
faea38e7
FB
1292 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1293 snprintf(buf, buf_size,
5fafdf24 1294 "%-10s%-20s%7s%20s%15s",
faea38e7
FB
1295 sn->id_str, sn->name,
1296 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1297 date_buf,
1298 clock_buf);
1299 }
1300 return buf;
1301}
1302
83f64091 1303
ea2384d3 1304/**************************************************************/
83f64091 1305/* async I/Os */
ea2384d3 1306
3b69e4b9 1307BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
f141eafe 1308 QEMUIOVector *qiov, int nb_sectors,
3b69e4b9 1309 BlockDriverCompletionFunc *cb, void *opaque)
83f64091
FB
1310{
1311 BlockDriver *drv = bs->drv;
a36e69dd 1312 BlockDriverAIOCB *ret;
83f64091 1313
19cb3738 1314 if (!drv)
ce1a14dc 1315 return NULL;
71d0770c
AL
1316 if (bdrv_check_request(bs, sector_num, nb_sectors))
1317 return NULL;
3b46e624 1318
f141eafe
AL
1319 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1320 cb, opaque);
a36e69dd
TS
1321
1322 if (ret) {
1323 /* Update stats even though technically transfer has not happened. */
1324 bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1325 bs->rd_ops ++;
1326 }
1327
1328 return ret;
ea2384d3
FB
1329}
1330
f141eafe
AL
1331BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1332 QEMUIOVector *qiov, int nb_sectors,
1333 BlockDriverCompletionFunc *cb, void *opaque)
ea2384d3 1334{
83f64091 1335 BlockDriver *drv = bs->drv;
a36e69dd 1336 BlockDriverAIOCB *ret;
ea2384d3 1337
19cb3738 1338 if (!drv)
ce1a14dc 1339 return NULL;
83f64091 1340 if (bs->read_only)
ce1a14dc 1341 return NULL;
71d0770c
AL
1342 if (bdrv_check_request(bs, sector_num, nb_sectors))
1343 return NULL;
83f64091 1344
f141eafe
AL
1345 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1346 cb, opaque);
a36e69dd
TS
1347
1348 if (ret) {
1349 /* Update stats even though technically transfer has not happened. */
1350 bs->wr_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1351 bs->wr_ops ++;
1352 }
1353
1354 return ret;
83f64091
FB
1355}
1356
40b4f539
KW
1357
1358typedef struct MultiwriteCB {
1359 int error;
1360 int num_requests;
1361 int num_callbacks;
1362 struct {
1363 BlockDriverCompletionFunc *cb;
1364 void *opaque;
1365 QEMUIOVector *free_qiov;
1366 void *free_buf;
1367 } callbacks[];
1368} MultiwriteCB;
1369
1370static void multiwrite_user_cb(MultiwriteCB *mcb)
1371{
1372 int i;
1373
1374 for (i = 0; i < mcb->num_callbacks; i++) {
1375 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1376 qemu_free(mcb->callbacks[i].free_qiov);
1377 qemu_free(mcb->callbacks[i].free_buf);
1378 }
1379}
1380
1381static void multiwrite_cb(void *opaque, int ret)
1382{
1383 MultiwriteCB *mcb = opaque;
1384
1385 if (ret < 0) {
1386 mcb->error = ret;
1387 multiwrite_user_cb(mcb);
1388 }
1389
1390 mcb->num_requests--;
1391 if (mcb->num_requests == 0) {
1392 if (mcb->error == 0) {
1393 multiwrite_user_cb(mcb);
1394 }
1395 qemu_free(mcb);
1396 }
1397}
1398
1399static int multiwrite_req_compare(const void *a, const void *b)
1400{
1401 return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
1402}
1403
1404/*
1405 * Takes a bunch of requests and tries to merge them. Returns the number of
1406 * requests that remain after merging.
1407 */
1408static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1409 int num_reqs, MultiwriteCB *mcb)
1410{
1411 int i, outidx;
1412
1413 // Sort requests by start sector
1414 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1415
1416 // Check if adjacent requests touch the same clusters. If so, combine them,
1417 // filling up gaps with zero sectors.
1418 outidx = 0;
1419 for (i = 1; i < num_reqs; i++) {
1420 int merge = 0;
1421 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1422
1423 // This handles the cases that are valid for all block drivers, namely
1424 // exactly sequential writes and overlapping writes.
1425 if (reqs[i].sector <= oldreq_last) {
1426 merge = 1;
1427 }
1428
1429 // The block driver may decide that it makes sense to combine requests
1430 // even if there is a gap of some sectors between them. In this case,
1431 // the gap is filled with zeros (therefore only applicable for yet
1432 // unused space in format like qcow2).
1433 if (!merge && bs->drv->bdrv_merge_requests) {
1434 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1435 }
1436
1437 if (merge) {
1438 size_t size;
1439 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1440 qemu_iovec_init(qiov,
1441 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1442
1443 // Add the first request to the merged one. If the requests are
1444 // overlapping, drop the last sectors of the first request.
1445 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1446 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1447
1448 // We might need to add some zeros between the two requests
1449 if (reqs[i].sector > oldreq_last) {
1450 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1451 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1452 memset(buf, 0, zero_bytes);
1453 qemu_iovec_add(qiov, buf, zero_bytes);
1454 mcb->callbacks[i].free_buf = buf;
1455 }
1456
1457 // Add the second request
1458 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1459
1460 reqs[outidx].nb_sectors += reqs[i].nb_sectors;
1461 reqs[outidx].qiov = qiov;
1462
1463 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1464 } else {
1465 outidx++;
1466 reqs[outidx].sector = reqs[i].sector;
1467 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1468 reqs[outidx].qiov = reqs[i].qiov;
1469 }
1470 }
1471
1472 return outidx + 1;
1473}
1474
1475/*
1476 * Submit multiple AIO write requests at once.
1477 *
1478 * On success, the function returns 0 and all requests in the reqs array have
1479 * been submitted. In error case this function returns -1, and any of the
1480 * requests may or may not be submitted yet. In particular, this means that the
1481 * callback will be called for some of the requests, for others it won't. The
1482 * caller must check the error field of the BlockRequest to wait for the right
1483 * callbacks (if error != 0, no callback will be called).
1484 *
1485 * The implementation may modify the contents of the reqs array, e.g. to merge
1486 * requests. However, the fields opaque and error are left unmodified as they
1487 * are used to signal failure for a single request to the caller.
1488 */
1489int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1490{
1491 BlockDriverAIOCB *acb;
1492 MultiwriteCB *mcb;
1493 int i;
1494
1495 if (num_reqs == 0) {
1496 return 0;
1497 }
1498
1499 // Create MultiwriteCB structure
1500 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1501 mcb->num_requests = 0;
1502 mcb->num_callbacks = num_reqs;
1503
1504 for (i = 0; i < num_reqs; i++) {
1505 mcb->callbacks[i].cb = reqs[i].cb;
1506 mcb->callbacks[i].opaque = reqs[i].opaque;
1507 }
1508
1509 // Check for mergable requests
1510 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1511
1512 // Run the aio requests
1513 for (i = 0; i < num_reqs; i++) {
1514 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
1515 reqs[i].nb_sectors, multiwrite_cb, mcb);
1516
1517 if (acb == NULL) {
1518 // We can only fail the whole thing if no request has been
1519 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1520 // complete and report the error in the callback.
1521 if (mcb->num_requests == 0) {
1522 reqs[i].error = EIO;
1523 goto fail;
1524 } else {
1525 mcb->error = EIO;
1526 break;
1527 }
1528 } else {
1529 mcb->num_requests++;
1530 }
1531 }
1532
1533 return 0;
1534
1535fail:
1536 free(mcb);
1537 return -1;
1538}
1539
83f64091 1540void bdrv_aio_cancel(BlockDriverAIOCB *acb)
83f64091 1541{
6bbff9a0 1542 acb->pool->cancel(acb);
83f64091
FB
1543}
1544
ce1a14dc 1545
83f64091
FB
1546/**************************************************************/
1547/* async block device emulation */
1548
c16b5a2c
CH
1549typedef struct BlockDriverAIOCBSync {
1550 BlockDriverAIOCB common;
1551 QEMUBH *bh;
1552 int ret;
1553 /* vector translation state */
1554 QEMUIOVector *qiov;
1555 uint8_t *bounce;
1556 int is_write;
1557} BlockDriverAIOCBSync;
1558
1559static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1560{
1561 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
6a7ad299 1562 qemu_bh_delete(acb->bh);
36afc451 1563 acb->bh = NULL;
c16b5a2c
CH
1564 qemu_aio_release(acb);
1565}
1566
1567static AIOPool bdrv_em_aio_pool = {
1568 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1569 .cancel = bdrv_aio_cancel_em,
1570};
1571
ce1a14dc 1572static void bdrv_aio_bh_cb(void *opaque)
83f64091 1573{
ce1a14dc 1574 BlockDriverAIOCBSync *acb = opaque;
f141eafe 1575
f141eafe
AL
1576 if (!acb->is_write)
1577 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
ceb42de8 1578 qemu_vfree(acb->bounce);
ce1a14dc 1579 acb->common.cb(acb->common.opaque, acb->ret);
6a7ad299 1580 qemu_bh_delete(acb->bh);
36afc451 1581 acb->bh = NULL;
ce1a14dc 1582 qemu_aio_release(acb);
83f64091 1583}
beac80cd 1584
f141eafe
AL
1585static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1586 int64_t sector_num,
1587 QEMUIOVector *qiov,
1588 int nb_sectors,
1589 BlockDriverCompletionFunc *cb,
1590 void *opaque,
1591 int is_write)
1592
83f64091 1593{
ce1a14dc 1594 BlockDriverAIOCBSync *acb;
ce1a14dc 1595
c16b5a2c 1596 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
f141eafe
AL
1597 acb->is_write = is_write;
1598 acb->qiov = qiov;
e268ca52 1599 acb->bounce = qemu_blockalign(bs, qiov->size);
f141eafe 1600
ce1a14dc
PB
1601 if (!acb->bh)
1602 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
f141eafe
AL
1603
1604 if (is_write) {
1605 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1606 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1607 } else {
1608 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1609 }
1610
ce1a14dc 1611 qemu_bh_schedule(acb->bh);
f141eafe 1612
ce1a14dc 1613 return &acb->common;
beac80cd
FB
1614}
1615
f141eafe
AL
1616static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1617 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 1618 BlockDriverCompletionFunc *cb, void *opaque)
beac80cd 1619{
f141eafe
AL
1620 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1621}
83f64091 1622
f141eafe
AL
1623static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1624 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1625 BlockDriverCompletionFunc *cb, void *opaque)
1626{
1627 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
beac80cd 1628}
beac80cd 1629
83f64091
FB
1630/**************************************************************/
1631/* sync block device emulation */
ea2384d3 1632
83f64091
FB
1633static void bdrv_rw_em_cb(void *opaque, int ret)
1634{
1635 *(int *)opaque = ret;
ea2384d3
FB
1636}
1637
83f64091
FB
1638#define NOT_DONE 0x7fffffff
1639
5fafdf24 1640static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
83f64091 1641 uint8_t *buf, int nb_sectors)
7a6cba61 1642{
ce1a14dc
PB
1643 int async_ret;
1644 BlockDriverAIOCB *acb;
f141eafe
AL
1645 struct iovec iov;
1646 QEMUIOVector qiov;
83f64091 1647
83f64091 1648 async_ret = NOT_DONE;
3f4cb3d3 1649 iov.iov_base = (void *)buf;
f141eafe
AL
1650 iov.iov_len = nb_sectors * 512;
1651 qemu_iovec_init_external(&qiov, &iov, 1);
1652 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1653 bdrv_rw_em_cb, &async_ret);
baf35cb9 1654 if (acb == NULL)
ce1a14dc 1655 return -1;
baf35cb9 1656
83f64091
FB
1657 while (async_ret == NOT_DONE) {
1658 qemu_aio_wait();
1659 }
baf35cb9 1660
83f64091 1661 return async_ret;
7a6cba61
PB
1662}
1663
83f64091
FB
1664static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1665 const uint8_t *buf, int nb_sectors)
1666{
ce1a14dc
PB
1667 int async_ret;
1668 BlockDriverAIOCB *acb;
f141eafe
AL
1669 struct iovec iov;
1670 QEMUIOVector qiov;
83f64091 1671
83f64091 1672 async_ret = NOT_DONE;
f141eafe
AL
1673 iov.iov_base = (void *)buf;
1674 iov.iov_len = nb_sectors * 512;
1675 qemu_iovec_init_external(&qiov, &iov, 1);
1676 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1677 bdrv_rw_em_cb, &async_ret);
baf35cb9 1678 if (acb == NULL)
ce1a14dc 1679 return -1;
83f64091
FB
1680 while (async_ret == NOT_DONE) {
1681 qemu_aio_wait();
1682 }
83f64091
FB
1683 return async_ret;
1684}
ea2384d3
FB
1685
1686void bdrv_init(void)
1687{
5efa9d5a 1688 module_call_init(MODULE_INIT_BLOCK);
ea2384d3 1689}
ce1a14dc 1690
c16b5a2c
CH
1691void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1692 BlockDriverCompletionFunc *cb, void *opaque)
ce1a14dc 1693{
ce1a14dc
PB
1694 BlockDriverAIOCB *acb;
1695
6bbff9a0
AL
1696 if (pool->free_aiocb) {
1697 acb = pool->free_aiocb;
1698 pool->free_aiocb = acb->next;
ce1a14dc 1699 } else {
6bbff9a0
AL
1700 acb = qemu_mallocz(pool->aiocb_size);
1701 acb->pool = pool;
ce1a14dc
PB
1702 }
1703 acb->bs = bs;
1704 acb->cb = cb;
1705 acb->opaque = opaque;
1706 return acb;
1707}
1708
1709void qemu_aio_release(void *p)
1710{
6bbff9a0
AL
1711 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1712 AIOPool *pool = acb->pool;
1713 acb->next = pool->free_aiocb;
1714 pool->free_aiocb = acb;
ce1a14dc 1715}
19cb3738
FB
1716
1717/**************************************************************/
1718/* removable device support */
1719
1720/**
1721 * Return TRUE if the media is present
1722 */
1723int bdrv_is_inserted(BlockDriverState *bs)
1724{
1725 BlockDriver *drv = bs->drv;
1726 int ret;
1727 if (!drv)
1728 return 0;
1729 if (!drv->bdrv_is_inserted)
1730 return 1;
1731 ret = drv->bdrv_is_inserted(bs);
1732 return ret;
1733}
1734
1735/**
1736 * Return TRUE if the media changed since the last call to this
5fafdf24 1737 * function. It is currently only used for floppy disks
19cb3738
FB
1738 */
1739int bdrv_media_changed(BlockDriverState *bs)
1740{
1741 BlockDriver *drv = bs->drv;
1742 int ret;
1743
1744 if (!drv || !drv->bdrv_media_changed)
1745 ret = -ENOTSUP;
1746 else
1747 ret = drv->bdrv_media_changed(bs);
1748 if (ret == -ENOTSUP)
1749 ret = bs->media_changed;
1750 bs->media_changed = 0;
1751 return ret;
1752}
1753
1754/**
1755 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1756 */
aea2a33c 1757int bdrv_eject(BlockDriverState *bs, int eject_flag)
19cb3738
FB
1758{
1759 BlockDriver *drv = bs->drv;
1760 int ret;
1761
aea2a33c
MM
1762 if (bs->locked) {
1763 return -EBUSY;
1764 }
1765
19cb3738
FB
1766 if (!drv || !drv->bdrv_eject) {
1767 ret = -ENOTSUP;
1768 } else {
1769 ret = drv->bdrv_eject(bs, eject_flag);
1770 }
1771 if (ret == -ENOTSUP) {
1772 if (eject_flag)
1773 bdrv_close(bs);
aea2a33c 1774 ret = 0;
19cb3738 1775 }
aea2a33c
MM
1776
1777 return ret;
19cb3738
FB
1778}
1779
1780int bdrv_is_locked(BlockDriverState *bs)
1781{
1782 return bs->locked;
1783}
1784
1785/**
1786 * Lock or unlock the media (if it is locked, the user won't be able
1787 * to eject it manually).
1788 */
1789void bdrv_set_locked(BlockDriverState *bs, int locked)
1790{
1791 BlockDriver *drv = bs->drv;
1792
1793 bs->locked = locked;
1794 if (drv && drv->bdrv_set_locked) {
1795 drv->bdrv_set_locked(bs, locked);
1796 }
1797}
985a03b0
TS
1798
1799/* needed for generic scsi interface */
1800
1801int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1802{
1803 BlockDriver *drv = bs->drv;
1804
1805 if (drv && drv->bdrv_ioctl)
1806 return drv->bdrv_ioctl(bs, req, buf);
1807 return -ENOTSUP;
1808}
7d780669 1809
221f715d
AL
1810BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1811 unsigned long int req, void *buf,
1812 BlockDriverCompletionFunc *cb, void *opaque)
7d780669 1813{
221f715d 1814 BlockDriver *drv = bs->drv;
7d780669 1815
221f715d
AL
1816 if (drv && drv->bdrv_aio_ioctl)
1817 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1818 return NULL;
7d780669 1819}
e268ca52
AL
1820
1821void *qemu_blockalign(BlockDriverState *bs, size_t size)
1822{
1823 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
1824}