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