]> Git Repo - qemu.git/blob - block.c
trace: trace bdrv_open_common()
[qemu.git] / 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 "config-host.h"
25 #include "qemu-common.h"
26 #include "trace.h"
27 #include "monitor.h"
28 #include "block_int.h"
29 #include "module.h"
30 #include "qemu-objects.h"
31 #include "qemu-coroutine.h"
32
33 #ifdef CONFIG_BSD
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/ioctl.h>
37 #include <sys/queue.h>
38 #ifndef __DragonFly__
39 #include <sys/disk.h>
40 #endif
41 #endif
42
43 #ifdef _WIN32
44 #include <windows.h>
45 #endif
46
47 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
48 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50         BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
53         BlockDriverCompletionFunc *cb, void *opaque);
54 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55         BlockDriverCompletionFunc *cb, void *opaque);
56 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57         BlockDriverCompletionFunc *cb, void *opaque);
58 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
59                         uint8_t *buf, int nb_sectors);
60 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61                          const uint8_t *buf, int nb_sectors);
62 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64         BlockDriverCompletionFunc *cb, void *opaque);
65 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67         BlockDriverCompletionFunc *cb, void *opaque);
68 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69                                          int64_t sector_num, int nb_sectors,
70                                          QEMUIOVector *iov);
71 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72                                          int64_t sector_num, int nb_sectors,
73                                          QEMUIOVector *iov);
74 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
75
76 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
77     QTAILQ_HEAD_INITIALIZER(bdrv_states);
78
79 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80     QLIST_HEAD_INITIALIZER(bdrv_drivers);
81
82 /* The device to use for VM snapshots */
83 static BlockDriverState *bs_snapshots;
84
85 /* If non-zero, use only whitelisted block drivers */
86 static int use_bdrv_whitelist;
87
88 #ifdef _WIN32
89 static int is_windows_drive_prefix(const char *filename)
90 {
91     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
93             filename[1] == ':');
94 }
95
96 int is_windows_drive(const char *filename)
97 {
98     if (is_windows_drive_prefix(filename) &&
99         filename[2] == '\0')
100         return 1;
101     if (strstart(filename, "\\\\.\\", NULL) ||
102         strstart(filename, "//./", NULL))
103         return 1;
104     return 0;
105 }
106 #endif
107
108 /* check if the path starts with "<protocol>:" */
109 static int path_has_protocol(const char *path)
110 {
111 #ifdef _WIN32
112     if (is_windows_drive(path) ||
113         is_windows_drive_prefix(path)) {
114         return 0;
115     }
116 #endif
117
118     return strchr(path, ':') != NULL;
119 }
120
121 int path_is_absolute(const char *path)
122 {
123     const char *p;
124 #ifdef _WIN32
125     /* specific case for names like: "\\.\d:" */
126     if (*path == '/' || *path == '\\')
127         return 1;
128 #endif
129     p = strchr(path, ':');
130     if (p)
131         p++;
132     else
133         p = path;
134 #ifdef _WIN32
135     return (*p == '/' || *p == '\\');
136 #else
137     return (*p == '/');
138 #endif
139 }
140
141 /* if filename is absolute, just copy it to dest. Otherwise, build a
142    path to it by considering it is relative to base_path. URL are
143    supported. */
144 void path_combine(char *dest, int dest_size,
145                   const char *base_path,
146                   const char *filename)
147 {
148     const char *p, *p1;
149     int len;
150
151     if (dest_size <= 0)
152         return;
153     if (path_is_absolute(filename)) {
154         pstrcpy(dest, dest_size, filename);
155     } else {
156         p = strchr(base_path, ':');
157         if (p)
158             p++;
159         else
160             p = base_path;
161         p1 = strrchr(base_path, '/');
162 #ifdef _WIN32
163         {
164             const char *p2;
165             p2 = strrchr(base_path, '\\');
166             if (!p1 || p2 > p1)
167                 p1 = p2;
168         }
169 #endif
170         if (p1)
171             p1++;
172         else
173             p1 = base_path;
174         if (p1 > p)
175             p = p1;
176         len = p - base_path;
177         if (len > dest_size - 1)
178             len = dest_size - 1;
179         memcpy(dest, base_path, len);
180         dest[len] = '\0';
181         pstrcat(dest, dest_size, filename);
182     }
183 }
184
185 void bdrv_register(BlockDriver *bdrv)
186 {
187     if (bdrv->bdrv_co_readv) {
188         /* Emulate AIO by coroutines, and sync by AIO */
189         bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
190         bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
191         bdrv->bdrv_read = bdrv_read_em;
192         bdrv->bdrv_write = bdrv_write_em;
193      } else {
194         bdrv->bdrv_co_readv = bdrv_co_readv_em;
195         bdrv->bdrv_co_writev = bdrv_co_writev_em;
196
197         if (!bdrv->bdrv_aio_readv) {
198             /* add AIO emulation layer */
199             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
200             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
201         } else if (!bdrv->bdrv_read) {
202             /* add synchronous IO emulation layer */
203             bdrv->bdrv_read = bdrv_read_em;
204             bdrv->bdrv_write = bdrv_write_em;
205         }
206     }
207
208     if (!bdrv->bdrv_aio_flush)
209         bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
210
211     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
212 }
213
214 /* create a new block device (by default it is empty) */
215 BlockDriverState *bdrv_new(const char *device_name)
216 {
217     BlockDriverState *bs;
218
219     bs = g_malloc0(sizeof(BlockDriverState));
220     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
221     if (device_name[0] != '\0') {
222         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
223     }
224     return bs;
225 }
226
227 BlockDriver *bdrv_find_format(const char *format_name)
228 {
229     BlockDriver *drv1;
230     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
231         if (!strcmp(drv1->format_name, format_name)) {
232             return drv1;
233         }
234     }
235     return NULL;
236 }
237
238 static int bdrv_is_whitelisted(BlockDriver *drv)
239 {
240     static const char *whitelist[] = {
241         CONFIG_BDRV_WHITELIST
242     };
243     const char **p;
244
245     if (!whitelist[0])
246         return 1;               /* no whitelist, anything goes */
247
248     for (p = whitelist; *p; p++) {
249         if (!strcmp(drv->format_name, *p)) {
250             return 1;
251         }
252     }
253     return 0;
254 }
255
256 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
257 {
258     BlockDriver *drv = bdrv_find_format(format_name);
259     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
260 }
261
262 int bdrv_create(BlockDriver *drv, const char* filename,
263     QEMUOptionParameter *options)
264 {
265     if (!drv->bdrv_create)
266         return -ENOTSUP;
267
268     return drv->bdrv_create(filename, options);
269 }
270
271 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
272 {
273     BlockDriver *drv;
274
275     drv = bdrv_find_protocol(filename);
276     if (drv == NULL) {
277         return -ENOENT;
278     }
279
280     return bdrv_create(drv, filename, options);
281 }
282
283 #ifdef _WIN32
284 void get_tmp_filename(char *filename, int size)
285 {
286     char temp_dir[MAX_PATH];
287
288     GetTempPath(MAX_PATH, temp_dir);
289     GetTempFileName(temp_dir, "qem", 0, filename);
290 }
291 #else
292 void get_tmp_filename(char *filename, int size)
293 {
294     int fd;
295     const char *tmpdir;
296     /* XXX: race condition possible */
297     tmpdir = getenv("TMPDIR");
298     if (!tmpdir)
299         tmpdir = "/tmp";
300     snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
301     fd = mkstemp(filename);
302     close(fd);
303 }
304 #endif
305
306 /*
307  * Detect host devices. By convention, /dev/cdrom[N] is always
308  * recognized as a host CDROM.
309  */
310 static BlockDriver *find_hdev_driver(const char *filename)
311 {
312     int score_max = 0, score;
313     BlockDriver *drv = NULL, *d;
314
315     QLIST_FOREACH(d, &bdrv_drivers, list) {
316         if (d->bdrv_probe_device) {
317             score = d->bdrv_probe_device(filename);
318             if (score > score_max) {
319                 score_max = score;
320                 drv = d;
321             }
322         }
323     }
324
325     return drv;
326 }
327
328 BlockDriver *bdrv_find_protocol(const char *filename)
329 {
330     BlockDriver *drv1;
331     char protocol[128];
332     int len;
333     const char *p;
334
335     /* TODO Drivers without bdrv_file_open must be specified explicitly */
336
337     /*
338      * XXX(hch): we really should not let host device detection
339      * override an explicit protocol specification, but moving this
340      * later breaks access to device names with colons in them.
341      * Thanks to the brain-dead persistent naming schemes on udev-
342      * based Linux systems those actually are quite common.
343      */
344     drv1 = find_hdev_driver(filename);
345     if (drv1) {
346         return drv1;
347     }
348
349     if (!path_has_protocol(filename)) {
350         return bdrv_find_format("file");
351     }
352     p = strchr(filename, ':');
353     assert(p != NULL);
354     len = p - filename;
355     if (len > sizeof(protocol) - 1)
356         len = sizeof(protocol) - 1;
357     memcpy(protocol, filename, len);
358     protocol[len] = '\0';
359     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
360         if (drv1->protocol_name &&
361             !strcmp(drv1->protocol_name, protocol)) {
362             return drv1;
363         }
364     }
365     return NULL;
366 }
367
368 static int find_image_format(const char *filename, BlockDriver **pdrv)
369 {
370     int ret, score, score_max;
371     BlockDriver *drv1, *drv;
372     uint8_t buf[2048];
373     BlockDriverState *bs;
374
375     ret = bdrv_file_open(&bs, filename, 0);
376     if (ret < 0) {
377         *pdrv = NULL;
378         return ret;
379     }
380
381     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382     if (bs->sg || !bdrv_is_inserted(bs)) {
383         bdrv_delete(bs);
384         drv = bdrv_find_format("raw");
385         if (!drv) {
386             ret = -ENOENT;
387         }
388         *pdrv = drv;
389         return ret;
390     }
391
392     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
393     bdrv_delete(bs);
394     if (ret < 0) {
395         *pdrv = NULL;
396         return ret;
397     }
398
399     score_max = 0;
400     drv = NULL;
401     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
402         if (drv1->bdrv_probe) {
403             score = drv1->bdrv_probe(buf, ret, filename);
404             if (score > score_max) {
405                 score_max = score;
406                 drv = drv1;
407             }
408         }
409     }
410     if (!drv) {
411         ret = -ENOENT;
412     }
413     *pdrv = drv;
414     return ret;
415 }
416
417 /**
418  * Set the current 'total_sectors' value
419  */
420 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
421 {
422     BlockDriver *drv = bs->drv;
423
424     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
425     if (bs->sg)
426         return 0;
427
428     /* query actual device if possible, otherwise just trust the hint */
429     if (drv->bdrv_getlength) {
430         int64_t length = drv->bdrv_getlength(bs);
431         if (length < 0) {
432             return length;
433         }
434         hint = length >> BDRV_SECTOR_BITS;
435     }
436
437     bs->total_sectors = hint;
438     return 0;
439 }
440
441 /**
442  * Set open flags for a given cache mode
443  *
444  * Return 0 on success, -1 if the cache mode was invalid.
445  */
446 int bdrv_parse_cache_flags(const char *mode, int *flags)
447 {
448     *flags &= ~BDRV_O_CACHE_MASK;
449
450     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
451         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
452     } else if (!strcmp(mode, "directsync")) {
453         *flags |= BDRV_O_NOCACHE;
454     } else if (!strcmp(mode, "writeback")) {
455         *flags |= BDRV_O_CACHE_WB;
456     } else if (!strcmp(mode, "unsafe")) {
457         *flags |= BDRV_O_CACHE_WB;
458         *flags |= BDRV_O_NO_FLUSH;
459     } else if (!strcmp(mode, "writethrough")) {
460         /* this is the default */
461     } else {
462         return -1;
463     }
464
465     return 0;
466 }
467
468 /*
469  * Common part for opening disk images and files
470  */
471 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
472     int flags, BlockDriver *drv)
473 {
474     int ret, open_flags;
475
476     assert(drv != NULL);
477
478     trace_bdrv_open_common(bs, filename, flags, drv->format_name);
479
480     bs->file = NULL;
481     bs->total_sectors = 0;
482     bs->encrypted = 0;
483     bs->valid_key = 0;
484     bs->open_flags = flags;
485     bs->buffer_alignment = 512;
486
487     pstrcpy(bs->filename, sizeof(bs->filename), filename);
488
489     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
490         return -ENOTSUP;
491     }
492
493     bs->drv = drv;
494     bs->opaque = g_malloc0(drv->instance_size);
495
496     if (flags & BDRV_O_CACHE_WB)
497         bs->enable_write_cache = 1;
498
499     /*
500      * Clear flags that are internal to the block layer before opening the
501      * image.
502      */
503     open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
504
505     /*
506      * Snapshots should be writable.
507      */
508     if (bs->is_temporary) {
509         open_flags |= BDRV_O_RDWR;
510     }
511
512     /* Open the image, either directly or using a protocol */
513     if (drv->bdrv_file_open) {
514         ret = drv->bdrv_file_open(bs, filename, open_flags);
515     } else {
516         ret = bdrv_file_open(&bs->file, filename, open_flags);
517         if (ret >= 0) {
518             ret = drv->bdrv_open(bs, open_flags);
519         }
520     }
521
522     if (ret < 0) {
523         goto free_and_fail;
524     }
525
526     bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
527
528     ret = refresh_total_sectors(bs, bs->total_sectors);
529     if (ret < 0) {
530         goto free_and_fail;
531     }
532
533 #ifndef _WIN32
534     if (bs->is_temporary) {
535         unlink(filename);
536     }
537 #endif
538     return 0;
539
540 free_and_fail:
541     if (bs->file) {
542         bdrv_delete(bs->file);
543         bs->file = NULL;
544     }
545     g_free(bs->opaque);
546     bs->opaque = NULL;
547     bs->drv = NULL;
548     return ret;
549 }
550
551 /*
552  * Opens a file using a protocol (file, host_device, nbd, ...)
553  */
554 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
555 {
556     BlockDriverState *bs;
557     BlockDriver *drv;
558     int ret;
559
560     drv = bdrv_find_protocol(filename);
561     if (!drv) {
562         return -ENOENT;
563     }
564
565     bs = bdrv_new("");
566     ret = bdrv_open_common(bs, filename, flags, drv);
567     if (ret < 0) {
568         bdrv_delete(bs);
569         return ret;
570     }
571     bs->growable = 1;
572     *pbs = bs;
573     return 0;
574 }
575
576 /*
577  * Opens a disk image (raw, qcow2, vmdk, ...)
578  */
579 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
580               BlockDriver *drv)
581 {
582     int ret;
583
584     if (flags & BDRV_O_SNAPSHOT) {
585         BlockDriverState *bs1;
586         int64_t total_size;
587         int is_protocol = 0;
588         BlockDriver *bdrv_qcow2;
589         QEMUOptionParameter *options;
590         char tmp_filename[PATH_MAX];
591         char backing_filename[PATH_MAX];
592
593         /* if snapshot, we create a temporary backing file and open it
594            instead of opening 'filename' directly */
595
596         /* if there is a backing file, use it */
597         bs1 = bdrv_new("");
598         ret = bdrv_open(bs1, filename, 0, drv);
599         if (ret < 0) {
600             bdrv_delete(bs1);
601             return ret;
602         }
603         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
604
605         if (bs1->drv && bs1->drv->protocol_name)
606             is_protocol = 1;
607
608         bdrv_delete(bs1);
609
610         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
611
612         /* Real path is meaningless for protocols */
613         if (is_protocol)
614             snprintf(backing_filename, sizeof(backing_filename),
615                      "%s", filename);
616         else if (!realpath(filename, backing_filename))
617             return -errno;
618
619         bdrv_qcow2 = bdrv_find_format("qcow2");
620         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
621
622         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
623         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
624         if (drv) {
625             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
626                 drv->format_name);
627         }
628
629         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
630         free_option_parameters(options);
631         if (ret < 0) {
632             return ret;
633         }
634
635         filename = tmp_filename;
636         drv = bdrv_qcow2;
637         bs->is_temporary = 1;
638     }
639
640     /* Find the right image format driver */
641     if (!drv) {
642         ret = find_image_format(filename, &drv);
643     }
644
645     if (!drv) {
646         goto unlink_and_fail;
647     }
648
649     /* Open the image */
650     ret = bdrv_open_common(bs, filename, flags, drv);
651     if (ret < 0) {
652         goto unlink_and_fail;
653     }
654
655     /* If there is a backing file, use it */
656     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
657         char backing_filename[PATH_MAX];
658         int back_flags;
659         BlockDriver *back_drv = NULL;
660
661         bs->backing_hd = bdrv_new("");
662
663         if (path_has_protocol(bs->backing_file)) {
664             pstrcpy(backing_filename, sizeof(backing_filename),
665                     bs->backing_file);
666         } else {
667             path_combine(backing_filename, sizeof(backing_filename),
668                          filename, bs->backing_file);
669         }
670
671         if (bs->backing_format[0] != '\0') {
672             back_drv = bdrv_find_format(bs->backing_format);
673         }
674
675         /* backing files always opened read-only */
676         back_flags =
677             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
678
679         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
680         if (ret < 0) {
681             bdrv_close(bs);
682             return ret;
683         }
684         if (bs->is_temporary) {
685             bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
686         } else {
687             /* base image inherits from "parent" */
688             bs->backing_hd->keep_read_only = bs->keep_read_only;
689         }
690     }
691
692     if (!bdrv_key_required(bs)) {
693         bdrv_dev_change_media_cb(bs, true);
694     }
695
696     return 0;
697
698 unlink_and_fail:
699     if (bs->is_temporary) {
700         unlink(filename);
701     }
702     return ret;
703 }
704
705 void bdrv_close(BlockDriverState *bs)
706 {
707     if (bs->drv) {
708         if (bs == bs_snapshots) {
709             bs_snapshots = NULL;
710         }
711         if (bs->backing_hd) {
712             bdrv_delete(bs->backing_hd);
713             bs->backing_hd = NULL;
714         }
715         bs->drv->bdrv_close(bs);
716         g_free(bs->opaque);
717 #ifdef _WIN32
718         if (bs->is_temporary) {
719             unlink(bs->filename);
720         }
721 #endif
722         bs->opaque = NULL;
723         bs->drv = NULL;
724
725         if (bs->file != NULL) {
726             bdrv_close(bs->file);
727         }
728
729         bdrv_dev_change_media_cb(bs, false);
730     }
731 }
732
733 void bdrv_close_all(void)
734 {
735     BlockDriverState *bs;
736
737     QTAILQ_FOREACH(bs, &bdrv_states, list) {
738         bdrv_close(bs);
739     }
740 }
741
742 /* make a BlockDriverState anonymous by removing from bdrv_state list.
743    Also, NULL terminate the device_name to prevent double remove */
744 void bdrv_make_anon(BlockDriverState *bs)
745 {
746     if (bs->device_name[0] != '\0') {
747         QTAILQ_REMOVE(&bdrv_states, bs, list);
748     }
749     bs->device_name[0] = '\0';
750 }
751
752 void bdrv_delete(BlockDriverState *bs)
753 {
754     assert(!bs->dev);
755
756     /* remove from list, if necessary */
757     bdrv_make_anon(bs);
758
759     bdrv_close(bs);
760     if (bs->file != NULL) {
761         bdrv_delete(bs->file);
762     }
763
764     assert(bs != bs_snapshots);
765     g_free(bs);
766 }
767
768 int bdrv_attach_dev(BlockDriverState *bs, void *dev)
769 /* TODO change to DeviceState *dev when all users are qdevified */
770 {
771     if (bs->dev) {
772         return -EBUSY;
773     }
774     bs->dev = dev;
775     return 0;
776 }
777
778 /* TODO qdevified devices don't use this, remove when devices are qdevified */
779 void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
780 {
781     if (bdrv_attach_dev(bs, dev) < 0) {
782         abort();
783     }
784 }
785
786 void bdrv_detach_dev(BlockDriverState *bs, void *dev)
787 /* TODO change to DeviceState *dev when all users are qdevified */
788 {
789     assert(bs->dev == dev);
790     bs->dev = NULL;
791     bs->dev_ops = NULL;
792     bs->dev_opaque = NULL;
793     bs->buffer_alignment = 512;
794 }
795
796 /* TODO change to return DeviceState * when all users are qdevified */
797 void *bdrv_get_attached_dev(BlockDriverState *bs)
798 {
799     return bs->dev;
800 }
801
802 void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
803                       void *opaque)
804 {
805     bs->dev_ops = ops;
806     bs->dev_opaque = opaque;
807     if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
808         bs_snapshots = NULL;
809     }
810 }
811
812 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
813 {
814     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
815         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
816     }
817 }
818
819 bool bdrv_dev_has_removable_media(BlockDriverState *bs)
820 {
821     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
822 }
823
824 bool bdrv_dev_is_tray_open(BlockDriverState *bs)
825 {
826     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
827         return bs->dev_ops->is_tray_open(bs->dev_opaque);
828     }
829     return false;
830 }
831
832 static void bdrv_dev_resize_cb(BlockDriverState *bs)
833 {
834     if (bs->dev_ops && bs->dev_ops->resize_cb) {
835         bs->dev_ops->resize_cb(bs->dev_opaque);
836     }
837 }
838
839 bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
840 {
841     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
842         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
843     }
844     return false;
845 }
846
847 /*
848  * Run consistency checks on an image
849  *
850  * Returns 0 if the check could be completed (it doesn't mean that the image is
851  * free of errors) or -errno when an internal error occurred. The results of the
852  * check are stored in res.
853  */
854 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
855 {
856     if (bs->drv->bdrv_check == NULL) {
857         return -ENOTSUP;
858     }
859
860     memset(res, 0, sizeof(*res));
861     return bs->drv->bdrv_check(bs, res);
862 }
863
864 #define COMMIT_BUF_SECTORS 2048
865
866 /* commit COW file into the raw image */
867 int bdrv_commit(BlockDriverState *bs)
868 {
869     BlockDriver *drv = bs->drv;
870     BlockDriver *backing_drv;
871     int64_t sector, total_sectors;
872     int n, ro, open_flags;
873     int ret = 0, rw_ret = 0;
874     uint8_t *buf;
875     char filename[1024];
876     BlockDriverState *bs_rw, *bs_ro;
877
878     if (!drv)
879         return -ENOMEDIUM;
880     
881     if (!bs->backing_hd) {
882         return -ENOTSUP;
883     }
884
885     if (bs->backing_hd->keep_read_only) {
886         return -EACCES;
887     }
888
889     backing_drv = bs->backing_hd->drv;
890     ro = bs->backing_hd->read_only;
891     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
892     open_flags =  bs->backing_hd->open_flags;
893
894     if (ro) {
895         /* re-open as RW */
896         bdrv_delete(bs->backing_hd);
897         bs->backing_hd = NULL;
898         bs_rw = bdrv_new("");
899         rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
900             backing_drv);
901         if (rw_ret < 0) {
902             bdrv_delete(bs_rw);
903             /* try to re-open read-only */
904             bs_ro = bdrv_new("");
905             ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
906                 backing_drv);
907             if (ret < 0) {
908                 bdrv_delete(bs_ro);
909                 /* drive not functional anymore */
910                 bs->drv = NULL;
911                 return ret;
912             }
913             bs->backing_hd = bs_ro;
914             return rw_ret;
915         }
916         bs->backing_hd = bs_rw;
917     }
918
919     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
920     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
921
922     for (sector = 0; sector < total_sectors; sector += n) {
923         if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
924
925             if (bdrv_read(bs, sector, buf, n) != 0) {
926                 ret = -EIO;
927                 goto ro_cleanup;
928             }
929
930             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
931                 ret = -EIO;
932                 goto ro_cleanup;
933             }
934         }
935     }
936
937     if (drv->bdrv_make_empty) {
938         ret = drv->bdrv_make_empty(bs);
939         bdrv_flush(bs);
940     }
941
942     /*
943      * Make sure all data we wrote to the backing device is actually
944      * stable on disk.
945      */
946     if (bs->backing_hd)
947         bdrv_flush(bs->backing_hd);
948
949 ro_cleanup:
950     g_free(buf);
951
952     if (ro) {
953         /* re-open as RO */
954         bdrv_delete(bs->backing_hd);
955         bs->backing_hd = NULL;
956         bs_ro = bdrv_new("");
957         ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
958             backing_drv);
959         if (ret < 0) {
960             bdrv_delete(bs_ro);
961             /* drive not functional anymore */
962             bs->drv = NULL;
963             return ret;
964         }
965         bs->backing_hd = bs_ro;
966         bs->backing_hd->keep_read_only = 0;
967     }
968
969     return ret;
970 }
971
972 void bdrv_commit_all(void)
973 {
974     BlockDriverState *bs;
975
976     QTAILQ_FOREACH(bs, &bdrv_states, list) {
977         bdrv_commit(bs);
978     }
979 }
980
981 /*
982  * Return values:
983  * 0        - success
984  * -EINVAL  - backing format specified, but no file
985  * -ENOSPC  - can't update the backing file because no space is left in the
986  *            image file header
987  * -ENOTSUP - format driver doesn't support changing the backing file
988  */
989 int bdrv_change_backing_file(BlockDriverState *bs,
990     const char *backing_file, const char *backing_fmt)
991 {
992     BlockDriver *drv = bs->drv;
993
994     if (drv->bdrv_change_backing_file != NULL) {
995         return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
996     } else {
997         return -ENOTSUP;
998     }
999 }
1000
1001 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1002                                    size_t size)
1003 {
1004     int64_t len;
1005
1006     if (!bdrv_is_inserted(bs))
1007         return -ENOMEDIUM;
1008
1009     if (bs->growable)
1010         return 0;
1011
1012     len = bdrv_getlength(bs);
1013
1014     if (offset < 0)
1015         return -EIO;
1016
1017     if ((offset > len) || (len - offset < size))
1018         return -EIO;
1019
1020     return 0;
1021 }
1022
1023 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1024                               int nb_sectors)
1025 {
1026     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1027                                    nb_sectors * BDRV_SECTOR_SIZE);
1028 }
1029
1030 static inline bool bdrv_has_async_rw(BlockDriver *drv)
1031 {
1032     return drv->bdrv_co_readv != bdrv_co_readv_em
1033         || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1034 }
1035
1036 static inline bool bdrv_has_async_flush(BlockDriver *drv)
1037 {
1038     return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1039 }
1040
1041 /* return < 0 if error. See bdrv_write() for the return codes */
1042 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
1043               uint8_t *buf, int nb_sectors)
1044 {
1045     BlockDriver *drv = bs->drv;
1046
1047     if (!drv)
1048         return -ENOMEDIUM;
1049
1050     if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1051         QEMUIOVector qiov;
1052         struct iovec iov = {
1053             .iov_base = (void *)buf,
1054             .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1055         };
1056
1057         qemu_iovec_init_external(&qiov, &iov, 1);
1058         return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1059     }
1060
1061     if (bdrv_check_request(bs, sector_num, nb_sectors))
1062         return -EIO;
1063
1064     return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
1065 }
1066
1067 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
1068                              int nb_sectors, int dirty)
1069 {
1070     int64_t start, end;
1071     unsigned long val, idx, bit;
1072
1073     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1074     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
1075
1076     for (; start <= end; start++) {
1077         idx = start / (sizeof(unsigned long) * 8);
1078         bit = start % (sizeof(unsigned long) * 8);
1079         val = bs->dirty_bitmap[idx];
1080         if (dirty) {
1081             if (!(val & (1UL << bit))) {
1082                 bs->dirty_count++;
1083                 val |= 1UL << bit;
1084             }
1085         } else {
1086             if (val & (1UL << bit)) {
1087                 bs->dirty_count--;
1088                 val &= ~(1UL << bit);
1089             }
1090         }
1091         bs->dirty_bitmap[idx] = val;
1092     }
1093 }
1094
1095 /* Return < 0 if error. Important errors are:
1096   -EIO         generic I/O error (may happen for all errors)
1097   -ENOMEDIUM   No media inserted.
1098   -EINVAL      Invalid sector number or nb_sectors
1099   -EACCES      Trying to write a read-only device
1100 */
1101 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
1102                const uint8_t *buf, int nb_sectors)
1103 {
1104     BlockDriver *drv = bs->drv;
1105
1106     if (!bs->drv)
1107         return -ENOMEDIUM;
1108
1109     if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1110         QEMUIOVector qiov;
1111         struct iovec iov = {
1112             .iov_base = (void *)buf,
1113             .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1114         };
1115
1116         qemu_iovec_init_external(&qiov, &iov, 1);
1117         return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1118     }
1119
1120     if (bs->read_only)
1121         return -EACCES;
1122     if (bdrv_check_request(bs, sector_num, nb_sectors))
1123         return -EIO;
1124
1125     if (bs->dirty_bitmap) {
1126         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1127     }
1128
1129     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1130         bs->wr_highest_sector = sector_num + nb_sectors - 1;
1131     }
1132
1133     return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
1134 }
1135
1136 int bdrv_pread(BlockDriverState *bs, int64_t offset,
1137                void *buf, int count1)
1138 {
1139     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1140     int len, nb_sectors, count;
1141     int64_t sector_num;
1142     int ret;
1143
1144     count = count1;
1145     /* first read to align to sector start */
1146     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1147     if (len > count)
1148         len = count;
1149     sector_num = offset >> BDRV_SECTOR_BITS;
1150     if (len > 0) {
1151         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1152             return ret;
1153         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
1154         count -= len;
1155         if (count == 0)
1156             return count1;
1157         sector_num++;
1158         buf += len;
1159     }
1160
1161     /* read the sectors "in place" */
1162     nb_sectors = count >> BDRV_SECTOR_BITS;
1163     if (nb_sectors > 0) {
1164         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1165             return ret;
1166         sector_num += nb_sectors;
1167         len = nb_sectors << BDRV_SECTOR_BITS;
1168         buf += len;
1169         count -= len;
1170     }
1171
1172     /* add data from the last sector */
1173     if (count > 0) {
1174         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1175             return ret;
1176         memcpy(buf, tmp_buf, count);
1177     }
1178     return count1;
1179 }
1180
1181 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1182                 const void *buf, int count1)
1183 {
1184     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1185     int len, nb_sectors, count;
1186     int64_t sector_num;
1187     int ret;
1188
1189     count = count1;
1190     /* first write to align to sector start */
1191     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1192     if (len > count)
1193         len = count;
1194     sector_num = offset >> BDRV_SECTOR_BITS;
1195     if (len > 0) {
1196         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1197             return ret;
1198         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1199         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1200             return ret;
1201         count -= len;
1202         if (count == 0)
1203             return count1;
1204         sector_num++;
1205         buf += len;
1206     }
1207
1208     /* write the sectors "in place" */
1209     nb_sectors = count >> BDRV_SECTOR_BITS;
1210     if (nb_sectors > 0) {
1211         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1212             return ret;
1213         sector_num += nb_sectors;
1214         len = nb_sectors << BDRV_SECTOR_BITS;
1215         buf += len;
1216         count -= len;
1217     }
1218
1219     /* add data from the last sector */
1220     if (count > 0) {
1221         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1222             return ret;
1223         memcpy(tmp_buf, buf, count);
1224         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1225             return ret;
1226     }
1227     return count1;
1228 }
1229
1230 /*
1231  * Writes to the file and ensures that no writes are reordered across this
1232  * request (acts as a barrier)
1233  *
1234  * Returns 0 on success, -errno in error cases.
1235  */
1236 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1237     const void *buf, int count)
1238 {
1239     int ret;
1240
1241     ret = bdrv_pwrite(bs, offset, buf, count);
1242     if (ret < 0) {
1243         return ret;
1244     }
1245
1246     /* No flush needed for cache modes that use O_DSYNC */
1247     if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
1248         bdrv_flush(bs);
1249     }
1250
1251     return 0;
1252 }
1253
1254 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1255     int nb_sectors, QEMUIOVector *qiov)
1256 {
1257     BlockDriver *drv = bs->drv;
1258
1259     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1260
1261     if (!drv) {
1262         return -ENOMEDIUM;
1263     }
1264     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1265         return -EIO;
1266     }
1267
1268     return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1269 }
1270
1271 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1272     int nb_sectors, QEMUIOVector *qiov)
1273 {
1274     BlockDriver *drv = bs->drv;
1275
1276     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1277
1278     if (!bs->drv) {
1279         return -ENOMEDIUM;
1280     }
1281     if (bs->read_only) {
1282         return -EACCES;
1283     }
1284     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1285         return -EIO;
1286     }
1287
1288     if (bs->dirty_bitmap) {
1289         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1290     }
1291
1292     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1293         bs->wr_highest_sector = sector_num + nb_sectors - 1;
1294     }
1295
1296     return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1297 }
1298
1299 /**
1300  * Truncate file to 'offset' bytes (needed only for file protocols)
1301  */
1302 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1303 {
1304     BlockDriver *drv = bs->drv;
1305     int ret;
1306     if (!drv)
1307         return -ENOMEDIUM;
1308     if (!drv->bdrv_truncate)
1309         return -ENOTSUP;
1310     if (bs->read_only)
1311         return -EACCES;
1312     if (bdrv_in_use(bs))
1313         return -EBUSY;
1314     ret = drv->bdrv_truncate(bs, offset);
1315     if (ret == 0) {
1316         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1317         bdrv_dev_resize_cb(bs);
1318     }
1319     return ret;
1320 }
1321
1322 /**
1323  * Length of a allocated file in bytes. Sparse files are counted by actual
1324  * allocated space. Return < 0 if error or unknown.
1325  */
1326 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1327 {
1328     BlockDriver *drv = bs->drv;
1329     if (!drv) {
1330         return -ENOMEDIUM;
1331     }
1332     if (drv->bdrv_get_allocated_file_size) {
1333         return drv->bdrv_get_allocated_file_size(bs);
1334     }
1335     if (bs->file) {
1336         return bdrv_get_allocated_file_size(bs->file);
1337     }
1338     return -ENOTSUP;
1339 }
1340
1341 /**
1342  * Length of a file in bytes. Return < 0 if error or unknown.
1343  */
1344 int64_t bdrv_getlength(BlockDriverState *bs)
1345 {
1346     BlockDriver *drv = bs->drv;
1347     if (!drv)
1348         return -ENOMEDIUM;
1349
1350     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
1351         if (drv->bdrv_getlength) {
1352             return drv->bdrv_getlength(bs);
1353         }
1354     }
1355     return bs->total_sectors * BDRV_SECTOR_SIZE;
1356 }
1357
1358 /* return 0 as number of sectors if no device present or error */
1359 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1360 {
1361     int64_t length;
1362     length = bdrv_getlength(bs);
1363     if (length < 0)
1364         length = 0;
1365     else
1366         length = length >> BDRV_SECTOR_BITS;
1367     *nb_sectors_ptr = length;
1368 }
1369
1370 struct partition {
1371         uint8_t boot_ind;           /* 0x80 - active */
1372         uint8_t head;               /* starting head */
1373         uint8_t sector;             /* starting sector */
1374         uint8_t cyl;                /* starting cylinder */
1375         uint8_t sys_ind;            /* What partition type */
1376         uint8_t end_head;           /* end head */
1377         uint8_t end_sector;         /* end sector */
1378         uint8_t end_cyl;            /* end cylinder */
1379         uint32_t start_sect;        /* starting sector counting from 0 */
1380         uint32_t nr_sects;          /* nr of sectors in partition */
1381 } QEMU_PACKED;
1382
1383 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1384 static int guess_disk_lchs(BlockDriverState *bs,
1385                            int *pcylinders, int *pheads, int *psectors)
1386 {
1387     uint8_t buf[BDRV_SECTOR_SIZE];
1388     int ret, i, heads, sectors, cylinders;
1389     struct partition *p;
1390     uint32_t nr_sects;
1391     uint64_t nb_sectors;
1392
1393     bdrv_get_geometry(bs, &nb_sectors);
1394
1395     ret = bdrv_read(bs, 0, buf, 1);
1396     if (ret < 0)
1397         return -1;
1398     /* test msdos magic */
1399     if (buf[510] != 0x55 || buf[511] != 0xaa)
1400         return -1;
1401     for(i = 0; i < 4; i++) {
1402         p = ((struct partition *)(buf + 0x1be)) + i;
1403         nr_sects = le32_to_cpu(p->nr_sects);
1404         if (nr_sects && p->end_head) {
1405             /* We make the assumption that the partition terminates on
1406                a cylinder boundary */
1407             heads = p->end_head + 1;
1408             sectors = p->end_sector & 63;
1409             if (sectors == 0)
1410                 continue;
1411             cylinders = nb_sectors / (heads * sectors);
1412             if (cylinders < 1 || cylinders > 16383)
1413                 continue;
1414             *pheads = heads;
1415             *psectors = sectors;
1416             *pcylinders = cylinders;
1417 #if 0
1418             printf("guessed geometry: LCHS=%d %d %d\n",
1419                    cylinders, heads, sectors);
1420 #endif
1421             return 0;
1422         }
1423     }
1424     return -1;
1425 }
1426
1427 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1428 {
1429     int translation, lba_detected = 0;
1430     int cylinders, heads, secs;
1431     uint64_t nb_sectors;
1432
1433     /* if a geometry hint is available, use it */
1434     bdrv_get_geometry(bs, &nb_sectors);
1435     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1436     translation = bdrv_get_translation_hint(bs);
1437     if (cylinders != 0) {
1438         *pcyls = cylinders;
1439         *pheads = heads;
1440         *psecs = secs;
1441     } else {
1442         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1443             if (heads > 16) {
1444                 /* if heads > 16, it means that a BIOS LBA
1445                    translation was active, so the default
1446                    hardware geometry is OK */
1447                 lba_detected = 1;
1448                 goto default_geometry;
1449             } else {
1450                 *pcyls = cylinders;
1451                 *pheads = heads;
1452                 *psecs = secs;
1453                 /* disable any translation to be in sync with
1454                    the logical geometry */
1455                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1456                     bdrv_set_translation_hint(bs,
1457                                               BIOS_ATA_TRANSLATION_NONE);
1458                 }
1459             }
1460         } else {
1461         default_geometry:
1462             /* if no geometry, use a standard physical disk geometry */
1463             cylinders = nb_sectors / (16 * 63);
1464
1465             if (cylinders > 16383)
1466                 cylinders = 16383;
1467             else if (cylinders < 2)
1468                 cylinders = 2;
1469             *pcyls = cylinders;
1470             *pheads = 16;
1471             *psecs = 63;
1472             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1473                 if ((*pcyls * *pheads) <= 131072) {
1474                     bdrv_set_translation_hint(bs,
1475                                               BIOS_ATA_TRANSLATION_LARGE);
1476                 } else {
1477                     bdrv_set_translation_hint(bs,
1478                                               BIOS_ATA_TRANSLATION_LBA);
1479                 }
1480             }
1481         }
1482         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1483     }
1484 }
1485
1486 void bdrv_set_geometry_hint(BlockDriverState *bs,
1487                             int cyls, int heads, int secs)
1488 {
1489     bs->cyls = cyls;
1490     bs->heads = heads;
1491     bs->secs = secs;
1492 }
1493
1494 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1495 {
1496     bs->translation = translation;
1497 }
1498
1499 void bdrv_get_geometry_hint(BlockDriverState *bs,
1500                             int *pcyls, int *pheads, int *psecs)
1501 {
1502     *pcyls = bs->cyls;
1503     *pheads = bs->heads;
1504     *psecs = bs->secs;
1505 }
1506
1507 /* Recognize floppy formats */
1508 typedef struct FDFormat {
1509     FDriveType drive;
1510     uint8_t last_sect;
1511     uint8_t max_track;
1512     uint8_t max_head;
1513 } FDFormat;
1514
1515 static const FDFormat fd_formats[] = {
1516     /* First entry is default format */
1517     /* 1.44 MB 3"1/2 floppy disks */
1518     { FDRIVE_DRV_144, 18, 80, 1, },
1519     { FDRIVE_DRV_144, 20, 80, 1, },
1520     { FDRIVE_DRV_144, 21, 80, 1, },
1521     { FDRIVE_DRV_144, 21, 82, 1, },
1522     { FDRIVE_DRV_144, 21, 83, 1, },
1523     { FDRIVE_DRV_144, 22, 80, 1, },
1524     { FDRIVE_DRV_144, 23, 80, 1, },
1525     { FDRIVE_DRV_144, 24, 80, 1, },
1526     /* 2.88 MB 3"1/2 floppy disks */
1527     { FDRIVE_DRV_288, 36, 80, 1, },
1528     { FDRIVE_DRV_288, 39, 80, 1, },
1529     { FDRIVE_DRV_288, 40, 80, 1, },
1530     { FDRIVE_DRV_288, 44, 80, 1, },
1531     { FDRIVE_DRV_288, 48, 80, 1, },
1532     /* 720 kB 3"1/2 floppy disks */
1533     { FDRIVE_DRV_144,  9, 80, 1, },
1534     { FDRIVE_DRV_144, 10, 80, 1, },
1535     { FDRIVE_DRV_144, 10, 82, 1, },
1536     { FDRIVE_DRV_144, 10, 83, 1, },
1537     { FDRIVE_DRV_144, 13, 80, 1, },
1538     { FDRIVE_DRV_144, 14, 80, 1, },
1539     /* 1.2 MB 5"1/4 floppy disks */
1540     { FDRIVE_DRV_120, 15, 80, 1, },
1541     { FDRIVE_DRV_120, 18, 80, 1, },
1542     { FDRIVE_DRV_120, 18, 82, 1, },
1543     { FDRIVE_DRV_120, 18, 83, 1, },
1544     { FDRIVE_DRV_120, 20, 80, 1, },
1545     /* 720 kB 5"1/4 floppy disks */
1546     { FDRIVE_DRV_120,  9, 80, 1, },
1547     { FDRIVE_DRV_120, 11, 80, 1, },
1548     /* 360 kB 5"1/4 floppy disks */
1549     { FDRIVE_DRV_120,  9, 40, 1, },
1550     { FDRIVE_DRV_120,  9, 40, 0, },
1551     { FDRIVE_DRV_120, 10, 41, 1, },
1552     { FDRIVE_DRV_120, 10, 42, 1, },
1553     /* 320 kB 5"1/4 floppy disks */
1554     { FDRIVE_DRV_120,  8, 40, 1, },
1555     { FDRIVE_DRV_120,  8, 40, 0, },
1556     /* 360 kB must match 5"1/4 better than 3"1/2... */
1557     { FDRIVE_DRV_144,  9, 80, 0, },
1558     /* end */
1559     { FDRIVE_DRV_NONE, -1, -1, 0, },
1560 };
1561
1562 void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1563                                    int *max_track, int *last_sect,
1564                                    FDriveType drive_in, FDriveType *drive)
1565 {
1566     const FDFormat *parse;
1567     uint64_t nb_sectors, size;
1568     int i, first_match, match;
1569
1570     bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1571     if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1572         /* User defined disk */
1573     } else {
1574         bdrv_get_geometry(bs, &nb_sectors);
1575         match = -1;
1576         first_match = -1;
1577         for (i = 0; ; i++) {
1578             parse = &fd_formats[i];
1579             if (parse->drive == FDRIVE_DRV_NONE) {
1580                 break;
1581             }
1582             if (drive_in == parse->drive ||
1583                 drive_in == FDRIVE_DRV_NONE) {
1584                 size = (parse->max_head + 1) * parse->max_track *
1585                     parse->last_sect;
1586                 if (nb_sectors == size) {
1587                     match = i;
1588                     break;
1589                 }
1590                 if (first_match == -1) {
1591                     first_match = i;
1592                 }
1593             }
1594         }
1595         if (match == -1) {
1596             if (first_match == -1) {
1597                 match = 1;
1598             } else {
1599                 match = first_match;
1600             }
1601             parse = &fd_formats[match];
1602         }
1603         *nb_heads = parse->max_head + 1;
1604         *max_track = parse->max_track;
1605         *last_sect = parse->last_sect;
1606         *drive = parse->drive;
1607     }
1608 }
1609
1610 int bdrv_get_translation_hint(BlockDriverState *bs)
1611 {
1612     return bs->translation;
1613 }
1614
1615 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1616                        BlockErrorAction on_write_error)
1617 {
1618     bs->on_read_error = on_read_error;
1619     bs->on_write_error = on_write_error;
1620 }
1621
1622 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1623 {
1624     return is_read ? bs->on_read_error : bs->on_write_error;
1625 }
1626
1627 int bdrv_is_read_only(BlockDriverState *bs)
1628 {
1629     return bs->read_only;
1630 }
1631
1632 int bdrv_is_sg(BlockDriverState *bs)
1633 {
1634     return bs->sg;
1635 }
1636
1637 int bdrv_enable_write_cache(BlockDriverState *bs)
1638 {
1639     return bs->enable_write_cache;
1640 }
1641
1642 int bdrv_is_encrypted(BlockDriverState *bs)
1643 {
1644     if (bs->backing_hd && bs->backing_hd->encrypted)
1645         return 1;
1646     return bs->encrypted;
1647 }
1648
1649 int bdrv_key_required(BlockDriverState *bs)
1650 {
1651     BlockDriverState *backing_hd = bs->backing_hd;
1652
1653     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1654         return 1;
1655     return (bs->encrypted && !bs->valid_key);
1656 }
1657
1658 int bdrv_set_key(BlockDriverState *bs, const char *key)
1659 {
1660     int ret;
1661     if (bs->backing_hd && bs->backing_hd->encrypted) {
1662         ret = bdrv_set_key(bs->backing_hd, key);
1663         if (ret < 0)
1664             return ret;
1665         if (!bs->encrypted)
1666             return 0;
1667     }
1668     if (!bs->encrypted) {
1669         return -EINVAL;
1670     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1671         return -ENOMEDIUM;
1672     }
1673     ret = bs->drv->bdrv_set_key(bs, key);
1674     if (ret < 0) {
1675         bs->valid_key = 0;
1676     } else if (!bs->valid_key) {
1677         bs->valid_key = 1;
1678         /* call the change callback now, we skipped it on open */
1679         bdrv_dev_change_media_cb(bs, true);
1680     }
1681     return ret;
1682 }
1683
1684 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1685 {
1686     if (!bs->drv) {
1687         buf[0] = '\0';
1688     } else {
1689         pstrcpy(buf, buf_size, bs->drv->format_name);
1690     }
1691 }
1692
1693 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1694                          void *opaque)
1695 {
1696     BlockDriver *drv;
1697
1698     QLIST_FOREACH(drv, &bdrv_drivers, list) {
1699         it(opaque, drv->format_name);
1700     }
1701 }
1702
1703 BlockDriverState *bdrv_find(const char *name)
1704 {
1705     BlockDriverState *bs;
1706
1707     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1708         if (!strcmp(name, bs->device_name)) {
1709             return bs;
1710         }
1711     }
1712     return NULL;
1713 }
1714
1715 BlockDriverState *bdrv_next(BlockDriverState *bs)
1716 {
1717     if (!bs) {
1718         return QTAILQ_FIRST(&bdrv_states);
1719     }
1720     return QTAILQ_NEXT(bs, list);
1721 }
1722
1723 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1724 {
1725     BlockDriverState *bs;
1726
1727     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1728         it(opaque, bs);
1729     }
1730 }
1731
1732 const char *bdrv_get_device_name(BlockDriverState *bs)
1733 {
1734     return bs->device_name;
1735 }
1736
1737 int bdrv_flush(BlockDriverState *bs)
1738 {
1739     if (bs->open_flags & BDRV_O_NO_FLUSH) {
1740         return 0;
1741     }
1742
1743     if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1744         return bdrv_co_flush_em(bs);
1745     }
1746
1747     if (bs->drv && bs->drv->bdrv_flush) {
1748         return bs->drv->bdrv_flush(bs);
1749     }
1750
1751     /*
1752      * Some block drivers always operate in either writethrough or unsafe mode
1753      * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1754      * the server works (because the behaviour is hardcoded or depends on
1755      * server-side configuration), so we can't ensure that everything is safe
1756      * on disk. Returning an error doesn't work because that would break guests
1757      * even if the server operates in writethrough mode.
1758      *
1759      * Let's hope the user knows what he's doing.
1760      */
1761     return 0;
1762 }
1763
1764 void bdrv_flush_all(void)
1765 {
1766     BlockDriverState *bs;
1767
1768     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1769         if (!bdrv_is_read_only(bs) && bdrv_is_inserted(bs)) {
1770             bdrv_flush(bs);
1771         }
1772     }
1773 }
1774
1775 int bdrv_has_zero_init(BlockDriverState *bs)
1776 {
1777     assert(bs->drv);
1778
1779     if (bs->drv->bdrv_has_zero_init) {
1780         return bs->drv->bdrv_has_zero_init(bs);
1781     }
1782
1783     return 1;
1784 }
1785
1786 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1787 {
1788     if (!bs->drv) {
1789         return -ENOMEDIUM;
1790     }
1791     if (!bs->drv->bdrv_discard) {
1792         return 0;
1793     }
1794     return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1795 }
1796
1797 /*
1798  * Returns true iff the specified sector is present in the disk image. Drivers
1799  * not implementing the functionality are assumed to not support backing files,
1800  * hence all their sectors are reported as allocated.
1801  *
1802  * 'pnum' is set to the number of sectors (including and immediately following
1803  * the specified sector) that are known to be in the same
1804  * allocated/unallocated state.
1805  *
1806  * 'nb_sectors' is the max value 'pnum' should be set to.
1807  */
1808 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1809         int *pnum)
1810 {
1811     int64_t n;
1812     if (!bs->drv->bdrv_is_allocated) {
1813         if (sector_num >= bs->total_sectors) {
1814             *pnum = 0;
1815             return 0;
1816         }
1817         n = bs->total_sectors - sector_num;
1818         *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1819         return 1;
1820     }
1821     return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1822 }
1823
1824 void bdrv_mon_event(const BlockDriverState *bdrv,
1825                     BlockMonEventAction action, int is_read)
1826 {
1827     QObject *data;
1828     const char *action_str;
1829
1830     switch (action) {
1831     case BDRV_ACTION_REPORT:
1832         action_str = "report";
1833         break;
1834     case BDRV_ACTION_IGNORE:
1835         action_str = "ignore";
1836         break;
1837     case BDRV_ACTION_STOP:
1838         action_str = "stop";
1839         break;
1840     default:
1841         abort();
1842     }
1843
1844     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1845                               bdrv->device_name,
1846                               action_str,
1847                               is_read ? "read" : "write");
1848     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1849
1850     qobject_decref(data);
1851 }
1852
1853 static void bdrv_print_dict(QObject *obj, void *opaque)
1854 {
1855     QDict *bs_dict;
1856     Monitor *mon = opaque;
1857
1858     bs_dict = qobject_to_qdict(obj);
1859
1860     monitor_printf(mon, "%s: removable=%d",
1861                         qdict_get_str(bs_dict, "device"),
1862                         qdict_get_bool(bs_dict, "removable"));
1863
1864     if (qdict_get_bool(bs_dict, "removable")) {
1865         monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1866         monitor_printf(mon, " tray-open=%d",
1867                        qdict_get_bool(bs_dict, "tray-open"));
1868     }
1869     if (qdict_haskey(bs_dict, "inserted")) {
1870         QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1871
1872         monitor_printf(mon, " file=");
1873         monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1874         if (qdict_haskey(qdict, "backing_file")) {
1875             monitor_printf(mon, " backing_file=");
1876             monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1877         }
1878         monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1879                             qdict_get_bool(qdict, "ro"),
1880                             qdict_get_str(qdict, "drv"),
1881                             qdict_get_bool(qdict, "encrypted"));
1882     } else {
1883         monitor_printf(mon, " [not inserted]");
1884     }
1885
1886     monitor_printf(mon, "\n");
1887 }
1888
1889 void bdrv_info_print(Monitor *mon, const QObject *data)
1890 {
1891     qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1892 }
1893
1894 void bdrv_info(Monitor *mon, QObject **ret_data)
1895 {
1896     QList *bs_list;
1897     BlockDriverState *bs;
1898
1899     bs_list = qlist_new();
1900
1901     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1902         QObject *bs_obj;
1903         QDict *bs_dict;
1904
1905         bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1906                                     "'removable': %i, 'locked': %i }",
1907                                     bs->device_name,
1908                                     bdrv_dev_has_removable_media(bs),
1909                                     bdrv_dev_is_medium_locked(bs));
1910         bs_dict = qobject_to_qdict(bs_obj);
1911
1912         if (bdrv_dev_has_removable_media(bs)) {
1913             qdict_put(bs_dict, "tray-open",
1914                       qbool_from_int(bdrv_dev_is_tray_open(bs)));
1915         }
1916         if (bs->drv) {
1917             QObject *obj;
1918
1919             obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1920                                      "'encrypted': %i }",
1921                                      bs->filename, bs->read_only,
1922                                      bs->drv->format_name,
1923                                      bdrv_is_encrypted(bs));
1924             if (bs->backing_file[0] != '\0') {
1925                 QDict *qdict = qobject_to_qdict(obj);
1926                 qdict_put(qdict, "backing_file",
1927                           qstring_from_str(bs->backing_file));
1928             }
1929
1930             qdict_put_obj(bs_dict, "inserted", obj);
1931         }
1932         qlist_append_obj(bs_list, bs_obj);
1933     }
1934
1935     *ret_data = QOBJECT(bs_list);
1936 }
1937
1938 static void bdrv_stats_iter(QObject *data, void *opaque)
1939 {
1940     QDict *qdict;
1941     Monitor *mon = opaque;
1942
1943     qdict = qobject_to_qdict(data);
1944     monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1945
1946     qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1947     monitor_printf(mon, " rd_bytes=%" PRId64
1948                         " wr_bytes=%" PRId64
1949                         " rd_operations=%" PRId64
1950                         " wr_operations=%" PRId64
1951                         " flush_operations=%" PRId64
1952                         " wr_total_time_ns=%" PRId64
1953                         " rd_total_time_ns=%" PRId64
1954                         " flush_total_time_ns=%" PRId64
1955                         "\n",
1956                         qdict_get_int(qdict, "rd_bytes"),
1957                         qdict_get_int(qdict, "wr_bytes"),
1958                         qdict_get_int(qdict, "rd_operations"),
1959                         qdict_get_int(qdict, "wr_operations"),
1960                         qdict_get_int(qdict, "flush_operations"),
1961                         qdict_get_int(qdict, "wr_total_time_ns"),
1962                         qdict_get_int(qdict, "rd_total_time_ns"),
1963                         qdict_get_int(qdict, "flush_total_time_ns"));
1964 }
1965
1966 void bdrv_stats_print(Monitor *mon, const QObject *data)
1967 {
1968     qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1969 }
1970
1971 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1972 {
1973     QObject *res;
1974     QDict *dict;
1975
1976     res = qobject_from_jsonf("{ 'stats': {"
1977                              "'rd_bytes': %" PRId64 ","
1978                              "'wr_bytes': %" PRId64 ","
1979                              "'rd_operations': %" PRId64 ","
1980                              "'wr_operations': %" PRId64 ","
1981                              "'wr_highest_offset': %" PRId64 ","
1982                              "'flush_operations': %" PRId64 ","
1983                              "'wr_total_time_ns': %" PRId64 ","
1984                              "'rd_total_time_ns': %" PRId64 ","
1985                              "'flush_total_time_ns': %" PRId64
1986                              "} }",
1987                              bs->nr_bytes[BDRV_ACCT_READ],
1988                              bs->nr_bytes[BDRV_ACCT_WRITE],
1989                              bs->nr_ops[BDRV_ACCT_READ],
1990                              bs->nr_ops[BDRV_ACCT_WRITE],
1991                              bs->wr_highest_sector *
1992                              (uint64_t)BDRV_SECTOR_SIZE,
1993                              bs->nr_ops[BDRV_ACCT_FLUSH],
1994                              bs->total_time_ns[BDRV_ACCT_WRITE],
1995                              bs->total_time_ns[BDRV_ACCT_READ],
1996                              bs->total_time_ns[BDRV_ACCT_FLUSH]);
1997     dict  = qobject_to_qdict(res);
1998
1999     if (*bs->device_name) {
2000         qdict_put(dict, "device", qstring_from_str(bs->device_name));
2001     }
2002
2003     if (bs->file) {
2004         QObject *parent = bdrv_info_stats_bs(bs->file);
2005         qdict_put_obj(dict, "parent", parent);
2006     }
2007
2008     return res;
2009 }
2010
2011 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
2012 {
2013     QObject *obj;
2014     QList *devices;
2015     BlockDriverState *bs;
2016
2017     devices = qlist_new();
2018
2019     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2020         obj = bdrv_info_stats_bs(bs);
2021         qlist_append_obj(devices, obj);
2022     }
2023
2024     *ret_data = QOBJECT(devices);
2025 }
2026
2027 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2028 {
2029     if (bs->backing_hd && bs->backing_hd->encrypted)
2030         return bs->backing_file;
2031     else if (bs->encrypted)
2032         return bs->filename;
2033     else
2034         return NULL;
2035 }
2036
2037 void bdrv_get_backing_filename(BlockDriverState *bs,
2038                                char *filename, int filename_size)
2039 {
2040     if (!bs->backing_file) {
2041         pstrcpy(filename, filename_size, "");
2042     } else {
2043         pstrcpy(filename, filename_size, bs->backing_file);
2044     }
2045 }
2046
2047 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2048                           const uint8_t *buf, int nb_sectors)
2049 {
2050     BlockDriver *drv = bs->drv;
2051     if (!drv)
2052         return -ENOMEDIUM;
2053     if (!drv->bdrv_write_compressed)
2054         return -ENOTSUP;
2055     if (bdrv_check_request(bs, sector_num, nb_sectors))
2056         return -EIO;
2057
2058     if (bs->dirty_bitmap) {
2059         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2060     }
2061
2062     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2063 }
2064
2065 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2066 {
2067     BlockDriver *drv = bs->drv;
2068     if (!drv)
2069         return -ENOMEDIUM;
2070     if (!drv->bdrv_get_info)
2071         return -ENOTSUP;
2072     memset(bdi, 0, sizeof(*bdi));
2073     return drv->bdrv_get_info(bs, bdi);
2074 }
2075
2076 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2077                       int64_t pos, int size)
2078 {
2079     BlockDriver *drv = bs->drv;
2080     if (!drv)
2081         return -ENOMEDIUM;
2082     if (drv->bdrv_save_vmstate)
2083         return drv->bdrv_save_vmstate(bs, buf, pos, size);
2084     if (bs->file)
2085         return bdrv_save_vmstate(bs->file, buf, pos, size);
2086     return -ENOTSUP;
2087 }
2088
2089 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2090                       int64_t pos, int size)
2091 {
2092     BlockDriver *drv = bs->drv;
2093     if (!drv)
2094         return -ENOMEDIUM;
2095     if (drv->bdrv_load_vmstate)
2096         return drv->bdrv_load_vmstate(bs, buf, pos, size);
2097     if (bs->file)
2098         return bdrv_load_vmstate(bs->file, buf, pos, size);
2099     return -ENOTSUP;
2100 }
2101
2102 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2103 {
2104     BlockDriver *drv = bs->drv;
2105
2106     if (!drv || !drv->bdrv_debug_event) {
2107         return;
2108     }
2109
2110     return drv->bdrv_debug_event(bs, event);
2111
2112 }
2113
2114 /**************************************************************/
2115 /* handling of snapshots */
2116
2117 int bdrv_can_snapshot(BlockDriverState *bs)
2118 {
2119     BlockDriver *drv = bs->drv;
2120     if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2121         return 0;
2122     }
2123
2124     if (!drv->bdrv_snapshot_create) {
2125         if (bs->file != NULL) {
2126             return bdrv_can_snapshot(bs->file);
2127         }
2128         return 0;
2129     }
2130
2131     return 1;
2132 }
2133
2134 int bdrv_is_snapshot(BlockDriverState *bs)
2135 {
2136     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2137 }
2138
2139 BlockDriverState *bdrv_snapshots(void)
2140 {
2141     BlockDriverState *bs;
2142
2143     if (bs_snapshots) {
2144         return bs_snapshots;
2145     }
2146
2147     bs = NULL;
2148     while ((bs = bdrv_next(bs))) {
2149         if (bdrv_can_snapshot(bs)) {
2150             bs_snapshots = bs;
2151             return bs;
2152         }
2153     }
2154     return NULL;
2155 }
2156
2157 int bdrv_snapshot_create(BlockDriverState *bs,
2158                          QEMUSnapshotInfo *sn_info)
2159 {
2160     BlockDriver *drv = bs->drv;
2161     if (!drv)
2162         return -ENOMEDIUM;
2163     if (drv->bdrv_snapshot_create)
2164         return drv->bdrv_snapshot_create(bs, sn_info);
2165     if (bs->file)
2166         return bdrv_snapshot_create(bs->file, sn_info);
2167     return -ENOTSUP;
2168 }
2169
2170 int bdrv_snapshot_goto(BlockDriverState *bs,
2171                        const char *snapshot_id)
2172 {
2173     BlockDriver *drv = bs->drv;
2174     int ret, open_ret;
2175
2176     if (!drv)
2177         return -ENOMEDIUM;
2178     if (drv->bdrv_snapshot_goto)
2179         return drv->bdrv_snapshot_goto(bs, snapshot_id);
2180
2181     if (bs->file) {
2182         drv->bdrv_close(bs);
2183         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2184         open_ret = drv->bdrv_open(bs, bs->open_flags);
2185         if (open_ret < 0) {
2186             bdrv_delete(bs->file);
2187             bs->drv = NULL;
2188             return open_ret;
2189         }
2190         return ret;
2191     }
2192
2193     return -ENOTSUP;
2194 }
2195
2196 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2197 {
2198     BlockDriver *drv = bs->drv;
2199     if (!drv)
2200         return -ENOMEDIUM;
2201     if (drv->bdrv_snapshot_delete)
2202         return drv->bdrv_snapshot_delete(bs, snapshot_id);
2203     if (bs->file)
2204         return bdrv_snapshot_delete(bs->file, snapshot_id);
2205     return -ENOTSUP;
2206 }
2207
2208 int bdrv_snapshot_list(BlockDriverState *bs,
2209                        QEMUSnapshotInfo **psn_info)
2210 {
2211     BlockDriver *drv = bs->drv;
2212     if (!drv)
2213         return -ENOMEDIUM;
2214     if (drv->bdrv_snapshot_list)
2215         return drv->bdrv_snapshot_list(bs, psn_info);
2216     if (bs->file)
2217         return bdrv_snapshot_list(bs->file, psn_info);
2218     return -ENOTSUP;
2219 }
2220
2221 int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2222         const char *snapshot_name)
2223 {
2224     BlockDriver *drv = bs->drv;
2225     if (!drv) {
2226         return -ENOMEDIUM;
2227     }
2228     if (!bs->read_only) {
2229         return -EINVAL;
2230     }
2231     if (drv->bdrv_snapshot_load_tmp) {
2232         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2233     }
2234     return -ENOTSUP;
2235 }
2236
2237 #define NB_SUFFIXES 4
2238
2239 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2240 {
2241     static const char suffixes[NB_SUFFIXES] = "KMGT";
2242     int64_t base;
2243     int i;
2244
2245     if (size <= 999) {
2246         snprintf(buf, buf_size, "%" PRId64, size);
2247     } else {
2248         base = 1024;
2249         for(i = 0; i < NB_SUFFIXES; i++) {
2250             if (size < (10 * base)) {
2251                 snprintf(buf, buf_size, "%0.1f%c",
2252                          (double)size / base,
2253                          suffixes[i]);
2254                 break;
2255             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2256                 snprintf(buf, buf_size, "%" PRId64 "%c",
2257                          ((size + (base >> 1)) / base),
2258                          suffixes[i]);
2259                 break;
2260             }
2261             base = base * 1024;
2262         }
2263     }
2264     return buf;
2265 }
2266
2267 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2268 {
2269     char buf1[128], date_buf[128], clock_buf[128];
2270 #ifdef _WIN32
2271     struct tm *ptm;
2272 #else
2273     struct tm tm;
2274 #endif
2275     time_t ti;
2276     int64_t secs;
2277
2278     if (!sn) {
2279         snprintf(buf, buf_size,
2280                  "%-10s%-20s%7s%20s%15s",
2281                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2282     } else {
2283         ti = sn->date_sec;
2284 #ifdef _WIN32
2285         ptm = localtime(&ti);
2286         strftime(date_buf, sizeof(date_buf),
2287                  "%Y-%m-%d %H:%M:%S", ptm);
2288 #else
2289         localtime_r(&ti, &tm);
2290         strftime(date_buf, sizeof(date_buf),
2291                  "%Y-%m-%d %H:%M:%S", &tm);
2292 #endif
2293         secs = sn->vm_clock_nsec / 1000000000;
2294         snprintf(clock_buf, sizeof(clock_buf),
2295                  "%02d:%02d:%02d.%03d",
2296                  (int)(secs / 3600),
2297                  (int)((secs / 60) % 60),
2298                  (int)(secs % 60),
2299                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
2300         snprintf(buf, buf_size,
2301                  "%-10s%-20s%7s%20s%15s",
2302                  sn->id_str, sn->name,
2303                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2304                  date_buf,
2305                  clock_buf);
2306     }
2307     return buf;
2308 }
2309
2310 /**************************************************************/
2311 /* async I/Os */
2312
2313 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2314                                  QEMUIOVector *qiov, int nb_sectors,
2315                                  BlockDriverCompletionFunc *cb, void *opaque)
2316 {
2317     BlockDriver *drv = bs->drv;
2318
2319     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2320
2321     if (!drv)
2322         return NULL;
2323     if (bdrv_check_request(bs, sector_num, nb_sectors))
2324         return NULL;
2325
2326     return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2327                                cb, opaque);
2328 }
2329
2330 typedef struct BlockCompleteData {
2331     BlockDriverCompletionFunc *cb;
2332     void *opaque;
2333     BlockDriverState *bs;
2334     int64_t sector_num;
2335     int nb_sectors;
2336 } BlockCompleteData;
2337
2338 static void block_complete_cb(void *opaque, int ret)
2339 {
2340     BlockCompleteData *b = opaque;
2341
2342     if (b->bs->dirty_bitmap) {
2343         set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2344     }
2345     b->cb(b->opaque, ret);
2346     g_free(b);
2347 }
2348
2349 static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2350                                              int64_t sector_num,
2351                                              int nb_sectors,
2352                                              BlockDriverCompletionFunc *cb,
2353                                              void *opaque)
2354 {
2355     BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
2356
2357     blkdata->bs = bs;
2358     blkdata->cb = cb;
2359     blkdata->opaque = opaque;
2360     blkdata->sector_num = sector_num;
2361     blkdata->nb_sectors = nb_sectors;
2362
2363     return blkdata;
2364 }
2365
2366 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2367                                   QEMUIOVector *qiov, int nb_sectors,
2368                                   BlockDriverCompletionFunc *cb, void *opaque)
2369 {
2370     BlockDriver *drv = bs->drv;
2371     BlockDriverAIOCB *ret;
2372     BlockCompleteData *blk_cb_data;
2373
2374     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2375
2376     if (!drv)
2377         return NULL;
2378     if (bs->read_only)
2379         return NULL;
2380     if (bdrv_check_request(bs, sector_num, nb_sectors))
2381         return NULL;
2382
2383     if (bs->dirty_bitmap) {
2384         blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2385                                          opaque);
2386         cb = &block_complete_cb;
2387         opaque = blk_cb_data;
2388     }
2389
2390     ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2391                                cb, opaque);
2392
2393     if (ret) {
2394         if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2395             bs->wr_highest_sector = sector_num + nb_sectors - 1;
2396         }
2397     }
2398
2399     return ret;
2400 }
2401
2402
2403 typedef struct MultiwriteCB {
2404     int error;
2405     int num_requests;
2406     int num_callbacks;
2407     struct {
2408         BlockDriverCompletionFunc *cb;
2409         void *opaque;
2410         QEMUIOVector *free_qiov;
2411         void *free_buf;
2412     } callbacks[];
2413 } MultiwriteCB;
2414
2415 static void multiwrite_user_cb(MultiwriteCB *mcb)
2416 {
2417     int i;
2418
2419     for (i = 0; i < mcb->num_callbacks; i++) {
2420         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2421         if (mcb->callbacks[i].free_qiov) {
2422             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2423         }
2424         g_free(mcb->callbacks[i].free_qiov);
2425         qemu_vfree(mcb->callbacks[i].free_buf);
2426     }
2427 }
2428
2429 static void multiwrite_cb(void *opaque, int ret)
2430 {
2431     MultiwriteCB *mcb = opaque;
2432
2433     trace_multiwrite_cb(mcb, ret);
2434
2435     if (ret < 0 && !mcb->error) {
2436         mcb->error = ret;
2437     }
2438
2439     mcb->num_requests--;
2440     if (mcb->num_requests == 0) {
2441         multiwrite_user_cb(mcb);
2442         g_free(mcb);
2443     }
2444 }
2445
2446 static int multiwrite_req_compare(const void *a, const void *b)
2447 {
2448     const BlockRequest *req1 = a, *req2 = b;
2449
2450     /*
2451      * Note that we can't simply subtract req2->sector from req1->sector
2452      * here as that could overflow the return value.
2453      */
2454     if (req1->sector > req2->sector) {
2455         return 1;
2456     } else if (req1->sector < req2->sector) {
2457         return -1;
2458     } else {
2459         return 0;
2460     }
2461 }
2462
2463 /*
2464  * Takes a bunch of requests and tries to merge them. Returns the number of
2465  * requests that remain after merging.
2466  */
2467 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2468     int num_reqs, MultiwriteCB *mcb)
2469 {
2470     int i, outidx;
2471
2472     // Sort requests by start sector
2473     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2474
2475     // Check if adjacent requests touch the same clusters. If so, combine them,
2476     // filling up gaps with zero sectors.
2477     outidx = 0;
2478     for (i = 1; i < num_reqs; i++) {
2479         int merge = 0;
2480         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2481
2482         // This handles the cases that are valid for all block drivers, namely
2483         // exactly sequential writes and overlapping writes.
2484         if (reqs[i].sector <= oldreq_last) {
2485             merge = 1;
2486         }
2487
2488         // The block driver may decide that it makes sense to combine requests
2489         // even if there is a gap of some sectors between them. In this case,
2490         // the gap is filled with zeros (therefore only applicable for yet
2491         // unused space in format like qcow2).
2492         if (!merge && bs->drv->bdrv_merge_requests) {
2493             merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2494         }
2495
2496         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2497             merge = 0;
2498         }
2499
2500         if (merge) {
2501             size_t size;
2502             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
2503             qemu_iovec_init(qiov,
2504                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2505
2506             // Add the first request to the merged one. If the requests are
2507             // overlapping, drop the last sectors of the first request.
2508             size = (reqs[i].sector - reqs[outidx].sector) << 9;
2509             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2510
2511             // We might need to add some zeros between the two requests
2512             if (reqs[i].sector > oldreq_last) {
2513                 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2514                 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2515                 memset(buf, 0, zero_bytes);
2516                 qemu_iovec_add(qiov, buf, zero_bytes);
2517                 mcb->callbacks[i].free_buf = buf;
2518             }
2519
2520             // Add the second request
2521             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2522
2523             reqs[outidx].nb_sectors = qiov->size >> 9;
2524             reqs[outidx].qiov = qiov;
2525
2526             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2527         } else {
2528             outidx++;
2529             reqs[outidx].sector     = reqs[i].sector;
2530             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2531             reqs[outidx].qiov       = reqs[i].qiov;
2532         }
2533     }
2534
2535     return outidx + 1;
2536 }
2537
2538 /*
2539  * Submit multiple AIO write requests at once.
2540  *
2541  * On success, the function returns 0 and all requests in the reqs array have
2542  * been submitted. In error case this function returns -1, and any of the
2543  * requests may or may not be submitted yet. In particular, this means that the
2544  * callback will be called for some of the requests, for others it won't. The
2545  * caller must check the error field of the BlockRequest to wait for the right
2546  * callbacks (if error != 0, no callback will be called).
2547  *
2548  * The implementation may modify the contents of the reqs array, e.g. to merge
2549  * requests. However, the fields opaque and error are left unmodified as they
2550  * are used to signal failure for a single request to the caller.
2551  */
2552 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2553 {
2554     BlockDriverAIOCB *acb;
2555     MultiwriteCB *mcb;
2556     int i;
2557
2558     /* don't submit writes if we don't have a medium */
2559     if (bs->drv == NULL) {
2560         for (i = 0; i < num_reqs; i++) {
2561             reqs[i].error = -ENOMEDIUM;
2562         }
2563         return -1;
2564     }
2565
2566     if (num_reqs == 0) {
2567         return 0;
2568     }
2569
2570     // Create MultiwriteCB structure
2571     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2572     mcb->num_requests = 0;
2573     mcb->num_callbacks = num_reqs;
2574
2575     for (i = 0; i < num_reqs; i++) {
2576         mcb->callbacks[i].cb = reqs[i].cb;
2577         mcb->callbacks[i].opaque = reqs[i].opaque;
2578     }
2579
2580     // Check for mergable requests
2581     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2582
2583     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2584
2585     /*
2586      * Run the aio requests. As soon as one request can't be submitted
2587      * successfully, fail all requests that are not yet submitted (we must
2588      * return failure for all requests anyway)
2589      *
2590      * num_requests cannot be set to the right value immediately: If
2591      * bdrv_aio_writev fails for some request, num_requests would be too high
2592      * and therefore multiwrite_cb() would never recognize the multiwrite
2593      * request as completed. We also cannot use the loop variable i to set it
2594      * when the first request fails because the callback may already have been
2595      * called for previously submitted requests. Thus, num_requests must be
2596      * incremented for each request that is submitted.
2597      *
2598      * The problem that callbacks may be called early also means that we need
2599      * to take care that num_requests doesn't become 0 before all requests are
2600      * submitted - multiwrite_cb() would consider the multiwrite request
2601      * completed. A dummy request that is "completed" by a manual call to
2602      * multiwrite_cb() takes care of this.
2603      */
2604     mcb->num_requests = 1;
2605
2606     // Run the aio requests
2607     for (i = 0; i < num_reqs; i++) {
2608         mcb->num_requests++;
2609         acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2610             reqs[i].nb_sectors, multiwrite_cb, mcb);
2611
2612         if (acb == NULL) {
2613             // We can only fail the whole thing if no request has been
2614             // submitted yet. Otherwise we'll wait for the submitted AIOs to
2615             // complete and report the error in the callback.
2616             if (i == 0) {
2617                 trace_bdrv_aio_multiwrite_earlyfail(mcb);
2618                 goto fail;
2619             } else {
2620                 trace_bdrv_aio_multiwrite_latefail(mcb, i);
2621                 multiwrite_cb(mcb, -EIO);
2622                 break;
2623             }
2624         }
2625     }
2626
2627     /* Complete the dummy request */
2628     multiwrite_cb(mcb, 0);
2629
2630     return 0;
2631
2632 fail:
2633     for (i = 0; i < mcb->num_callbacks; i++) {
2634         reqs[i].error = -EIO;
2635     }
2636     g_free(mcb);
2637     return -1;
2638 }
2639
2640 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2641         BlockDriverCompletionFunc *cb, void *opaque)
2642 {
2643     BlockDriver *drv = bs->drv;
2644
2645     trace_bdrv_aio_flush(bs, opaque);
2646
2647     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2648         return bdrv_aio_noop_em(bs, cb, opaque);
2649     }
2650
2651     if (!drv)
2652         return NULL;
2653     return drv->bdrv_aio_flush(bs, cb, opaque);
2654 }
2655
2656 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2657 {
2658     acb->pool->cancel(acb);
2659 }
2660
2661
2662 /**************************************************************/
2663 /* async block device emulation */
2664
2665 typedef struct BlockDriverAIOCBSync {
2666     BlockDriverAIOCB common;
2667     QEMUBH *bh;
2668     int ret;
2669     /* vector translation state */
2670     QEMUIOVector *qiov;
2671     uint8_t *bounce;
2672     int is_write;
2673 } BlockDriverAIOCBSync;
2674
2675 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2676 {
2677     BlockDriverAIOCBSync *acb =
2678         container_of(blockacb, BlockDriverAIOCBSync, common);
2679     qemu_bh_delete(acb->bh);
2680     acb->bh = NULL;
2681     qemu_aio_release(acb);
2682 }
2683
2684 static AIOPool bdrv_em_aio_pool = {
2685     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2686     .cancel             = bdrv_aio_cancel_em,
2687 };
2688
2689 static void bdrv_aio_bh_cb(void *opaque)
2690 {
2691     BlockDriverAIOCBSync *acb = opaque;
2692
2693     if (!acb->is_write)
2694         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2695     qemu_vfree(acb->bounce);
2696     acb->common.cb(acb->common.opaque, acb->ret);
2697     qemu_bh_delete(acb->bh);
2698     acb->bh = NULL;
2699     qemu_aio_release(acb);
2700 }
2701
2702 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2703                                             int64_t sector_num,
2704                                             QEMUIOVector *qiov,
2705                                             int nb_sectors,
2706                                             BlockDriverCompletionFunc *cb,
2707                                             void *opaque,
2708                                             int is_write)
2709
2710 {
2711     BlockDriverAIOCBSync *acb;
2712
2713     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2714     acb->is_write = is_write;
2715     acb->qiov = qiov;
2716     acb->bounce = qemu_blockalign(bs, qiov->size);
2717
2718     if (!acb->bh)
2719         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2720
2721     if (is_write) {
2722         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2723         acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2724     } else {
2725         acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2726     }
2727
2728     qemu_bh_schedule(acb->bh);
2729
2730     return &acb->common;
2731 }
2732
2733 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2734         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2735         BlockDriverCompletionFunc *cb, void *opaque)
2736 {
2737     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2738 }
2739
2740 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2741         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2742         BlockDriverCompletionFunc *cb, void *opaque)
2743 {
2744     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2745 }
2746
2747
2748 typedef struct BlockDriverAIOCBCoroutine {
2749     BlockDriverAIOCB common;
2750     BlockRequest req;
2751     bool is_write;
2752     QEMUBH* bh;
2753 } BlockDriverAIOCBCoroutine;
2754
2755 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2756 {
2757     qemu_aio_flush();
2758 }
2759
2760 static AIOPool bdrv_em_co_aio_pool = {
2761     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
2762     .cancel             = bdrv_aio_co_cancel_em,
2763 };
2764
2765 static void bdrv_co_rw_bh(void *opaque)
2766 {
2767     BlockDriverAIOCBCoroutine *acb = opaque;
2768
2769     acb->common.cb(acb->common.opaque, acb->req.error);
2770     qemu_bh_delete(acb->bh);
2771     qemu_aio_release(acb);
2772 }
2773
2774 static void coroutine_fn bdrv_co_rw(void *opaque)
2775 {
2776     BlockDriverAIOCBCoroutine *acb = opaque;
2777     BlockDriverState *bs = acb->common.bs;
2778
2779     if (!acb->is_write) {
2780         acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2781             acb->req.nb_sectors, acb->req.qiov);
2782     } else {
2783         acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2784             acb->req.nb_sectors, acb->req.qiov);
2785     }
2786
2787     acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2788     qemu_bh_schedule(acb->bh);
2789 }
2790
2791 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2792                                                int64_t sector_num,
2793                                                QEMUIOVector *qiov,
2794                                                int nb_sectors,
2795                                                BlockDriverCompletionFunc *cb,
2796                                                void *opaque,
2797                                                bool is_write)
2798 {
2799     Coroutine *co;
2800     BlockDriverAIOCBCoroutine *acb;
2801
2802     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2803     acb->req.sector = sector_num;
2804     acb->req.nb_sectors = nb_sectors;
2805     acb->req.qiov = qiov;
2806     acb->is_write = is_write;
2807
2808     co = qemu_coroutine_create(bdrv_co_rw);
2809     qemu_coroutine_enter(co, acb);
2810
2811     return &acb->common;
2812 }
2813
2814 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2815         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2816         BlockDriverCompletionFunc *cb, void *opaque)
2817 {
2818     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2819                                  false);
2820 }
2821
2822 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2823         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2824         BlockDriverCompletionFunc *cb, void *opaque)
2825 {
2826     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2827                                  true);
2828 }
2829
2830 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2831         BlockDriverCompletionFunc *cb, void *opaque)
2832 {
2833     BlockDriverAIOCBSync *acb;
2834
2835     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2836     acb->is_write = 1; /* don't bounce in the completion hadler */
2837     acb->qiov = NULL;
2838     acb->bounce = NULL;
2839     acb->ret = 0;
2840
2841     if (!acb->bh)
2842         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2843
2844     bdrv_flush(bs);
2845     qemu_bh_schedule(acb->bh);
2846     return &acb->common;
2847 }
2848
2849 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2850         BlockDriverCompletionFunc *cb, void *opaque)
2851 {
2852     BlockDriverAIOCBSync *acb;
2853
2854     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2855     acb->is_write = 1; /* don't bounce in the completion handler */
2856     acb->qiov = NULL;
2857     acb->bounce = NULL;
2858     acb->ret = 0;
2859
2860     if (!acb->bh) {
2861         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2862     }
2863
2864     qemu_bh_schedule(acb->bh);
2865     return &acb->common;
2866 }
2867
2868 /**************************************************************/
2869 /* sync block device emulation */
2870
2871 static void bdrv_rw_em_cb(void *opaque, int ret)
2872 {
2873     *(int *)opaque = ret;
2874 }
2875
2876 #define NOT_DONE 0x7fffffff
2877
2878 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2879                         uint8_t *buf, int nb_sectors)
2880 {
2881     int async_ret;
2882     BlockDriverAIOCB *acb;
2883     struct iovec iov;
2884     QEMUIOVector qiov;
2885
2886     async_ret = NOT_DONE;
2887     iov.iov_base = (void *)buf;
2888     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2889     qemu_iovec_init_external(&qiov, &iov, 1);
2890     acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2891         bdrv_rw_em_cb, &async_ret);
2892     if (acb == NULL) {
2893         async_ret = -1;
2894         goto fail;
2895     }
2896
2897     while (async_ret == NOT_DONE) {
2898         qemu_aio_wait();
2899     }
2900
2901
2902 fail:
2903     return async_ret;
2904 }
2905
2906 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2907                          const uint8_t *buf, int nb_sectors)
2908 {
2909     int async_ret;
2910     BlockDriverAIOCB *acb;
2911     struct iovec iov;
2912     QEMUIOVector qiov;
2913
2914     async_ret = NOT_DONE;
2915     iov.iov_base = (void *)buf;
2916     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2917     qemu_iovec_init_external(&qiov, &iov, 1);
2918     acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2919         bdrv_rw_em_cb, &async_ret);
2920     if (acb == NULL) {
2921         async_ret = -1;
2922         goto fail;
2923     }
2924     while (async_ret == NOT_DONE) {
2925         qemu_aio_wait();
2926     }
2927
2928 fail:
2929     return async_ret;
2930 }
2931
2932 void bdrv_init(void)
2933 {
2934     module_call_init(MODULE_INIT_BLOCK);
2935 }
2936
2937 void bdrv_init_with_whitelist(void)
2938 {
2939     use_bdrv_whitelist = 1;
2940     bdrv_init();
2941 }
2942
2943 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2944                    BlockDriverCompletionFunc *cb, void *opaque)
2945 {
2946     BlockDriverAIOCB *acb;
2947
2948     if (pool->free_aiocb) {
2949         acb = pool->free_aiocb;
2950         pool->free_aiocb = acb->next;
2951     } else {
2952         acb = g_malloc0(pool->aiocb_size);
2953         acb->pool = pool;
2954     }
2955     acb->bs = bs;
2956     acb->cb = cb;
2957     acb->opaque = opaque;
2958     return acb;
2959 }
2960
2961 void qemu_aio_release(void *p)
2962 {
2963     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2964     AIOPool *pool = acb->pool;
2965     acb->next = pool->free_aiocb;
2966     pool->free_aiocb = acb;
2967 }
2968
2969 /**************************************************************/
2970 /* Coroutine block device emulation */
2971
2972 typedef struct CoroutineIOCompletion {
2973     Coroutine *coroutine;
2974     int ret;
2975 } CoroutineIOCompletion;
2976
2977 static void bdrv_co_io_em_complete(void *opaque, int ret)
2978 {
2979     CoroutineIOCompletion *co = opaque;
2980
2981     co->ret = ret;
2982     qemu_coroutine_enter(co->coroutine, NULL);
2983 }
2984
2985 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2986                                       int nb_sectors, QEMUIOVector *iov,
2987                                       bool is_write)
2988 {
2989     CoroutineIOCompletion co = {
2990         .coroutine = qemu_coroutine_self(),
2991     };
2992     BlockDriverAIOCB *acb;
2993
2994     if (is_write) {
2995         acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2996                               bdrv_co_io_em_complete, &co);
2997     } else {
2998         acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2999                              bdrv_co_io_em_complete, &co);
3000     }
3001
3002     trace_bdrv_co_io(is_write, acb);
3003     if (!acb) {
3004         return -EIO;
3005     }
3006     qemu_coroutine_yield();
3007
3008     return co.ret;
3009 }
3010
3011 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3012                                          int64_t sector_num, int nb_sectors,
3013                                          QEMUIOVector *iov)
3014 {
3015     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3016 }
3017
3018 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3019                                          int64_t sector_num, int nb_sectors,
3020                                          QEMUIOVector *iov)
3021 {
3022     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3023 }
3024
3025 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3026 {
3027     CoroutineIOCompletion co = {
3028         .coroutine = qemu_coroutine_self(),
3029     };
3030     BlockDriverAIOCB *acb;
3031
3032     acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3033     if (!acb) {
3034         return -EIO;
3035     }
3036     qemu_coroutine_yield();
3037     return co.ret;
3038 }
3039
3040 /**************************************************************/
3041 /* removable device support */
3042
3043 /**
3044  * Return TRUE if the media is present
3045  */
3046 int bdrv_is_inserted(BlockDriverState *bs)
3047 {
3048     BlockDriver *drv = bs->drv;
3049
3050     if (!drv)
3051         return 0;
3052     if (!drv->bdrv_is_inserted)
3053         return 1;
3054     return drv->bdrv_is_inserted(bs);
3055 }
3056
3057 /**
3058  * Return whether the media changed since the last call to this
3059  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
3060  */
3061 int bdrv_media_changed(BlockDriverState *bs)
3062 {
3063     BlockDriver *drv = bs->drv;
3064
3065     if (drv && drv->bdrv_media_changed) {
3066         return drv->bdrv_media_changed(bs);
3067     }
3068     return -ENOTSUP;
3069 }
3070
3071 /**
3072  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3073  */
3074 void bdrv_eject(BlockDriverState *bs, int eject_flag)
3075 {
3076     BlockDriver *drv = bs->drv;
3077
3078     if (drv && drv->bdrv_eject) {
3079         drv->bdrv_eject(bs, eject_flag);
3080     }
3081 }
3082
3083 /**
3084  * Lock or unlock the media (if it is locked, the user won't be able
3085  * to eject it manually).
3086  */
3087 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
3088 {
3089     BlockDriver *drv = bs->drv;
3090
3091     trace_bdrv_lock_medium(bs, locked);
3092
3093     if (drv && drv->bdrv_lock_medium) {
3094         drv->bdrv_lock_medium(bs, locked);
3095     }
3096 }
3097
3098 /* needed for generic scsi interface */
3099
3100 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3101 {
3102     BlockDriver *drv = bs->drv;
3103
3104     if (drv && drv->bdrv_ioctl)
3105         return drv->bdrv_ioctl(bs, req, buf);
3106     return -ENOTSUP;
3107 }
3108
3109 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3110         unsigned long int req, void *buf,
3111         BlockDriverCompletionFunc *cb, void *opaque)
3112 {
3113     BlockDriver *drv = bs->drv;
3114
3115     if (drv && drv->bdrv_aio_ioctl)
3116         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3117     return NULL;
3118 }
3119
3120 void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
3121 {
3122     bs->buffer_alignment = align;
3123 }
3124
3125 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3126 {
3127     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3128 }
3129
3130 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3131 {
3132     int64_t bitmap_size;
3133
3134     bs->dirty_count = 0;
3135     if (enable) {
3136         if (!bs->dirty_bitmap) {
3137             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3138                     BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3139             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
3140
3141             bs->dirty_bitmap = g_malloc0(bitmap_size);
3142         }
3143     } else {
3144         if (bs->dirty_bitmap) {
3145             g_free(bs->dirty_bitmap);
3146             bs->dirty_bitmap = NULL;
3147         }
3148     }
3149 }
3150
3151 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3152 {
3153     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
3154
3155     if (bs->dirty_bitmap &&
3156         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
3157         return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3158             (1UL << (chunk % (sizeof(unsigned long) * 8))));
3159     } else {
3160         return 0;
3161     }
3162 }
3163
3164 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3165                       int nr_sectors)
3166 {
3167     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3168 }
3169
3170 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3171 {
3172     return bs->dirty_count;
3173 }
3174
3175 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3176 {
3177     assert(bs->in_use != in_use);
3178     bs->in_use = in_use;
3179 }
3180
3181 int bdrv_in_use(BlockDriverState *bs)
3182 {
3183     return bs->in_use;
3184 }
3185
3186 void
3187 bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3188         enum BlockAcctType type)
3189 {
3190     assert(type < BDRV_MAX_IOTYPE);
3191
3192     cookie->bytes = bytes;
3193     cookie->start_time_ns = get_clock();
3194     cookie->type = type;
3195 }
3196
3197 void
3198 bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3199 {
3200     assert(cookie->type < BDRV_MAX_IOTYPE);
3201
3202     bs->nr_bytes[cookie->type] += cookie->bytes;
3203     bs->nr_ops[cookie->type]++;
3204     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
3205 }
3206
3207 int bdrv_img_create(const char *filename, const char *fmt,
3208                     const char *base_filename, const char *base_fmt,
3209                     char *options, uint64_t img_size, int flags)
3210 {
3211     QEMUOptionParameter *param = NULL, *create_options = NULL;
3212     QEMUOptionParameter *backing_fmt, *backing_file, *size;
3213     BlockDriverState *bs = NULL;
3214     BlockDriver *drv, *proto_drv;
3215     BlockDriver *backing_drv = NULL;
3216     int ret = 0;
3217
3218     /* Find driver and parse its options */
3219     drv = bdrv_find_format(fmt);
3220     if (!drv) {
3221         error_report("Unknown file format '%s'", fmt);
3222         ret = -EINVAL;
3223         goto out;
3224     }
3225
3226     proto_drv = bdrv_find_protocol(filename);
3227     if (!proto_drv) {
3228         error_report("Unknown protocol '%s'", filename);
3229         ret = -EINVAL;
3230         goto out;
3231     }
3232
3233     create_options = append_option_parameters(create_options,
3234                                               drv->create_options);
3235     create_options = append_option_parameters(create_options,
3236                                               proto_drv->create_options);
3237
3238     /* Create parameter list with default values */
3239     param = parse_option_parameters("", create_options, param);
3240
3241     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3242
3243     /* Parse -o options */
3244     if (options) {
3245         param = parse_option_parameters(options, create_options, param);
3246         if (param == NULL) {
3247             error_report("Invalid options for file format '%s'.", fmt);
3248             ret = -EINVAL;
3249             goto out;
3250         }
3251     }
3252
3253     if (base_filename) {
3254         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3255                                  base_filename)) {
3256             error_report("Backing file not supported for file format '%s'",
3257                          fmt);
3258             ret = -EINVAL;
3259             goto out;
3260         }
3261     }
3262
3263     if (base_fmt) {
3264         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3265             error_report("Backing file format not supported for file "
3266                          "format '%s'", fmt);
3267             ret = -EINVAL;
3268             goto out;
3269         }
3270     }
3271
3272     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3273     if (backing_file && backing_file->value.s) {
3274         if (!strcmp(filename, backing_file->value.s)) {
3275             error_report("Error: Trying to create an image with the "
3276                          "same filename as the backing file");
3277             ret = -EINVAL;
3278             goto out;
3279         }
3280     }
3281
3282     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3283     if (backing_fmt && backing_fmt->value.s) {
3284         backing_drv = bdrv_find_format(backing_fmt->value.s);
3285         if (!backing_drv) {
3286             error_report("Unknown backing file format '%s'",
3287                          backing_fmt->value.s);
3288             ret = -EINVAL;
3289             goto out;
3290         }
3291     }
3292
3293     // The size for the image must always be specified, with one exception:
3294     // If we are using a backing file, we can obtain the size from there
3295     size = get_option_parameter(param, BLOCK_OPT_SIZE);
3296     if (size && size->value.n == -1) {
3297         if (backing_file && backing_file->value.s) {
3298             uint64_t size;
3299             char buf[32];
3300
3301             bs = bdrv_new("");
3302
3303             ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
3304             if (ret < 0) {
3305                 error_report("Could not open '%s'", backing_file->value.s);
3306                 goto out;
3307             }
3308             bdrv_get_geometry(bs, &size);
3309             size *= 512;
3310
3311             snprintf(buf, sizeof(buf), "%" PRId64, size);
3312             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3313         } else {
3314             error_report("Image creation needs a size parameter");
3315             ret = -EINVAL;
3316             goto out;
3317         }
3318     }
3319
3320     printf("Formatting '%s', fmt=%s ", filename, fmt);
3321     print_option_parameters(param);
3322     puts("");
3323
3324     ret = bdrv_create(drv, filename, param);
3325
3326     if (ret < 0) {
3327         if (ret == -ENOTSUP) {
3328             error_report("Formatting or formatting option not supported for "
3329                          "file format '%s'", fmt);
3330         } else if (ret == -EFBIG) {
3331             error_report("The image size is too large for file format '%s'",
3332                          fmt);
3333         } else {
3334             error_report("%s: error while creating %s: %s", filename, fmt,
3335                          strerror(-ret));
3336         }
3337     }
3338
3339 out:
3340     free_option_parameters(create_options);
3341     free_option_parameters(param);
3342
3343     if (bs) {
3344         bdrv_delete(bs);
3345     }
3346
3347     return ret;
3348 }
This page took 0.207344 seconds and 4 git commands to generate.