cirrus_vga: remove pointless cast from void *
[qemu] / block.c
1 /*
2  * QEMU System Emulator block driver
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  *
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  */
24 #include "config-host.h"
25 #ifdef CONFIG_BSD
26 /* include native header before sys-queue.h */
27 #include <sys/queue.h>
28 #endif
29
30 #include "qemu-common.h"
31 #include "monitor.h"
32 #include "block_int.h"
33 #include "module.h"
34
35 #ifdef CONFIG_BSD
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/ioctl.h>
39 #ifndef __DragonFly__
40 #include <sys/disk.h>
41 #endif
42 #endif
43
44 #ifdef _WIN32
45 #include <windows.h>
46 #endif
47
48 #define SECTOR_BITS 9
49 #define SECTOR_SIZE (1 << SECTOR_BITS)
50
51 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
52         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
53         BlockDriverCompletionFunc *cb, void *opaque);
54 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
55         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
56         BlockDriverCompletionFunc *cb, void *opaque);
57 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
58                         uint8_t *buf, int nb_sectors);
59 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
60                          const uint8_t *buf, int nb_sectors);
61
62 BlockDriverState *bdrv_first;
63
64 static BlockDriver *first_drv;
65
66 int path_is_absolute(const char *path)
67 {
68     const char *p;
69 #ifdef _WIN32
70     /* specific case for names like: "\\.\d:" */
71     if (*path == '/' || *path == '\\')
72         return 1;
73 #endif
74     p = strchr(path, ':');
75     if (p)
76         p++;
77     else
78         p = path;
79 #ifdef _WIN32
80     return (*p == '/' || *p == '\\');
81 #else
82     return (*p == '/');
83 #endif
84 }
85
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. */
89 void path_combine(char *dest, int dest_size,
90                   const char *base_path,
91                   const char *filename)
92 {
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;
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
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);
127     }
128 }
129
130 void bdrv_register(BlockDriver *bdrv)
131 {
132     if (!bdrv->bdrv_aio_readv) {
133         /* add AIO emulation layer */
134         bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
135         bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
136     } else if (!bdrv->bdrv_read) {
137         /* add synchronous IO emulation layer */
138         bdrv->bdrv_read = bdrv_read_em;
139         bdrv->bdrv_write = bdrv_write_em;
140     }
141     bdrv->next = first_drv;
142     first_drv = bdrv;
143 }
144
145 /* create a new block device (by default it is empty) */
146 BlockDriverState *bdrv_new(const char *device_name)
147 {
148     BlockDriverState **pbs, *bs;
149
150     bs = qemu_mallocz(sizeof(BlockDriverState));
151     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
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     }
159     return bs;
160 }
161
162 BlockDriver *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
172 int bdrv_create(BlockDriver *drv, const char* filename,
173     QEMUOptionParameter *options)
174 {
175     if (!drv->bdrv_create)
176         return -ENOTSUP;
177
178     return drv->bdrv_create(filename, options);
179 }
180
181 #ifdef _WIN32
182 void get_tmp_filename(char *filename, int size)
183 {
184     char temp_dir[MAX_PATH];
185
186     GetTempPath(MAX_PATH, temp_dir);
187     GetTempFileName(temp_dir, "qem", 0, filename);
188 }
189 #else
190 void get_tmp_filename(char *filename, int size)
191 {
192     int fd;
193     const char *tmpdir;
194     /* XXX: race condition possible */
195     tmpdir = getenv("TMPDIR");
196     if (!tmpdir)
197         tmpdir = "/tmp";
198     snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
199     fd = mkstemp(filename);
200     close(fd);
201 }
202 #endif
203
204 #ifdef _WIN32
205 static 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 }
211
212 int is_windows_drive(const char *filename)
213 {
214     if (is_windows_drive_prefix(filename) &&
215         filename[2] == '\0')
216         return 1;
217     if (strstart(filename, "\\\\.\\", NULL) ||
218         strstart(filename, "//./", NULL))
219         return 1;
220     return 0;
221 }
222 #endif
223
224 static BlockDriver *find_protocol(const char *filename)
225 {
226     BlockDriver *drv1;
227     char protocol[128];
228     int len;
229     const char *p;
230
231 #ifdef _WIN32
232     if (is_windows_drive(filename) ||
233         is_windows_drive_prefix(filename))
234         return bdrv_find_format("raw");
235 #endif
236     p = strchr(filename, ':');
237     if (!p)
238         return bdrv_find_format("raw");
239     len = p - filename;
240     if (len > sizeof(protocol) - 1)
241         len = sizeof(protocol) - 1;
242     memcpy(protocol, filename, len);
243     protocol[len] = '\0';
244     for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
245         if (drv1->protocol_name &&
246             !strcmp(drv1->protocol_name, protocol))
247             return drv1;
248     }
249     return NULL;
250 }
251
252 /*
253  * Detect host devices. By convention, /dev/cdrom[N] is always
254  * recognized as a host CDROM.
255  */
256 static BlockDriver *find_hdev_driver(const char *filename)
257 {
258     int score_max = 0, score;
259     BlockDriver *drv = NULL, *d;
260
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         }
269     }
270
271     return drv;
272 }
273
274 static 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
281     drv = find_protocol(filename);
282     /* no need to test disk image formats for vvfat */
283     if (drv && strcmp(drv->format_name, "vvfat") == 0)
284         return drv;
285
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
295     score_max = 0;
296     for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
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             }
303         }
304     }
305     return drv;
306 }
307
308 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
309 {
310     BlockDriverState *bs;
311     int ret;
312
313     bs = bdrv_new("");
314     ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
315     if (ret < 0) {
316         bdrv_delete(bs);
317         return ret;
318     }
319     bs->growable = 1;
320     *pbs = bs;
321     return 0;
322 }
323
324 int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
325 {
326     return bdrv_open2(bs, filename, flags, NULL);
327 }
328
329 int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
330                BlockDriver *drv)
331 {
332     int ret, open_flags;
333     char tmp_filename[PATH_MAX];
334     char backing_filename[PATH_MAX];
335
336     bs->read_only = 0;
337     bs->is_temporary = 0;
338     bs->encrypted = 0;
339     bs->valid_key = 0;
340     /* buffer_alignment defaulted to 512, drivers can change this value */
341     bs->buffer_alignment = 512;
342
343     if (flags & BDRV_O_SNAPSHOT) {
344         BlockDriverState *bs1;
345         int64_t total_size;
346         int is_protocol = 0;
347         BlockDriver *bdrv_qcow2;
348         QEMUOptionParameter *options;
349
350         /* if snapshot, we create a temporary backing file and open it
351            instead of opening 'filename' directly */
352
353         /* if there is a backing file, use it */
354         bs1 = bdrv_new("");
355         ret = bdrv_open2(bs1, filename, 0, drv);
356         if (ret < 0) {
357             bdrv_delete(bs1);
358             return ret;
359         }
360         total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
361
362         if (bs1->drv && bs1->drv->protocol_name)
363             is_protocol = 1;
364
365         bdrv_delete(bs1);
366
367         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
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
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);
387         if (ret < 0) {
388             return ret;
389         }
390
391         filename = tmp_filename;
392         drv = bdrv_qcow2;
393         bs->is_temporary = 1;
394     }
395
396     pstrcpy(bs->filename, sizeof(bs->filename), filename);
397     if (flags & BDRV_O_FILE) {
398         drv = find_protocol(filename);
399     } else if (!drv) {
400         drv = find_hdev_driver(filename);
401         if (!drv) {
402             drv = find_image_format(filename);
403         }
404     }
405     if (!drv) {
406         ret = -ENOENT;
407         goto unlink_and_fail;
408     }
409     bs->drv = drv;
410     bs->opaque = qemu_mallocz(drv->instance_size);
411     /* Note: for compatibility, we open disk image files as RDWR, and
412        RDONLY as fallback */
413     if (!(flags & BDRV_O_FILE))
414         open_flags = BDRV_O_RDWR |
415                 (flags & (BDRV_O_CACHE_MASK|BDRV_O_NATIVE_AIO));
416     else
417         open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
418     ret = drv->bdrv_open(bs, filename, open_flags);
419     if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
420         ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
421         bs->read_only = 1;
422     }
423     if (ret < 0) {
424         qemu_free(bs->opaque);
425         bs->opaque = NULL;
426         bs->drv = NULL;
427     unlink_and_fail:
428         if (bs->is_temporary)
429             unlink(filename);
430         return ret;
431     }
432     if (drv->bdrv_getlength) {
433         bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
434     }
435 #ifndef _WIN32
436     if (bs->is_temporary) {
437         unlink(filename);
438     }
439 #endif
440     if (bs->backing_file[0] != '\0') {
441         /* if there is a backing file, use it */
442         BlockDriver *back_drv = NULL;
443         bs->backing_hd = bdrv_new("");
444         path_combine(backing_filename, sizeof(backing_filename),
445                      filename, bs->backing_file);
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);
450         if (ret < 0) {
451             bdrv_close(bs);
452             return ret;
453         }
454     }
455
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     }
462     return 0;
463 }
464
465 void bdrv_close(BlockDriverState *bs)
466 {
467     if (bs->drv) {
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         }
476 #endif
477         bs->opaque = NULL;
478         bs->drv = NULL;
479
480         /* call the change callback */
481         bs->media_changed = 1;
482         if (bs->change_cb)
483             bs->change_cb(bs->change_opaque);
484     }
485 }
486
487 void bdrv_delete(BlockDriverState *bs)
488 {
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
497     bdrv_close(bs);
498     qemu_free(bs);
499 }
500
501 /*
502  * Run consistency checks on an image
503  *
504  * Returns the number of errors or -errno when an internal error occurs
505  */
506 int 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
515 /* commit COW file into the raw image */
516 int bdrv_commit(BlockDriverState *bs)
517 {
518     BlockDriver *drv = bs->drv;
519     int64_t i, total_sectors;
520     int n, j;
521     unsigned char sector[512];
522
523     if (!drv)
524         return -ENOMEDIUM;
525
526     if (bs->read_only) {
527         return -EACCES;
528     }
529
530     if (!bs->backing_hd) {
531         return -ENOTSUP;
532     }
533
534     total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
535     for (i = 0; i < total_sectors;) {
536         if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
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++;
546             }
547         } else {
548             i += n;
549         }
550     }
551
552     if (drv->bdrv_make_empty)
553         return drv->bdrv_make_empty(bs);
554
555     return 0;
556 }
557
558 static 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
571     if (offset < 0)
572         return -EIO;
573
574     if ((offset > len) || (len - offset < size))
575         return -EIO;
576
577     return 0;
578 }
579
580 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
581                               int nb_sectors)
582 {
583     return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
584 }
585
586 /* return < 0 if error. See bdrv_write() for the return codes */
587 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
588               uint8_t *buf, int nb_sectors)
589 {
590     BlockDriver *drv = bs->drv;
591
592     if (!drv)
593         return -ENOMEDIUM;
594     if (bdrv_check_request(bs, sector_num, nb_sectors))
595         return -EIO;
596
597     return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
598 }
599
600 /* Return < 0 if error. Important errors are:
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 */
606 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
607                const uint8_t *buf, int nb_sectors)
608 {
609     BlockDriver *drv = bs->drv;
610     if (!bs->drv)
611         return -ENOMEDIUM;
612     if (bs->read_only)
613         return -EACCES;
614     if (bdrv_check_request(bs, sector_num, nb_sectors))
615         return -EIO;
616
617     return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
618 }
619
620 int bdrv_pread(BlockDriverState *bs, int64_t offset,
621                void *buf, int count1)
622 {
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
664 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
665                 const void *buf, int count1)
666 {
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 }
711
712 /**
713  * Truncate file to 'offset' bytes (needed only for file protocols)
714  */
715 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
716 {
717     BlockDriver *drv = bs->drv;
718     if (!drv)
719         return -ENOMEDIUM;
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  */
728 int64_t bdrv_getlength(BlockDriverState *bs)
729 {
730     BlockDriver *drv = bs->drv;
731     if (!drv)
732         return -ENOMEDIUM;
733     if (!drv->bdrv_getlength) {
734         /* legacy mode */
735         return bs->total_sectors * SECTOR_SIZE;
736     }
737     return drv->bdrv_getlength(bs);
738 }
739
740 /* return 0 as number of sectors if no device present or error */
741 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
742 {
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;
750 }
751
752 struct 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 */
766 static 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;
773     uint64_t nb_sectors;
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
809 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
810 {
811     int translation, lba_detected = 0;
812     int cylinders, heads, secs;
813     uint64_t nb_sectors;
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
868 void bdrv_set_geometry_hint(BlockDriverState *bs,
869                             int cyls, int heads, int secs)
870 {
871     bs->cyls = cyls;
872     bs->heads = heads;
873     bs->secs = secs;
874 }
875
876 void 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
883 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
884 {
885     bs->translation = translation;
886 }
887
888 void bdrv_get_geometry_hint(BlockDriverState *bs,
889                             int *pcyls, int *pheads, int *psecs)
890 {
891     *pcyls = bs->cyls;
892     *pheads = bs->heads;
893     *psecs = bs->secs;
894 }
895
896 int bdrv_get_type_hint(BlockDriverState *bs)
897 {
898     return bs->type;
899 }
900
901 int bdrv_get_translation_hint(BlockDriverState *bs)
902 {
903     return bs->translation;
904 }
905
906 int bdrv_is_removable(BlockDriverState *bs)
907 {
908     return bs->removable;
909 }
910
911 int bdrv_is_read_only(BlockDriverState *bs)
912 {
913     return bs->read_only;
914 }
915
916 int bdrv_is_sg(BlockDriverState *bs)
917 {
918     return bs->sg;
919 }
920
921 /* XXX: no longer used */
922 void bdrv_set_change_cb(BlockDriverState *bs,
923                         void (*change_cb)(void *opaque), void *opaque)
924 {
925     bs->change_cb = change_cb;
926     bs->change_opaque = opaque;
927 }
928
929 int bdrv_is_encrypted(BlockDriverState *bs)
930 {
931     if (bs->backing_hd && bs->backing_hd->encrypted)
932         return 1;
933     return bs->encrypted;
934 }
935
936 int 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
945 int 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;
957     ret = bs->drv->bdrv_set_key(bs, key);
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     }
967     return ret;
968 }
969
970 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
971 {
972     if (!bs->drv) {
973         buf[0] = '\0';
974     } else {
975         pstrcpy(buf, buf_size, bs->drv->format_name);
976     }
977 }
978
979 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
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
989 BlockDriverState *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
1000 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1001 {
1002     BlockDriverState *bs;
1003
1004     for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1005         it(opaque, bs);
1006     }
1007 }
1008
1009 const char *bdrv_get_device_name(BlockDriverState *bs)
1010 {
1011     return bs->device_name;
1012 }
1013
1014 void bdrv_flush(BlockDriverState *bs)
1015 {
1016     if (!bs->drv)
1017         return;
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
1024 void 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
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  */
1045 int 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
1061 void bdrv_info(Monitor *mon)
1062 {
1063     BlockDriverState *bs;
1064
1065     for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1066         monitor_printf(mon, "%s:", bs->device_name);
1067         monitor_printf(mon, " type=");
1068         switch(bs->type) {
1069         case BDRV_TYPE_HD:
1070             monitor_printf(mon, "hd");
1071             break;
1072         case BDRV_TYPE_CDROM:
1073             monitor_printf(mon, "cdrom");
1074             break;
1075         case BDRV_TYPE_FLOPPY:
1076             monitor_printf(mon, "floppy");
1077             break;
1078         }
1079         monitor_printf(mon, " removable=%d", bs->removable);
1080         if (bs->removable) {
1081             monitor_printf(mon, " locked=%d", bs->locked);
1082         }
1083         if (bs->drv) {
1084             monitor_printf(mon, " file=");
1085             monitor_print_filename(mon, bs->filename);
1086             if (bs->backing_file[0] != '\0') {
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));
1093         } else {
1094             monitor_printf(mon, " [not inserted]");
1095         }
1096         monitor_printf(mon, "\n");
1097     }
1098 }
1099
1100 /* The "info blockstats" command. */
1101 void bdrv_info_stats(Monitor *mon)
1102 {
1103     BlockDriverState *bs;
1104
1105     for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1106         monitor_printf(mon, "%s:"
1107                        " rd_bytes=%" PRIu64
1108                        " wr_bytes=%" PRIu64
1109                        " rd_operations=%" PRIu64
1110                        " wr_operations=%" PRIu64
1111                        "\n",
1112                        bs->device_name,
1113                        bs->rd_bytes, bs->wr_bytes,
1114                        bs->rd_ops, bs->wr_ops);
1115     }
1116 }
1117
1118 const 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
1128 void bdrv_get_backing_filename(BlockDriverState *bs,
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
1138 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1139                           const uint8_t *buf, int nb_sectors)
1140 {
1141     BlockDriver *drv = bs->drv;
1142     if (!drv)
1143         return -ENOMEDIUM;
1144     if (!drv->bdrv_write_compressed)
1145         return -ENOTSUP;
1146     if (bdrv_check_request(bs, sector_num, nb_sectors))
1147         return -EIO;
1148     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1149 }
1150
1151 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1152 {
1153     BlockDriver *drv = bs->drv;
1154     if (!drv)
1155         return -ENOMEDIUM;
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
1162 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1163                       int64_t pos, int size)
1164 {
1165     BlockDriver *drv = bs->drv;
1166     if (!drv)
1167         return -ENOMEDIUM;
1168     if (!drv->bdrv_save_vmstate)
1169         return -ENOTSUP;
1170     return drv->bdrv_save_vmstate(bs, buf, pos, size);
1171 }
1172
1173 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1174                       int64_t pos, int size)
1175 {
1176     BlockDriver *drv = bs->drv;
1177     if (!drv)
1178         return -ENOMEDIUM;
1179     if (!drv->bdrv_load_vmstate)
1180         return -ENOTSUP;
1181     return drv->bdrv_load_vmstate(bs, buf, pos, size);
1182 }
1183
1184 /**************************************************************/
1185 /* handling of snapshots */
1186
1187 int bdrv_snapshot_create(BlockDriverState *bs,
1188                          QEMUSnapshotInfo *sn_info)
1189 {
1190     BlockDriver *drv = bs->drv;
1191     if (!drv)
1192         return -ENOMEDIUM;
1193     if (!drv->bdrv_snapshot_create)
1194         return -ENOTSUP;
1195     return drv->bdrv_snapshot_create(bs, sn_info);
1196 }
1197
1198 int bdrv_snapshot_goto(BlockDriverState *bs,
1199                        const char *snapshot_id)
1200 {
1201     BlockDriver *drv = bs->drv;
1202     if (!drv)
1203         return -ENOMEDIUM;
1204     if (!drv->bdrv_snapshot_goto)
1205         return -ENOTSUP;
1206     return drv->bdrv_snapshot_goto(bs, snapshot_id);
1207 }
1208
1209 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1210 {
1211     BlockDriver *drv = bs->drv;
1212     if (!drv)
1213         return -ENOMEDIUM;
1214     if (!drv->bdrv_snapshot_delete)
1215         return -ENOTSUP;
1216     return drv->bdrv_snapshot_delete(bs, snapshot_id);
1217 }
1218
1219 int bdrv_snapshot_list(BlockDriverState *bs,
1220                        QEMUSnapshotInfo **psn_info)
1221 {
1222     BlockDriver *drv = bs->drv;
1223     if (!drv)
1224         return -ENOMEDIUM;
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
1232 char *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)) {
1244                 snprintf(buf, buf_size, "%0.1f%c",
1245                          (double)size / base,
1246                          suffixes[i]);
1247                 break;
1248             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1249                 snprintf(buf, buf_size, "%" PRId64 "%c",
1250                          ((size + (base >> 1)) / base),
1251                          suffixes[i]);
1252                 break;
1253             }
1254             base = base * 1024;
1255         }
1256     }
1257     return buf;
1258 }
1259
1260 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1261 {
1262     char buf1[128], date_buf[128], clock_buf[128];
1263 #ifdef _WIN32
1264     struct tm *ptm;
1265 #else
1266     struct tm tm;
1267 #endif
1268     time_t ti;
1269     int64_t secs;
1270
1271     if (!sn) {
1272         snprintf(buf, buf_size,
1273                  "%-10s%-20s%7s%20s%15s",
1274                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1275     } else {
1276         ti = sn->date_sec;
1277 #ifdef _WIN32
1278         ptm = localtime(&ti);
1279         strftime(date_buf, sizeof(date_buf),
1280                  "%Y-%m-%d %H:%M:%S", ptm);
1281 #else
1282         localtime_r(&ti, &tm);
1283         strftime(date_buf, sizeof(date_buf),
1284                  "%Y-%m-%d %H:%M:%S", &tm);
1285 #endif
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),
1291                  (int)(secs % 60),
1292                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
1293         snprintf(buf, buf_size,
1294                  "%-10s%-20s%7s%20s%15s",
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
1303
1304 /**************************************************************/
1305 /* async I/Os */
1306
1307 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1308                                  QEMUIOVector *qiov, int nb_sectors,
1309                                  BlockDriverCompletionFunc *cb, void *opaque)
1310 {
1311     BlockDriver *drv = bs->drv;
1312     BlockDriverAIOCB *ret;
1313
1314     if (!drv)
1315         return NULL;
1316     if (bdrv_check_request(bs, sector_num, nb_sectors))
1317         return NULL;
1318
1319     ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1320                               cb, opaque);
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;
1329 }
1330
1331 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1332                                   QEMUIOVector *qiov, int nb_sectors,
1333                                   BlockDriverCompletionFunc *cb, void *opaque)
1334 {
1335     BlockDriver *drv = bs->drv;
1336     BlockDriverAIOCB *ret;
1337
1338     if (!drv)
1339         return NULL;
1340     if (bs->read_only)
1341         return NULL;
1342     if (bdrv_check_request(bs, sector_num, nb_sectors))
1343         return NULL;
1344
1345     ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1346                                cb, opaque);
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;
1355 }
1356
1357 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1358 {
1359     acb->pool->cancel(acb);
1360 }
1361
1362
1363 /**************************************************************/
1364 /* async block device emulation */
1365
1366 typedef struct BlockDriverAIOCBSync {
1367     BlockDriverAIOCB common;
1368     QEMUBH *bh;
1369     int ret;
1370     /* vector translation state */
1371     QEMUIOVector *qiov;
1372     uint8_t *bounce;
1373     int is_write;
1374 } BlockDriverAIOCBSync;
1375
1376 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1377 {
1378     BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1379     qemu_bh_delete(acb->bh);
1380     acb->bh = NULL;
1381     qemu_aio_release(acb);
1382 }
1383
1384 static AIOPool bdrv_em_aio_pool = {
1385     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
1386     .cancel             = bdrv_aio_cancel_em,
1387 };
1388
1389 static void bdrv_aio_bh_cb(void *opaque)
1390 {
1391     BlockDriverAIOCBSync *acb = opaque;
1392
1393     if (!acb->is_write)
1394         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1395     qemu_vfree(acb->bounce);
1396     acb->common.cb(acb->common.opaque, acb->ret);
1397     qemu_bh_delete(acb->bh);
1398     acb->bh = NULL;
1399     qemu_aio_release(acb);
1400 }
1401
1402 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1403                                             int64_t sector_num,
1404                                             QEMUIOVector *qiov,
1405                                             int nb_sectors,
1406                                             BlockDriverCompletionFunc *cb,
1407                                             void *opaque,
1408                                             int is_write)
1409
1410 {
1411     BlockDriverAIOCBSync *acb;
1412
1413     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1414     acb->is_write = is_write;
1415     acb->qiov = qiov;
1416     acb->bounce = qemu_blockalign(bs, qiov->size);
1417
1418     if (!acb->bh)
1419         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1420
1421     if (is_write) {
1422         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1423         acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1424     } else {
1425         acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1426     }
1427
1428     qemu_bh_schedule(acb->bh);
1429
1430     return &acb->common;
1431 }
1432
1433 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1434         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1435         BlockDriverCompletionFunc *cb, void *opaque)
1436 {
1437     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1438 }
1439
1440 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1441         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1442         BlockDriverCompletionFunc *cb, void *opaque)
1443 {
1444     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1445 }
1446
1447 /**************************************************************/
1448 /* sync block device emulation */
1449
1450 static void bdrv_rw_em_cb(void *opaque, int ret)
1451 {
1452     *(int *)opaque = ret;
1453 }
1454
1455 #define NOT_DONE 0x7fffffff
1456
1457 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
1458                         uint8_t *buf, int nb_sectors)
1459 {
1460     int async_ret;
1461     BlockDriverAIOCB *acb;
1462     struct iovec iov;
1463     QEMUIOVector qiov;
1464
1465     async_ret = NOT_DONE;
1466     iov.iov_base = (void *)buf;
1467     iov.iov_len = nb_sectors * 512;
1468     qemu_iovec_init_external(&qiov, &iov, 1);
1469     acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1470         bdrv_rw_em_cb, &async_ret);
1471     if (acb == NULL)
1472         return -1;
1473
1474     while (async_ret == NOT_DONE) {
1475         qemu_aio_wait();
1476     }
1477
1478     return async_ret;
1479 }
1480
1481 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1482                          const uint8_t *buf, int nb_sectors)
1483 {
1484     int async_ret;
1485     BlockDriverAIOCB *acb;
1486     struct iovec iov;
1487     QEMUIOVector qiov;
1488
1489     async_ret = NOT_DONE;
1490     iov.iov_base = (void *)buf;
1491     iov.iov_len = nb_sectors * 512;
1492     qemu_iovec_init_external(&qiov, &iov, 1);
1493     acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1494         bdrv_rw_em_cb, &async_ret);
1495     if (acb == NULL)
1496         return -1;
1497     while (async_ret == NOT_DONE) {
1498         qemu_aio_wait();
1499     }
1500     return async_ret;
1501 }
1502
1503 void bdrv_init(void)
1504 {
1505     module_call_init(MODULE_INIT_BLOCK);
1506 }
1507
1508 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1509                    BlockDriverCompletionFunc *cb, void *opaque)
1510 {
1511     BlockDriverAIOCB *acb;
1512
1513     if (pool->free_aiocb) {
1514         acb = pool->free_aiocb;
1515         pool->free_aiocb = acb->next;
1516     } else {
1517         acb = qemu_mallocz(pool->aiocb_size);
1518         acb->pool = pool;
1519     }
1520     acb->bs = bs;
1521     acb->cb = cb;
1522     acb->opaque = opaque;
1523     return acb;
1524 }
1525
1526 void qemu_aio_release(void *p)
1527 {
1528     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1529     AIOPool *pool = acb->pool;
1530     acb->next = pool->free_aiocb;
1531     pool->free_aiocb = acb;
1532 }
1533
1534 /**************************************************************/
1535 /* removable device support */
1536
1537 /**
1538  * Return TRUE if the media is present
1539  */
1540 int bdrv_is_inserted(BlockDriverState *bs)
1541 {
1542     BlockDriver *drv = bs->drv;
1543     int ret;
1544     if (!drv)
1545         return 0;
1546     if (!drv->bdrv_is_inserted)
1547         return 1;
1548     ret = drv->bdrv_is_inserted(bs);
1549     return ret;
1550 }
1551
1552 /**
1553  * Return TRUE if the media changed since the last call to this
1554  * function. It is currently only used for floppy disks
1555  */
1556 int bdrv_media_changed(BlockDriverState *bs)
1557 {
1558     BlockDriver *drv = bs->drv;
1559     int ret;
1560
1561     if (!drv || !drv->bdrv_media_changed)
1562         ret = -ENOTSUP;
1563     else
1564         ret = drv->bdrv_media_changed(bs);
1565     if (ret == -ENOTSUP)
1566         ret = bs->media_changed;
1567     bs->media_changed = 0;
1568     return ret;
1569 }
1570
1571 /**
1572  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1573  */
1574 int bdrv_eject(BlockDriverState *bs, int eject_flag)
1575 {
1576     BlockDriver *drv = bs->drv;
1577     int ret;
1578
1579     if (bs->locked) {
1580         return -EBUSY;
1581     }
1582
1583     if (!drv || !drv->bdrv_eject) {
1584         ret = -ENOTSUP;
1585     } else {
1586         ret = drv->bdrv_eject(bs, eject_flag);
1587     }
1588     if (ret == -ENOTSUP) {
1589         if (eject_flag)
1590             bdrv_close(bs);
1591         ret = 0;
1592     }
1593
1594     return ret;
1595 }
1596
1597 int bdrv_is_locked(BlockDriverState *bs)
1598 {
1599     return bs->locked;
1600 }
1601
1602 /**
1603  * Lock or unlock the media (if it is locked, the user won't be able
1604  * to eject it manually).
1605  */
1606 void bdrv_set_locked(BlockDriverState *bs, int locked)
1607 {
1608     BlockDriver *drv = bs->drv;
1609
1610     bs->locked = locked;
1611     if (drv && drv->bdrv_set_locked) {
1612         drv->bdrv_set_locked(bs, locked);
1613     }
1614 }
1615
1616 /* needed for generic scsi interface */
1617
1618 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1619 {
1620     BlockDriver *drv = bs->drv;
1621
1622     if (drv && drv->bdrv_ioctl)
1623         return drv->bdrv_ioctl(bs, req, buf);
1624     return -ENOTSUP;
1625 }
1626
1627 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1628         unsigned long int req, void *buf,
1629         BlockDriverCompletionFunc *cb, void *opaque)
1630 {
1631     BlockDriver *drv = bs->drv;
1632
1633     if (drv && drv->bdrv_aio_ioctl)
1634         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1635     return NULL;
1636 }
1637
1638 void *qemu_blockalign(BlockDriverState *bs, size_t size)
1639 {
1640     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
1641 }