win32 compilation fixes
[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 "vl.h"
25 #include "block_int.h"
26
27 #ifdef _BSD
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/ioctl.h>
31 #include <sys/queue.h>
32 #include <sys/disk.h>
33 #endif
34
35 #define SECTOR_BITS 9
36 #define SECTOR_SIZE (1 << SECTOR_BITS)
37
38 typedef struct BlockDriverAIOCBSync {
39     BlockDriverAIOCB common;
40     QEMUBH *bh;
41     int ret;
42 } BlockDriverAIOCBSync;
43
44 static BlockDriverAIOCB *bdrv_aio_read_em(BlockDriverState *bs,
45         int64_t sector_num, uint8_t *buf, int nb_sectors,
46         BlockDriverCompletionFunc *cb, void *opaque);
47 static BlockDriverAIOCB *bdrv_aio_write_em(BlockDriverState *bs,
48         int64_t sector_num, const uint8_t *buf, int nb_sectors,
49         BlockDriverCompletionFunc *cb, void *opaque);
50 static void bdrv_aio_cancel_em(BlockDriverAIOCB *acb);
51 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num, 
52                         uint8_t *buf, int nb_sectors);
53 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
54                          const uint8_t *buf, int nb_sectors);
55
56 static BlockDriverState *bdrv_first;
57 static BlockDriver *first_drv;
58
59 #ifdef _WIN32
60 #define PATH_SEP '\\'
61 #else
62 #define PATH_SEP '/'
63 #endif
64
65 int path_is_absolute(const char *path)
66 {
67     const char *p;
68     p = strchr(path, ':');
69     if (p)
70         p++;
71     else
72         p = path;
73     return (*p == PATH_SEP);
74 }
75
76 /* if filename is absolute, just copy it to dest. Otherwise, build a
77    path to it by considering it is relative to base_path. URL are
78    supported. */
79 void path_combine(char *dest, int dest_size,
80                   const char *base_path,
81                   const char *filename)
82 {
83     const char *p, *p1;
84     int len;
85
86     if (dest_size <= 0)
87         return;
88     if (path_is_absolute(filename)) {
89         pstrcpy(dest, dest_size, filename);
90     } else {
91         p = strchr(base_path, ':');
92         if (p)
93             p++;
94         else
95             p = base_path;
96         p1 = strrchr(base_path, PATH_SEP);
97         if (p1)
98             p1++;
99         else
100             p1 = base_path;
101         if (p1 > p)
102             p = p1;
103         len = p - base_path;
104         if (len > dest_size - 1)
105             len = dest_size - 1;
106         memcpy(dest, base_path, len);
107         dest[len] = '\0';
108         pstrcat(dest, dest_size, filename);
109     }
110 }
111
112
113 void bdrv_register(BlockDriver *bdrv)
114 {
115     if (!bdrv->bdrv_aio_read) {
116         /* add AIO emulation layer */
117         bdrv->bdrv_aio_read = bdrv_aio_read_em;
118         bdrv->bdrv_aio_write = bdrv_aio_write_em;
119         bdrv->bdrv_aio_cancel = bdrv_aio_cancel_em;
120         bdrv->aiocb_size = sizeof(BlockDriverAIOCBSync);
121     } else if (!bdrv->bdrv_read && !bdrv->bdrv_pread) {
122         /* add synchronous IO emulation layer */
123         bdrv->bdrv_read = bdrv_read_em;
124         bdrv->bdrv_write = bdrv_write_em;
125     }
126     bdrv->next = first_drv;
127     first_drv = bdrv;
128 }
129
130 /* create a new block device (by default it is empty) */
131 BlockDriverState *bdrv_new(const char *device_name)
132 {
133     BlockDriverState **pbs, *bs;
134
135     bs = qemu_mallocz(sizeof(BlockDriverState));
136     if(!bs)
137         return NULL;
138     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
139     if (device_name[0] != '\0') {
140         /* insert at the end */
141         pbs = &bdrv_first;
142         while (*pbs != NULL)
143             pbs = &(*pbs)->next;
144         *pbs = bs;
145     }
146     return bs;
147 }
148
149 BlockDriver *bdrv_find_format(const char *format_name)
150 {
151     BlockDriver *drv1;
152     for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
153         if (!strcmp(drv1->format_name, format_name))
154             return drv1;
155     }
156     return NULL;
157 }
158
159 int bdrv_create(BlockDriver *drv, 
160                 const char *filename, int64_t size_in_sectors,
161                 const char *backing_file, int flags)
162 {
163     if (!drv->bdrv_create)
164         return -ENOTSUP;
165     return drv->bdrv_create(filename, size_in_sectors, backing_file, flags);
166 }
167
168 #ifdef _WIN32
169 void get_tmp_filename(char *filename, int size)
170 {
171     tmpnam(filename);
172 }
173 #else
174 void get_tmp_filename(char *filename, int size)
175 {
176     int fd;
177     /* XXX: race condition possible */
178     pstrcpy(filename, size, "/tmp/vl.XXXXXX");
179     fd = mkstemp(filename);
180     close(fd);
181 }
182 #endif
183
184 #ifdef _WIN32
185 static int is_windows_drive_prefix(const char *filename)
186 {
187     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
188              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
189             filename[1] == ':');
190 }
191     
192 static int is_windows_drive(const char *filename)
193 {
194     if (is_windows_drive_prefix(filename) && 
195         filename[2] == '\0')
196         return 1;
197     if (strstart(filename, "\\\\.\\", NULL) ||
198         strstart(filename, "//./", NULL))
199         return 1;
200     return 0;
201 }
202 #endif
203
204 static BlockDriver *find_protocol(const char *filename)
205 {
206     BlockDriver *drv1;
207     char protocol[128];
208     int len;
209     const char *p;
210
211 #ifdef _WIN32
212     if (is_windows_drive(filename) ||
213         is_windows_drive_prefix(filename))
214         return &bdrv_raw;
215 #endif
216     p = strchr(filename, ':');
217     if (!p)
218         return &bdrv_raw;
219     len = p - filename;
220     if (len > sizeof(protocol) - 1)
221         len = sizeof(protocol) - 1;
222     memcpy(protocol, filename, len);
223     protocol[len] = '\0';
224     for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
225         if (drv1->protocol_name && 
226             !strcmp(drv1->protocol_name, protocol))
227             return drv1;
228     }
229     return NULL;
230 }
231
232 /* XXX: force raw format if block or character device ? It would
233    simplify the BSD case */
234 static BlockDriver *find_image_format(const char *filename)
235 {
236     int ret, score, score_max;
237     BlockDriver *drv1, *drv;
238     uint8_t buf[2048];
239     BlockDriverState *bs;
240     
241     /* detect host devices. By convention, /dev/cdrom[N] is always
242        recognized as a host CDROM */
243     if (strstart(filename, "/dev/cdrom", NULL))
244         return &bdrv_host_device;
245 #ifdef _WIN32
246     if (is_windows_drive(filename))
247         return &bdrv_host_device;
248 #else
249     {
250         struct stat st;
251         if (stat(filename, &st) >= 0 && 
252             (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
253             return &bdrv_host_device;
254         }
255     }
256 #endif
257     
258     drv = find_protocol(filename);
259     /* no need to test disk image formats for vvfat */
260     if (drv == &bdrv_vvfat)
261         return drv;
262
263     ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
264     if (ret < 0)
265         return NULL;
266     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
267     bdrv_delete(bs);
268     if (ret < 0) {
269         return NULL;
270     }
271
272     score_max = 0;
273     for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
274         if (drv1->bdrv_probe) {
275             score = drv1->bdrv_probe(buf, ret, filename);
276             if (score > score_max) {
277                 score_max = score;
278                 drv = drv1;
279             }
280         }
281     }
282     return drv;
283 }
284
285 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
286 {
287     BlockDriverState *bs;
288     int ret;
289
290     bs = bdrv_new("");
291     if (!bs)
292         return -ENOMEM;
293     ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
294     if (ret < 0) {
295         bdrv_delete(bs);
296         return ret;
297     }
298     *pbs = bs;
299     return 0;
300 }
301
302 int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
303 {
304     return bdrv_open2(bs, filename, flags, NULL);
305 }
306
307 int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
308                BlockDriver *drv)
309 {
310     int ret, open_flags;
311     char tmp_filename[1024];
312     char backing_filename[1024];
313     
314     bs->read_only = 0;
315     bs->is_temporary = 0;
316     bs->encrypted = 0;
317
318     if (flags & BDRV_O_SNAPSHOT) {
319         BlockDriverState *bs1;
320         int64_t total_size;
321         
322         /* if snapshot, we create a temporary backing file and open it
323            instead of opening 'filename' directly */
324
325         /* if there is a backing file, use it */
326         bs1 = bdrv_new("");
327         if (!bs1) {
328             return -ENOMEM;
329         }
330         if (bdrv_open(bs1, filename, 0) < 0) {
331             bdrv_delete(bs1);
332             return -1;
333         }
334         total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
335         bdrv_delete(bs1);
336         
337         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
338         if (bdrv_create(&bdrv_qcow2, tmp_filename, 
339                         total_size, filename, 0) < 0) {
340             return -1;
341         }
342         filename = tmp_filename;
343         bs->is_temporary = 1;
344     }
345
346     pstrcpy(bs->filename, sizeof(bs->filename), filename);
347     if (flags & BDRV_O_FILE) {
348         drv = find_protocol(filename);
349         if (!drv)
350             return -ENOENT;
351     } else {
352         if (!drv) {
353             drv = find_image_format(filename);
354             if (!drv)
355                 return -1;
356         }
357     }
358     bs->drv = drv;
359     bs->opaque = qemu_mallocz(drv->instance_size);
360     if (bs->opaque == NULL && drv->instance_size > 0)
361         return -1;
362     /* Note: for compatibility, we open disk image files as RDWR, and
363        RDONLY as fallback */
364     if (!(flags & BDRV_O_FILE))
365         open_flags = BDRV_O_RDWR;
366     else
367         open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
368     ret = drv->bdrv_open(bs, filename, open_flags);
369     if (ret == -EACCES && !(flags & BDRV_O_FILE)) {
370         ret = drv->bdrv_open(bs, filename, BDRV_O_RDONLY);
371         bs->read_only = 1;
372     }
373     if (ret < 0) {
374         qemu_free(bs->opaque);
375         bs->opaque = NULL;
376         bs->drv = NULL;
377         return ret;
378     }
379     if (drv->bdrv_getlength) {
380         bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
381     }
382 #ifndef _WIN32
383     if (bs->is_temporary) {
384         unlink(filename);
385     }
386 #endif
387     if (bs->backing_file[0] != '\0') {
388         /* if there is a backing file, use it */
389         bs->backing_hd = bdrv_new("");
390         if (!bs->backing_hd) {
391         fail:
392             bdrv_close(bs);
393             return -ENOMEM;
394         }
395         path_combine(backing_filename, sizeof(backing_filename),
396                      filename, bs->backing_file);
397         if (bdrv_open(bs->backing_hd, backing_filename, 0) < 0)
398             goto fail;
399     }
400
401     /* call the change callback */
402     bs->media_changed = 1;
403     if (bs->change_cb)
404         bs->change_cb(bs->change_opaque);
405
406     return 0;
407 }
408
409 void bdrv_close(BlockDriverState *bs)
410 {
411     if (bs->drv) {
412         if (bs->backing_hd)
413             bdrv_delete(bs->backing_hd);
414         bs->drv->bdrv_close(bs);
415         qemu_free(bs->opaque);
416 #ifdef _WIN32
417         if (bs->is_temporary) {
418             unlink(bs->filename);
419         }
420 #endif
421         bs->opaque = NULL;
422         bs->drv = NULL;
423
424         /* call the change callback */
425         bs->media_changed = 1;
426         if (bs->change_cb)
427             bs->change_cb(bs->change_opaque);
428     }
429 }
430
431 void bdrv_delete(BlockDriverState *bs)
432 {
433     /* XXX: remove the driver list */
434     bdrv_close(bs);
435     qemu_free(bs);
436 }
437
438 /* commit COW file into the raw image */
439 int bdrv_commit(BlockDriverState *bs)
440 {
441     BlockDriver *drv = bs->drv;
442     int64_t i, total_sectors;
443     int n, j;
444     unsigned char sector[512];
445
446     if (!drv)
447         return -ENOMEDIUM;
448
449     if (bs->read_only) {
450         return -EACCES;
451     }
452
453     if (!bs->backing_hd) {
454         return -ENOTSUP;
455     }
456
457     total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
458     for (i = 0; i < total_sectors;) {
459         if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
460             for(j = 0; j < n; j++) {
461                 if (bdrv_read(bs, i, sector, 1) != 0) {
462                     return -EIO;
463                 }
464
465                 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
466                     return -EIO;
467                 }
468                 i++;
469             }
470         } else {
471             i += n;
472         }
473     }
474
475     if (drv->bdrv_make_empty)
476         return drv->bdrv_make_empty(bs);
477
478     return 0;
479 }
480
481 /* return < 0 if error. See bdrv_write() for the return codes */
482 int bdrv_read(BlockDriverState *bs, int64_t sector_num, 
483               uint8_t *buf, int nb_sectors)
484 {
485     BlockDriver *drv = bs->drv;
486
487     if (!drv)
488         return -ENOMEDIUM;
489
490     if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) {
491             memcpy(buf, bs->boot_sector_data, 512);
492         sector_num++;
493         nb_sectors--;
494         buf += 512;
495         if (nb_sectors == 0)
496             return 0;
497     }
498     if (drv->bdrv_pread) {
499         int ret, len;
500         len = nb_sectors * 512;
501         ret = drv->bdrv_pread(bs, sector_num * 512, buf, len);
502         if (ret < 0)
503             return ret;
504         else if (ret != len)
505             return -EINVAL;
506         else
507             return 0;
508     } else {
509         return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
510     }
511 }
512
513 /* Return < 0 if error. Important errors are: 
514   -EIO         generic I/O error (may happen for all errors)
515   -ENOMEDIUM   No media inserted.
516   -EINVAL      Invalid sector number or nb_sectors
517   -EACCES      Trying to write a read-only device
518 */
519 int bdrv_write(BlockDriverState *bs, int64_t sector_num, 
520                const uint8_t *buf, int nb_sectors)
521 {
522     BlockDriver *drv = bs->drv;
523     if (!bs->drv)
524         return -ENOMEDIUM;
525     if (bs->read_only)
526         return -EACCES;
527     if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) {
528         memcpy(bs->boot_sector_data, buf, 512);   
529     }
530     if (drv->bdrv_pwrite) {
531         int ret, len;
532         len = nb_sectors * 512;
533         ret = drv->bdrv_pwrite(bs, sector_num * 512, buf, len);
534         if (ret < 0)
535             return ret;
536         else if (ret != len)
537             return -EIO;
538         else
539             return 0;
540     } else {
541         return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
542     }
543 }
544
545 static int bdrv_pread_em(BlockDriverState *bs, int64_t offset, 
546                          uint8_t *buf, int count1)
547 {
548     uint8_t tmp_buf[SECTOR_SIZE];
549     int len, nb_sectors, count;
550     int64_t sector_num;
551
552     count = count1;
553     /* first read to align to sector start */
554     len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
555     if (len > count)
556         len = count;
557     sector_num = offset >> SECTOR_BITS;
558     if (len > 0) {
559         if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
560             return -EIO;
561         memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
562         count -= len;
563         if (count == 0)
564             return count1;
565         sector_num++;
566         buf += len;
567     }
568
569     /* read the sectors "in place" */
570     nb_sectors = count >> SECTOR_BITS;
571     if (nb_sectors > 0) {
572         if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
573             return -EIO;
574         sector_num += nb_sectors;
575         len = nb_sectors << SECTOR_BITS;
576         buf += len;
577         count -= len;
578     }
579
580     /* add data from the last sector */
581     if (count > 0) {
582         if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
583             return -EIO;
584         memcpy(buf, tmp_buf, count);
585     }
586     return count1;
587 }
588
589 static int bdrv_pwrite_em(BlockDriverState *bs, int64_t offset, 
590                           const uint8_t *buf, int count1)
591 {
592     uint8_t tmp_buf[SECTOR_SIZE];
593     int len, nb_sectors, count;
594     int64_t sector_num;
595
596     count = count1;
597     /* first write to align to sector start */
598     len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
599     if (len > count)
600         len = count;
601     sector_num = offset >> SECTOR_BITS;
602     if (len > 0) {
603         if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
604             return -EIO;
605         memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
606         if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
607             return -EIO;
608         count -= len;
609         if (count == 0)
610             return count1;
611         sector_num++;
612         buf += len;
613     }
614
615     /* write the sectors "in place" */
616     nb_sectors = count >> SECTOR_BITS;
617     if (nb_sectors > 0) {
618         if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
619             return -EIO;
620         sector_num += nb_sectors;
621         len = nb_sectors << SECTOR_BITS;
622         buf += len;
623         count -= len;
624     }
625
626     /* add data from the last sector */
627     if (count > 0) {
628         if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
629             return -EIO;
630         memcpy(tmp_buf, buf, count);
631         if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
632             return -EIO;
633     }
634     return count1;
635 }
636
637 /**
638  * Read with byte offsets (needed only for file protocols) 
639  */
640 int bdrv_pread(BlockDriverState *bs, int64_t offset, 
641                void *buf1, int count1)
642 {
643     BlockDriver *drv = bs->drv;
644
645     if (!drv)
646         return -ENOMEDIUM;
647     if (!drv->bdrv_pread)
648         return bdrv_pread_em(bs, offset, buf1, count1);
649     return drv->bdrv_pread(bs, offset, buf1, count1);
650 }
651
652 /** 
653  * Write with byte offsets (needed only for file protocols) 
654  */
655 int bdrv_pwrite(BlockDriverState *bs, int64_t offset, 
656                 const void *buf1, int count1)
657 {
658     BlockDriver *drv = bs->drv;
659
660     if (!drv)
661         return -ENOMEDIUM;
662     if (!drv->bdrv_pwrite)
663         return bdrv_pwrite_em(bs, offset, buf1, count1);
664     return drv->bdrv_pwrite(bs, offset, buf1, count1);
665 }
666
667 /**
668  * Truncate file to 'offset' bytes (needed only for file protocols)
669  */
670 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
671 {
672     BlockDriver *drv = bs->drv;
673     if (!drv)
674         return -ENOMEDIUM;
675     if (!drv->bdrv_truncate)
676         return -ENOTSUP;
677     return drv->bdrv_truncate(bs, offset);
678 }
679
680 /**
681  * Length of a file in bytes. Return < 0 if error or unknown.
682  */
683 int64_t bdrv_getlength(BlockDriverState *bs)
684 {
685     BlockDriver *drv = bs->drv;
686     if (!drv)
687         return -ENOMEDIUM;
688     if (!drv->bdrv_getlength) {
689         /* legacy mode */
690         return bs->total_sectors * SECTOR_SIZE;
691     }
692     return drv->bdrv_getlength(bs);
693 }
694
695 /* return 0 as number of sectors if no device present or error */
696 void bdrv_get_geometry(BlockDriverState *bs, int64_t *nb_sectors_ptr)
697 {
698     int64_t length;
699     length = bdrv_getlength(bs);
700     if (length < 0)
701         length = 0;
702     else
703         length = length >> SECTOR_BITS;
704     *nb_sectors_ptr = length;
705 }
706
707 /* force a given boot sector. */
708 void bdrv_set_boot_sector(BlockDriverState *bs, const uint8_t *data, int size)
709 {
710     bs->boot_sector_enabled = 1;
711     if (size > 512)
712         size = 512;
713     memcpy(bs->boot_sector_data, data, size);
714     memset(bs->boot_sector_data + size, 0, 512 - size);
715 }
716
717 void bdrv_set_geometry_hint(BlockDriverState *bs, 
718                             int cyls, int heads, int secs)
719 {
720     bs->cyls = cyls;
721     bs->heads = heads;
722     bs->secs = secs;
723 }
724
725 void bdrv_set_type_hint(BlockDriverState *bs, int type)
726 {
727     bs->type = type;
728     bs->removable = ((type == BDRV_TYPE_CDROM ||
729                       type == BDRV_TYPE_FLOPPY));
730 }
731
732 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
733 {
734     bs->translation = translation;
735 }
736
737 void bdrv_get_geometry_hint(BlockDriverState *bs, 
738                             int *pcyls, int *pheads, int *psecs)
739 {
740     *pcyls = bs->cyls;
741     *pheads = bs->heads;
742     *psecs = bs->secs;
743 }
744
745 int bdrv_get_type_hint(BlockDriverState *bs)
746 {
747     return bs->type;
748 }
749
750 int bdrv_get_translation_hint(BlockDriverState *bs)
751 {
752     return bs->translation;
753 }
754
755 int bdrv_is_removable(BlockDriverState *bs)
756 {
757     return bs->removable;
758 }
759
760 int bdrv_is_read_only(BlockDriverState *bs)
761 {
762     return bs->read_only;
763 }
764
765 /* XXX: no longer used */
766 void bdrv_set_change_cb(BlockDriverState *bs, 
767                         void (*change_cb)(void *opaque), void *opaque)
768 {
769     bs->change_cb = change_cb;
770     bs->change_opaque = opaque;
771 }
772
773 int bdrv_is_encrypted(BlockDriverState *bs)
774 {
775     if (bs->backing_hd && bs->backing_hd->encrypted)
776         return 1;
777     return bs->encrypted;
778 }
779
780 int bdrv_set_key(BlockDriverState *bs, const char *key)
781 {
782     int ret;
783     if (bs->backing_hd && bs->backing_hd->encrypted) {
784         ret = bdrv_set_key(bs->backing_hd, key);
785         if (ret < 0)
786             return ret;
787         if (!bs->encrypted)
788             return 0;
789     }
790     if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
791         return -1;
792     return bs->drv->bdrv_set_key(bs, key);
793 }
794
795 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
796 {
797     if (!bs->drv) {
798         buf[0] = '\0';
799     } else {
800         pstrcpy(buf, buf_size, bs->drv->format_name);
801     }
802 }
803
804 void bdrv_iterate_format(void (*it)(void *opaque, const char *name), 
805                          void *opaque)
806 {
807     BlockDriver *drv;
808
809     for (drv = first_drv; drv != NULL; drv = drv->next) {
810         it(opaque, drv->format_name);
811     }
812 }
813
814 BlockDriverState *bdrv_find(const char *name)
815 {
816     BlockDriverState *bs;
817
818     for (bs = bdrv_first; bs != NULL; bs = bs->next) {
819         if (!strcmp(name, bs->device_name))
820             return bs;
821     }
822     return NULL;
823 }
824
825 void bdrv_iterate(void (*it)(void *opaque, const char *name), void *opaque)
826 {
827     BlockDriverState *bs;
828
829     for (bs = bdrv_first; bs != NULL; bs = bs->next) {
830         it(opaque, bs->device_name);
831     }
832 }
833
834 const char *bdrv_get_device_name(BlockDriverState *bs)
835 {
836     return bs->device_name;
837 }
838
839 void bdrv_flush(BlockDriverState *bs)
840 {
841     if (bs->drv->bdrv_flush)
842         bs->drv->bdrv_flush(bs);
843     if (bs->backing_hd)
844         bdrv_flush(bs->backing_hd);
845 }
846
847 void bdrv_info(void)
848 {
849     BlockDriverState *bs;
850
851     for (bs = bdrv_first; bs != NULL; bs = bs->next) {
852         term_printf("%s:", bs->device_name);
853         term_printf(" type=");
854         switch(bs->type) {
855         case BDRV_TYPE_HD:
856             term_printf("hd");
857             break;
858         case BDRV_TYPE_CDROM:
859             term_printf("cdrom");
860             break;
861         case BDRV_TYPE_FLOPPY:
862             term_printf("floppy");
863             break;
864         }
865         term_printf(" removable=%d", bs->removable);
866         if (bs->removable) {
867             term_printf(" locked=%d", bs->locked);
868         }
869         if (bs->drv) {
870             term_printf(" file=%s", bs->filename);
871             if (bs->backing_file[0] != '\0')
872                 term_printf(" backing_file=%s", bs->backing_file);
873             term_printf(" ro=%d", bs->read_only);
874             term_printf(" drv=%s", bs->drv->format_name);
875             if (bs->encrypted)
876                 term_printf(" encrypted");
877         } else {
878             term_printf(" [not inserted]");
879         }
880         term_printf("\n");
881     }
882 }
883
884 void bdrv_get_backing_filename(BlockDriverState *bs, 
885                                char *filename, int filename_size)
886 {
887     if (!bs->backing_hd) {
888         pstrcpy(filename, filename_size, "");
889     } else {
890         pstrcpy(filename, filename_size, bs->backing_file);
891     }
892 }
893
894 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num, 
895                           const uint8_t *buf, int nb_sectors)
896 {
897     BlockDriver *drv = bs->drv;
898     if (!drv)
899         return -ENOMEDIUM;
900     if (!drv->bdrv_write_compressed)
901         return -ENOTSUP;
902     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
903 }
904     
905 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
906 {
907     BlockDriver *drv = bs->drv;
908     if (!drv)
909         return -ENOMEDIUM;
910     if (!drv->bdrv_get_info)
911         return -ENOTSUP;
912     memset(bdi, 0, sizeof(*bdi));
913     return drv->bdrv_get_info(bs, bdi);
914 }
915
916 /**************************************************************/
917 /* handling of snapshots */
918
919 int bdrv_snapshot_create(BlockDriverState *bs, 
920                          QEMUSnapshotInfo *sn_info)
921 {
922     BlockDriver *drv = bs->drv;
923     if (!drv)
924         return -ENOMEDIUM;
925     if (!drv->bdrv_snapshot_create)
926         return -ENOTSUP;
927     return drv->bdrv_snapshot_create(bs, sn_info);
928 }
929
930 int bdrv_snapshot_goto(BlockDriverState *bs, 
931                        const char *snapshot_id)
932 {
933     BlockDriver *drv = bs->drv;
934     if (!drv)
935         return -ENOMEDIUM;
936     if (!drv->bdrv_snapshot_goto)
937         return -ENOTSUP;
938     return drv->bdrv_snapshot_goto(bs, snapshot_id);
939 }
940
941 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
942 {
943     BlockDriver *drv = bs->drv;
944     if (!drv)
945         return -ENOMEDIUM;
946     if (!drv->bdrv_snapshot_delete)
947         return -ENOTSUP;
948     return drv->bdrv_snapshot_delete(bs, snapshot_id);
949 }
950
951 int bdrv_snapshot_list(BlockDriverState *bs, 
952                        QEMUSnapshotInfo **psn_info)
953 {
954     BlockDriver *drv = bs->drv;
955     if (!drv)
956         return -ENOMEDIUM;
957     if (!drv->bdrv_snapshot_list)
958         return -ENOTSUP;
959     return drv->bdrv_snapshot_list(bs, psn_info);
960 }
961
962 #define NB_SUFFIXES 4
963
964 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
965 {
966     static const char suffixes[NB_SUFFIXES] = "KMGT";
967     int64_t base;
968     int i;
969
970     if (size <= 999) {
971         snprintf(buf, buf_size, "%" PRId64, size);
972     } else {
973         base = 1024;
974         for(i = 0; i < NB_SUFFIXES; i++) {
975             if (size < (10 * base)) {
976                 snprintf(buf, buf_size, "%0.1f%c", 
977                          (double)size / base,
978                          suffixes[i]);
979                 break;
980             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
981                 snprintf(buf, buf_size, "%" PRId64 "%c", 
982                          ((size + (base >> 1)) / base),
983                          suffixes[i]);
984                 break;
985             }
986             base = base * 1024;
987         }
988     }
989     return buf;
990 }
991
992 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
993 {
994     char buf1[128], date_buf[128], clock_buf[128];
995     struct tm tm;
996     time_t ti;
997     int64_t secs;
998
999     if (!sn) {
1000         snprintf(buf, buf_size, 
1001                  "%-10s%-20s%7s%20s%15s", 
1002                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1003     } else {
1004         ti = sn->date_sec;
1005 #ifndef _WIN32
1006         localtime_r(&ti, &tm);
1007 #endif
1008         strftime(date_buf, sizeof(date_buf),
1009                  "%Y-%m-%d %H:%M:%S", &tm);
1010         secs = sn->vm_clock_nsec / 1000000000;
1011         snprintf(clock_buf, sizeof(clock_buf),
1012                  "%02d:%02d:%02d.%03d",
1013                  (int)(secs / 3600),
1014                  (int)((secs / 60) % 60),
1015                  (int)(secs % 60), 
1016                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
1017         snprintf(buf, buf_size,
1018                  "%-10s%-20s%7s%20s%15s", 
1019                  sn->id_str, sn->name,
1020                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1021                  date_buf,
1022                  clock_buf);
1023     }
1024     return buf;
1025 }
1026
1027
1028 /**************************************************************/
1029 /* async I/Os */
1030
1031 BlockDriverAIOCB *bdrv_aio_read(BlockDriverState *bs, int64_t sector_num,
1032                                 uint8_t *buf, int nb_sectors,
1033                                 BlockDriverCompletionFunc *cb, void *opaque)
1034 {
1035     BlockDriver *drv = bs->drv;
1036
1037     if (!drv)
1038         return NULL;
1039     
1040     /* XXX: we assume that nb_sectors == 0 is suppored by the async read */
1041     if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) {
1042         memcpy(buf, bs->boot_sector_data, 512);
1043         sector_num++;
1044         nb_sectors--;
1045         buf += 512;
1046     }
1047
1048     return drv->bdrv_aio_read(bs, sector_num, buf, nb_sectors, cb, opaque);
1049 }
1050
1051 BlockDriverAIOCB *bdrv_aio_write(BlockDriverState *bs, int64_t sector_num,
1052                                  const uint8_t *buf, int nb_sectors,
1053                                  BlockDriverCompletionFunc *cb, void *opaque)
1054 {
1055     BlockDriver *drv = bs->drv;
1056
1057     if (!drv)
1058         return NULL;
1059     if (bs->read_only)
1060         return NULL;
1061     if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) {
1062         memcpy(bs->boot_sector_data, buf, 512);   
1063     }
1064
1065     return drv->bdrv_aio_write(bs, sector_num, buf, nb_sectors, cb, opaque);
1066 }
1067
1068 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1069 {
1070     BlockDriver *drv = acb->bs->drv;
1071
1072     drv->bdrv_aio_cancel(acb);
1073 }
1074
1075
1076 /**************************************************************/
1077 /* async block device emulation */
1078
1079 #ifdef QEMU_TOOL
1080 static BlockDriverAIOCB *bdrv_aio_read_em(BlockDriverState *bs,
1081         int64_t sector_num, uint8_t *buf, int nb_sectors,
1082         BlockDriverCompletionFunc *cb, void *opaque)
1083 {
1084     int ret;
1085     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
1086     cb(opaque, ret);
1087     return NULL;
1088 }
1089
1090 static BlockDriverAIOCB *bdrv_aio_write_em(BlockDriverState *bs,
1091         int64_t sector_num, const uint8_t *buf, int nb_sectors,
1092         BlockDriverCompletionFunc *cb, void *opaque)
1093 {
1094     int ret;
1095     ret = bdrv_write(bs, sector_num, buf, nb_sectors);
1096     cb(opaque, ret);
1097     return NULL;
1098 }
1099
1100 static void bdrv_aio_cancel_em(BlockDriverAIOCB *acb)
1101 {
1102 }
1103 #else
1104 static void bdrv_aio_bh_cb(void *opaque)
1105 {
1106     BlockDriverAIOCBSync *acb = opaque;
1107     acb->common.cb(acb->common.opaque, acb->ret);
1108     qemu_aio_release(acb);
1109 }
1110
1111 static BlockDriverAIOCB *bdrv_aio_read_em(BlockDriverState *bs,
1112         int64_t sector_num, uint8_t *buf, int nb_sectors,
1113         BlockDriverCompletionFunc *cb, void *opaque)
1114 {
1115     BlockDriverAIOCBSync *acb;
1116     int ret;
1117
1118     acb = qemu_aio_get(bs, cb, opaque);
1119     if (!acb->bh)
1120         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1121     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
1122     acb->ret = ret;
1123     qemu_bh_schedule(acb->bh);
1124     return &acb->common;
1125 }
1126
1127 static BlockDriverAIOCB *bdrv_aio_write_em(BlockDriverState *bs,
1128         int64_t sector_num, const uint8_t *buf, int nb_sectors,
1129         BlockDriverCompletionFunc *cb, void *opaque)
1130 {
1131     BlockDriverAIOCBSync *acb;
1132     int ret;
1133
1134     acb = qemu_aio_get(bs, cb, opaque);
1135     if (!acb->bh)
1136         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1137     ret = bdrv_write(bs, sector_num, buf, nb_sectors);
1138     acb->ret = ret;
1139     qemu_bh_schedule(acb->bh);
1140     return &acb->common;
1141 }
1142
1143 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1144 {
1145     BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1146     qemu_bh_cancel(acb->bh);
1147     qemu_aio_release(acb);
1148 }
1149 #endif /* !QEMU_TOOL */
1150
1151 /**************************************************************/
1152 /* sync block device emulation */
1153
1154 static void bdrv_rw_em_cb(void *opaque, int ret)
1155 {
1156     *(int *)opaque = ret;
1157 }
1158
1159 #define NOT_DONE 0x7fffffff
1160
1161 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num, 
1162                         uint8_t *buf, int nb_sectors)
1163 {
1164     int async_ret;
1165     BlockDriverAIOCB *acb;
1166
1167     async_ret = NOT_DONE;
1168     qemu_aio_wait_start();
1169     acb = bdrv_aio_read(bs, sector_num, buf, nb_sectors, 
1170                         bdrv_rw_em_cb, &async_ret);
1171     if (acb == NULL) {
1172         qemu_aio_wait_end();
1173         return -1;
1174     }
1175     while (async_ret == NOT_DONE) {
1176         qemu_aio_wait();
1177     }
1178     qemu_aio_wait_end();
1179     return async_ret;
1180 }
1181
1182 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1183                          const uint8_t *buf, int nb_sectors)
1184 {
1185     int async_ret;
1186     BlockDriverAIOCB *acb;
1187
1188     async_ret = NOT_DONE;
1189     qemu_aio_wait_start();
1190     acb = bdrv_aio_write(bs, sector_num, buf, nb_sectors, 
1191                          bdrv_rw_em_cb, &async_ret);
1192     if (acb == NULL) {
1193         qemu_aio_wait_end();
1194         return -1;
1195     }
1196     while (async_ret == NOT_DONE) {
1197         qemu_aio_wait();
1198     }
1199     qemu_aio_wait_end();
1200     return async_ret;
1201 }
1202
1203 void bdrv_init(void)
1204 {
1205     bdrv_register(&bdrv_raw);
1206     bdrv_register(&bdrv_host_device);
1207 #ifndef _WIN32
1208     bdrv_register(&bdrv_cow);
1209 #endif
1210     bdrv_register(&bdrv_qcow);
1211     bdrv_register(&bdrv_vmdk);
1212     bdrv_register(&bdrv_cloop);
1213     bdrv_register(&bdrv_dmg);
1214     bdrv_register(&bdrv_bochs);
1215     bdrv_register(&bdrv_vpc);
1216     bdrv_register(&bdrv_vvfat);
1217     bdrv_register(&bdrv_qcow2);
1218 }
1219
1220 void *qemu_aio_get(BlockDriverState *bs, BlockDriverCompletionFunc *cb,
1221                    void *opaque)
1222 {
1223     BlockDriver *drv;
1224     BlockDriverAIOCB *acb;
1225
1226     drv = bs->drv;
1227     if (drv->free_aiocb) {
1228         acb = drv->free_aiocb;
1229         drv->free_aiocb = acb->next;
1230     } else {
1231         acb = qemu_mallocz(drv->aiocb_size);
1232         if (!acb)
1233             return NULL;
1234     }
1235     acb->bs = bs;
1236     acb->cb = cb;
1237     acb->opaque = opaque;
1238     return acb;
1239 }
1240
1241 void qemu_aio_release(void *p)
1242 {
1243     BlockDriverAIOCB *acb = p;
1244     BlockDriver *drv = acb->bs->drv;
1245     acb->next = drv->free_aiocb;
1246     drv->free_aiocb = acb;
1247 }
1248
1249 /**************************************************************/
1250 /* removable device support */
1251
1252 /**
1253  * Return TRUE if the media is present
1254  */
1255 int bdrv_is_inserted(BlockDriverState *bs)
1256 {
1257     BlockDriver *drv = bs->drv;
1258     int ret;
1259     if (!drv)
1260         return 0;
1261     if (!drv->bdrv_is_inserted)
1262         return 1;
1263     ret = drv->bdrv_is_inserted(bs);
1264     return ret;
1265 }
1266
1267 /**
1268  * Return TRUE if the media changed since the last call to this
1269  * function. It is currently only used for floppy disks 
1270  */
1271 int bdrv_media_changed(BlockDriverState *bs)
1272 {
1273     BlockDriver *drv = bs->drv;
1274     int ret;
1275
1276     if (!drv || !drv->bdrv_media_changed)
1277         ret = -ENOTSUP;
1278     else
1279         ret = drv->bdrv_media_changed(bs);
1280     if (ret == -ENOTSUP)
1281         ret = bs->media_changed;
1282     bs->media_changed = 0;
1283     return ret;
1284 }
1285
1286 /**
1287  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1288  */
1289 void bdrv_eject(BlockDriverState *bs, int eject_flag)
1290 {
1291     BlockDriver *drv = bs->drv;
1292     int ret;
1293
1294     if (!drv || !drv->bdrv_eject) {
1295         ret = -ENOTSUP;
1296     } else {
1297         ret = drv->bdrv_eject(bs, eject_flag);
1298     }
1299     if (ret == -ENOTSUP) {
1300         if (eject_flag)
1301             bdrv_close(bs);
1302     }
1303 }
1304
1305 int bdrv_is_locked(BlockDriverState *bs)
1306 {
1307     return bs->locked;
1308 }
1309
1310 /**
1311  * Lock or unlock the media (if it is locked, the user won't be able
1312  * to eject it manually).
1313  */
1314 void bdrv_set_locked(BlockDriverState *bs, int locked)
1315 {
1316     BlockDriver *drv = bs->drv;
1317
1318     bs->locked = locked;
1319     if (drv && drv->bdrv_set_locked) {
1320         drv->bdrv_set_locked(bs, locked);
1321     }
1322 }