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