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