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