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