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