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