]> Git Repo - qemu.git/blob - block.c
Revert "Make default invocation of block drivers safer (v3)"
[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 "monitor.h"
27 #include "block_int.h"
28 #include "module.h"
29 #include "qemu-objects.h"
30
31 #ifdef CONFIG_BSD
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/ioctl.h>
35 #include <sys/queue.h>
36 #ifndef __DragonFly__
37 #include <sys/disk.h>
38 #endif
39 #endif
40
41 #ifdef _WIN32
42 #include <windows.h>
43 #endif
44
45 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
46         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
47         BlockDriverCompletionFunc *cb, void *opaque);
48 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
49         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50         BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
52         BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
54         BlockDriverCompletionFunc *cb, void *opaque);
55 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
56                         uint8_t *buf, int nb_sectors);
57 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
58                          const uint8_t *buf, int nb_sectors);
59
60 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
61     QTAILQ_HEAD_INITIALIZER(bdrv_states);
62
63 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
64     QLIST_HEAD_INITIALIZER(bdrv_drivers);
65
66 /* The device to use for VM snapshots */
67 static BlockDriverState *bs_snapshots;
68
69 /* If non-zero, use only whitelisted block drivers */
70 static int use_bdrv_whitelist;
71
72 int path_is_absolute(const char *path)
73 {
74     const char *p;
75 #ifdef _WIN32
76     /* specific case for names like: "\\.\d:" */
77     if (*path == '/' || *path == '\\')
78         return 1;
79 #endif
80     p = strchr(path, ':');
81     if (p)
82         p++;
83     else
84         p = path;
85 #ifdef _WIN32
86     return (*p == '/' || *p == '\\');
87 #else
88     return (*p == '/');
89 #endif
90 }
91
92 /* if filename is absolute, just copy it to dest. Otherwise, build a
93    path to it by considering it is relative to base_path. URL are
94    supported. */
95 void path_combine(char *dest, int dest_size,
96                   const char *base_path,
97                   const char *filename)
98 {
99     const char *p, *p1;
100     int len;
101
102     if (dest_size <= 0)
103         return;
104     if (path_is_absolute(filename)) {
105         pstrcpy(dest, dest_size, filename);
106     } else {
107         p = strchr(base_path, ':');
108         if (p)
109             p++;
110         else
111             p = base_path;
112         p1 = strrchr(base_path, '/');
113 #ifdef _WIN32
114         {
115             const char *p2;
116             p2 = strrchr(base_path, '\\');
117             if (!p1 || p2 > p1)
118                 p1 = p2;
119         }
120 #endif
121         if (p1)
122             p1++;
123         else
124             p1 = base_path;
125         if (p1 > p)
126             p = p1;
127         len = p - base_path;
128         if (len > dest_size - 1)
129             len = dest_size - 1;
130         memcpy(dest, base_path, len);
131         dest[len] = '\0';
132         pstrcat(dest, dest_size, filename);
133     }
134 }
135
136 void bdrv_register(BlockDriver *bdrv)
137 {
138     if (!bdrv->bdrv_aio_readv) {
139         /* add AIO emulation layer */
140         bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
141         bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
142     } else if (!bdrv->bdrv_read) {
143         /* add synchronous IO emulation layer */
144         bdrv->bdrv_read = bdrv_read_em;
145         bdrv->bdrv_write = bdrv_write_em;
146     }
147
148     if (!bdrv->bdrv_aio_flush)
149         bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
150
151     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
152 }
153
154 /* create a new block device (by default it is empty) */
155 BlockDriverState *bdrv_new(const char *device_name)
156 {
157     BlockDriverState *bs;
158
159     bs = qemu_mallocz(sizeof(BlockDriverState));
160     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
161     if (device_name[0] != '\0') {
162         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
163     }
164     return bs;
165 }
166
167 BlockDriver *bdrv_find_format(const char *format_name)
168 {
169     BlockDriver *drv1;
170     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
171         if (!strcmp(drv1->format_name, format_name)) {
172             return drv1;
173         }
174     }
175     return NULL;
176 }
177
178 static int bdrv_is_whitelisted(BlockDriver *drv)
179 {
180     static const char *whitelist[] = {
181         CONFIG_BDRV_WHITELIST
182     };
183     const char **p;
184
185     if (!whitelist[0])
186         return 1;               /* no whitelist, anything goes */
187
188     for (p = whitelist; *p; p++) {
189         if (!strcmp(drv->format_name, *p)) {
190             return 1;
191         }
192     }
193     return 0;
194 }
195
196 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
197 {
198     BlockDriver *drv = bdrv_find_format(format_name);
199     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
200 }
201
202 int bdrv_create(BlockDriver *drv, const char* filename,
203     QEMUOptionParameter *options)
204 {
205     if (!drv->bdrv_create)
206         return -ENOTSUP;
207
208     return drv->bdrv_create(filename, options);
209 }
210
211 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
212 {
213     BlockDriver *drv;
214
215     drv = bdrv_find_protocol(filename);
216     if (drv == NULL) {
217         drv = bdrv_find_format("file");
218     }
219
220     return bdrv_create(drv, filename, options);
221 }
222
223 #ifdef _WIN32
224 void get_tmp_filename(char *filename, int size)
225 {
226     char temp_dir[MAX_PATH];
227
228     GetTempPath(MAX_PATH, temp_dir);
229     GetTempFileName(temp_dir, "qem", 0, filename);
230 }
231 #else
232 void get_tmp_filename(char *filename, int size)
233 {
234     int fd;
235     const char *tmpdir;
236     /* XXX: race condition possible */
237     tmpdir = getenv("TMPDIR");
238     if (!tmpdir)
239         tmpdir = "/tmp";
240     snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
241     fd = mkstemp(filename);
242     close(fd);
243 }
244 #endif
245
246 #ifdef _WIN32
247 static int is_windows_drive_prefix(const char *filename)
248 {
249     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
250              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
251             filename[1] == ':');
252 }
253
254 int is_windows_drive(const char *filename)
255 {
256     if (is_windows_drive_prefix(filename) &&
257         filename[2] == '\0')
258         return 1;
259     if (strstart(filename, "\\\\.\\", NULL) ||
260         strstart(filename, "//./", NULL))
261         return 1;
262     return 0;
263 }
264 #endif
265
266 /*
267  * Detect host devices. By convention, /dev/cdrom[N] is always
268  * recognized as a host CDROM.
269  */
270 static BlockDriver *find_hdev_driver(const char *filename)
271 {
272     int score_max = 0, score;
273     BlockDriver *drv = NULL, *d;
274
275     QLIST_FOREACH(d, &bdrv_drivers, list) {
276         if (d->bdrv_probe_device) {
277             score = d->bdrv_probe_device(filename);
278             if (score > score_max) {
279                 score_max = score;
280                 drv = d;
281             }
282         }
283     }
284
285     return drv;
286 }
287
288 BlockDriver *bdrv_find_protocol(const char *filename)
289 {
290     BlockDriver *drv1;
291     char protocol[128];
292     int len;
293     const char *p;
294
295     /* TODO Drivers without bdrv_file_open must be specified explicitly */
296
297     /*
298      * XXX(hch): we really should not let host device detection
299      * override an explicit protocol specification, but moving this
300      * later breaks access to device names with colons in them.
301      * Thanks to the brain-dead persistent naming schemes on udev-
302      * based Linux systems those actually are quite common.
303      */
304     drv1 = find_hdev_driver(filename);
305     if (drv1) {
306         return drv1;
307     }
308
309 #ifdef _WIN32
310      if (is_windows_drive(filename) ||
311          is_windows_drive_prefix(filename))
312          return bdrv_find_format("file");
313 #endif
314
315     p = strchr(filename, ':');
316     if (!p) {
317         return bdrv_find_format("file");
318     }
319     len = p - filename;
320     if (len > sizeof(protocol) - 1)
321         len = sizeof(protocol) - 1;
322     memcpy(protocol, filename, len);
323     protocol[len] = '\0';
324     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
325         if (drv1->protocol_name &&
326             !strcmp(drv1->protocol_name, protocol)) {
327             return drv1;
328         }
329     }
330     return NULL;
331 }
332
333 static int find_image_format(const char *filename, BlockDriver **pdrv)
334 {
335     int ret, score, score_max;
336     BlockDriver *drv1, *drv;
337     uint8_t buf[2048];
338     BlockDriverState *bs;
339
340     ret = bdrv_file_open(&bs, filename, 0);
341     if (ret < 0) {
342         *pdrv = NULL;
343         return ret;
344     }
345
346     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
347     if (bs->sg || !bdrv_is_inserted(bs)) {
348         bdrv_delete(bs);
349         drv = bdrv_find_format("raw");
350         if (!drv) {
351             ret = -ENOENT;
352         }
353         *pdrv = drv;
354         return ret;
355     }
356
357     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
358     bdrv_delete(bs);
359     if (ret < 0) {
360         *pdrv = NULL;
361         return ret;
362     }
363
364     score_max = 0;
365     drv = NULL;
366     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
367         if (drv1->bdrv_probe) {
368             score = drv1->bdrv_probe(buf, ret, filename);
369             if (score > score_max) {
370                 score_max = score;
371                 drv = drv1;
372             }
373         }
374     }
375     if (!drv) {
376         ret = -ENOENT;
377     }
378     *pdrv = drv;
379     return ret;
380 }
381
382 /**
383  * Set the current 'total_sectors' value
384  */
385 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
386 {
387     BlockDriver *drv = bs->drv;
388
389     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
390     if (bs->sg)
391         return 0;
392
393     /* query actual device if possible, otherwise just trust the hint */
394     if (drv->bdrv_getlength) {
395         int64_t length = drv->bdrv_getlength(bs);
396         if (length < 0) {
397             return length;
398         }
399         hint = length >> BDRV_SECTOR_BITS;
400     }
401
402     bs->total_sectors = hint;
403     return 0;
404 }
405
406 /*
407  * Common part for opening disk images and files
408  */
409 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
410     int flags, BlockDriver *drv)
411 {
412     int ret, open_flags;
413
414     assert(drv != NULL);
415
416     bs->file = NULL;
417     bs->total_sectors = 0;
418     bs->encrypted = 0;
419     bs->valid_key = 0;
420     bs->open_flags = flags;
421     /* buffer_alignment defaulted to 512, drivers can change this value */
422     bs->buffer_alignment = 512;
423
424     pstrcpy(bs->filename, sizeof(bs->filename), filename);
425
426     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
427         return -ENOTSUP;
428     }
429
430     bs->drv = drv;
431     bs->opaque = qemu_mallocz(drv->instance_size);
432
433     /*
434      * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
435      * write cache to the guest.  We do need the fdatasync to flush
436      * out transactions for block allocations, and we maybe have a
437      * volatile write cache in our backing device to deal with.
438      */
439     if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
440         bs->enable_write_cache = 1;
441
442     /*
443      * Clear flags that are internal to the block layer before opening the
444      * image.
445      */
446     open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
447
448     /*
449      * Snapshots should be writeable.
450      */
451     if (bs->is_temporary) {
452         open_flags |= BDRV_O_RDWR;
453     }
454
455     /* Open the image, either directly or using a protocol */
456     if (drv->bdrv_file_open) {
457         ret = drv->bdrv_file_open(bs, filename, open_flags);
458     } else {
459         ret = bdrv_file_open(&bs->file, filename, open_flags);
460         if (ret >= 0) {
461             ret = drv->bdrv_open(bs, open_flags);
462         }
463     }
464
465     if (ret < 0) {
466         goto free_and_fail;
467     }
468
469     bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
470
471     ret = refresh_total_sectors(bs, bs->total_sectors);
472     if (ret < 0) {
473         goto free_and_fail;
474     }
475
476 #ifndef _WIN32
477     if (bs->is_temporary) {
478         unlink(filename);
479     }
480 #endif
481     return 0;
482
483 free_and_fail:
484     if (bs->file) {
485         bdrv_delete(bs->file);
486         bs->file = NULL;
487     }
488     qemu_free(bs->opaque);
489     bs->opaque = NULL;
490     bs->drv = NULL;
491     return ret;
492 }
493
494 /*
495  * Opens a file using a protocol (file, host_device, nbd, ...)
496  */
497 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
498 {
499     BlockDriverState *bs;
500     BlockDriver *drv;
501     int ret;
502
503     drv = bdrv_find_protocol(filename);
504     if (!drv) {
505         return -ENOENT;
506     }
507
508     bs = bdrv_new("");
509     ret = bdrv_open_common(bs, filename, flags, drv);
510     if (ret < 0) {
511         bdrv_delete(bs);
512         return ret;
513     }
514     bs->growable = 1;
515     *pbs = bs;
516     return 0;
517 }
518
519 /*
520  * Opens a disk image (raw, qcow2, vmdk, ...)
521  */
522 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
523               BlockDriver *drv)
524 {
525     int ret;
526
527     if (flags & BDRV_O_SNAPSHOT) {
528         BlockDriverState *bs1;
529         int64_t total_size;
530         int is_protocol = 0;
531         BlockDriver *bdrv_qcow2;
532         QEMUOptionParameter *options;
533         char tmp_filename[PATH_MAX];
534         char backing_filename[PATH_MAX];
535
536         /* if snapshot, we create a temporary backing file and open it
537            instead of opening 'filename' directly */
538
539         /* if there is a backing file, use it */
540         bs1 = bdrv_new("");
541         ret = bdrv_open(bs1, filename, 0, drv);
542         if (ret < 0) {
543             bdrv_delete(bs1);
544             return ret;
545         }
546         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
547
548         if (bs1->drv && bs1->drv->protocol_name)
549             is_protocol = 1;
550
551         bdrv_delete(bs1);
552
553         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
554
555         /* Real path is meaningless for protocols */
556         if (is_protocol)
557             snprintf(backing_filename, sizeof(backing_filename),
558                      "%s", filename);
559         else if (!realpath(filename, backing_filename))
560             return -errno;
561
562         bdrv_qcow2 = bdrv_find_format("qcow2");
563         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
564
565         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
566         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
567         if (drv) {
568             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
569                 drv->format_name);
570         }
571
572         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
573         free_option_parameters(options);
574         if (ret < 0) {
575             return ret;
576         }
577
578         filename = tmp_filename;
579         drv = bdrv_qcow2;
580         bs->is_temporary = 1;
581     }
582
583     /* Find the right image format driver */
584     if (!drv) {
585         ret = find_image_format(filename, &drv);
586     }
587
588     if (!drv) {
589         goto unlink_and_fail;
590     }
591
592     /* Open the image */
593     ret = bdrv_open_common(bs, filename, flags, drv);
594     if (ret < 0) {
595         goto unlink_and_fail;
596     }
597
598     /* If there is a backing file, use it */
599     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
600         char backing_filename[PATH_MAX];
601         int back_flags;
602         BlockDriver *back_drv = NULL;
603
604         bs->backing_hd = bdrv_new("");
605         path_combine(backing_filename, sizeof(backing_filename),
606                      filename, bs->backing_file);
607         if (bs->backing_format[0] != '\0')
608             back_drv = bdrv_find_format(bs->backing_format);
609
610         /* backing files always opened read-only */
611         back_flags =
612             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
613
614         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
615         if (ret < 0) {
616             bdrv_close(bs);
617             return ret;
618         }
619         if (bs->is_temporary) {
620             bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
621         } else {
622             /* base image inherits from "parent" */
623             bs->backing_hd->keep_read_only = bs->keep_read_only;
624         }
625     }
626
627     if (!bdrv_key_required(bs)) {
628         /* call the change callback */
629         bs->media_changed = 1;
630         if (bs->change_cb)
631             bs->change_cb(bs->change_opaque);
632     }
633
634     return 0;
635
636 unlink_and_fail:
637     if (bs->is_temporary) {
638         unlink(filename);
639     }
640     return ret;
641 }
642
643 void bdrv_close(BlockDriverState *bs)
644 {
645     if (bs->drv) {
646         if (bs == bs_snapshots) {
647             bs_snapshots = NULL;
648         }
649         if (bs->backing_hd) {
650             bdrv_delete(bs->backing_hd);
651             bs->backing_hd = NULL;
652         }
653         bs->drv->bdrv_close(bs);
654         qemu_free(bs->opaque);
655 #ifdef _WIN32
656         if (bs->is_temporary) {
657             unlink(bs->filename);
658         }
659 #endif
660         bs->opaque = NULL;
661         bs->drv = NULL;
662
663         if (bs->file != NULL) {
664             bdrv_close(bs->file);
665         }
666
667         /* call the change callback */
668         bs->media_changed = 1;
669         if (bs->change_cb)
670             bs->change_cb(bs->change_opaque);
671     }
672 }
673
674 void bdrv_close_all(void)
675 {
676     BlockDriverState *bs;
677
678     QTAILQ_FOREACH(bs, &bdrv_states, list) {
679         bdrv_close(bs);
680     }
681 }
682
683 void bdrv_delete(BlockDriverState *bs)
684 {
685     assert(!bs->peer);
686
687     /* remove from list, if necessary */
688     if (bs->device_name[0] != '\0') {
689         QTAILQ_REMOVE(&bdrv_states, bs, list);
690     }
691
692     bdrv_close(bs);
693     if (bs->file != NULL) {
694         bdrv_delete(bs->file);
695     }
696
697     assert(bs != bs_snapshots);
698     qemu_free(bs);
699 }
700
701 int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
702 {
703     if (bs->peer) {
704         return -EBUSY;
705     }
706     bs->peer = qdev;
707     return 0;
708 }
709
710 void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
711 {
712     assert(bs->peer == qdev);
713     bs->peer = NULL;
714 }
715
716 DeviceState *bdrv_get_attached(BlockDriverState *bs)
717 {
718     return bs->peer;
719 }
720
721 /*
722  * Run consistency checks on an image
723  *
724  * Returns 0 if the check could be completed (it doesn't mean that the image is
725  * free of errors) or -errno when an internal error occured. The results of the
726  * check are stored in res.
727  */
728 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
729 {
730     if (bs->drv->bdrv_check == NULL) {
731         return -ENOTSUP;
732     }
733
734     memset(res, 0, sizeof(*res));
735     return bs->drv->bdrv_check(bs, res);
736 }
737
738 #define COMMIT_BUF_SECTORS 2048
739
740 /* commit COW file into the raw image */
741 int bdrv_commit(BlockDriverState *bs)
742 {
743     BlockDriver *drv = bs->drv;
744     BlockDriver *backing_drv;
745     int64_t sector, total_sectors;
746     int n, ro, open_flags;
747     int ret = 0, rw_ret = 0;
748     uint8_t *buf;
749     char filename[1024];
750     BlockDriverState *bs_rw, *bs_ro;
751
752     if (!drv)
753         return -ENOMEDIUM;
754     
755     if (!bs->backing_hd) {
756         return -ENOTSUP;
757     }
758
759     if (bs->backing_hd->keep_read_only) {
760         return -EACCES;
761     }
762
763     backing_drv = bs->backing_hd->drv;
764     ro = bs->backing_hd->read_only;
765     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
766     open_flags =  bs->backing_hd->open_flags;
767
768     if (ro) {
769         /* re-open as RW */
770         bdrv_delete(bs->backing_hd);
771         bs->backing_hd = NULL;
772         bs_rw = bdrv_new("");
773         rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
774             backing_drv);
775         if (rw_ret < 0) {
776             bdrv_delete(bs_rw);
777             /* try to re-open read-only */
778             bs_ro = bdrv_new("");
779             ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
780                 backing_drv);
781             if (ret < 0) {
782                 bdrv_delete(bs_ro);
783                 /* drive not functional anymore */
784                 bs->drv = NULL;
785                 return ret;
786             }
787             bs->backing_hd = bs_ro;
788             return rw_ret;
789         }
790         bs->backing_hd = bs_rw;
791     }
792
793     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
794     buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
795
796     for (sector = 0; sector < total_sectors; sector += n) {
797         if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
798
799             if (bdrv_read(bs, sector, buf, n) != 0) {
800                 ret = -EIO;
801                 goto ro_cleanup;
802             }
803
804             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
805                 ret = -EIO;
806                 goto ro_cleanup;
807             }
808         }
809     }
810
811     if (drv->bdrv_make_empty) {
812         ret = drv->bdrv_make_empty(bs);
813         bdrv_flush(bs);
814     }
815
816     /*
817      * Make sure all data we wrote to the backing device is actually
818      * stable on disk.
819      */
820     if (bs->backing_hd)
821         bdrv_flush(bs->backing_hd);
822
823 ro_cleanup:
824     qemu_free(buf);
825
826     if (ro) {
827         /* re-open as RO */
828         bdrv_delete(bs->backing_hd);
829         bs->backing_hd = NULL;
830         bs_ro = bdrv_new("");
831         ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
832             backing_drv);
833         if (ret < 0) {
834             bdrv_delete(bs_ro);
835             /* drive not functional anymore */
836             bs->drv = NULL;
837             return ret;
838         }
839         bs->backing_hd = bs_ro;
840         bs->backing_hd->keep_read_only = 0;
841     }
842
843     return ret;
844 }
845
846 void bdrv_commit_all(void)
847 {
848     BlockDriverState *bs;
849
850     QTAILQ_FOREACH(bs, &bdrv_states, list) {
851         bdrv_commit(bs);
852     }
853 }
854
855 /*
856  * Return values:
857  * 0        - success
858  * -EINVAL  - backing format specified, but no file
859  * -ENOSPC  - can't update the backing file because no space is left in the
860  *            image file header
861  * -ENOTSUP - format driver doesn't support changing the backing file
862  */
863 int bdrv_change_backing_file(BlockDriverState *bs,
864     const char *backing_file, const char *backing_fmt)
865 {
866     BlockDriver *drv = bs->drv;
867
868     if (drv->bdrv_change_backing_file != NULL) {
869         return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
870     } else {
871         return -ENOTSUP;
872     }
873 }
874
875 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
876                                    size_t size)
877 {
878     int64_t len;
879
880     if (!bdrv_is_inserted(bs))
881         return -ENOMEDIUM;
882
883     if (bs->growable)
884         return 0;
885
886     len = bdrv_getlength(bs);
887
888     if (offset < 0)
889         return -EIO;
890
891     if ((offset > len) || (len - offset < size))
892         return -EIO;
893
894     return 0;
895 }
896
897 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
898                               int nb_sectors)
899 {
900     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
901                                    nb_sectors * BDRV_SECTOR_SIZE);
902 }
903
904 /* return < 0 if error. See bdrv_write() for the return codes */
905 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
906               uint8_t *buf, int nb_sectors)
907 {
908     BlockDriver *drv = bs->drv;
909
910     if (!drv)
911         return -ENOMEDIUM;
912     if (bdrv_check_request(bs, sector_num, nb_sectors))
913         return -EIO;
914
915     return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
916 }
917
918 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
919                              int nb_sectors, int dirty)
920 {
921     int64_t start, end;
922     unsigned long val, idx, bit;
923
924     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
925     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
926
927     for (; start <= end; start++) {
928         idx = start / (sizeof(unsigned long) * 8);
929         bit = start % (sizeof(unsigned long) * 8);
930         val = bs->dirty_bitmap[idx];
931         if (dirty) {
932             if (!(val & (1 << bit))) {
933                 bs->dirty_count++;
934                 val |= 1 << bit;
935             }
936         } else {
937             if (val & (1 << bit)) {
938                 bs->dirty_count--;
939                 val &= ~(1 << bit);
940             }
941         }
942         bs->dirty_bitmap[idx] = val;
943     }
944 }
945
946 /* Return < 0 if error. Important errors are:
947   -EIO         generic I/O error (may happen for all errors)
948   -ENOMEDIUM   No media inserted.
949   -EINVAL      Invalid sector number or nb_sectors
950   -EACCES      Trying to write a read-only device
951 */
952 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
953                const uint8_t *buf, int nb_sectors)
954 {
955     BlockDriver *drv = bs->drv;
956     if (!bs->drv)
957         return -ENOMEDIUM;
958     if (bs->read_only)
959         return -EACCES;
960     if (bdrv_check_request(bs, sector_num, nb_sectors))
961         return -EIO;
962
963     if (bs->dirty_bitmap) {
964         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
965     }
966
967     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
968         bs->wr_highest_sector = sector_num + nb_sectors - 1;
969     }
970
971     return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
972 }
973
974 int bdrv_pread(BlockDriverState *bs, int64_t offset,
975                void *buf, int count1)
976 {
977     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
978     int len, nb_sectors, count;
979     int64_t sector_num;
980     int ret;
981
982     count = count1;
983     /* first read to align to sector start */
984     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
985     if (len > count)
986         len = count;
987     sector_num = offset >> BDRV_SECTOR_BITS;
988     if (len > 0) {
989         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
990             return ret;
991         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
992         count -= len;
993         if (count == 0)
994             return count1;
995         sector_num++;
996         buf += len;
997     }
998
999     /* read the sectors "in place" */
1000     nb_sectors = count >> BDRV_SECTOR_BITS;
1001     if (nb_sectors > 0) {
1002         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1003             return ret;
1004         sector_num += nb_sectors;
1005         len = nb_sectors << BDRV_SECTOR_BITS;
1006         buf += len;
1007         count -= len;
1008     }
1009
1010     /* add data from the last sector */
1011     if (count > 0) {
1012         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1013             return ret;
1014         memcpy(buf, tmp_buf, count);
1015     }
1016     return count1;
1017 }
1018
1019 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1020                 const void *buf, int count1)
1021 {
1022     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1023     int len, nb_sectors, count;
1024     int64_t sector_num;
1025     int ret;
1026
1027     count = count1;
1028     /* first write to align to sector start */
1029     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1030     if (len > count)
1031         len = count;
1032     sector_num = offset >> BDRV_SECTOR_BITS;
1033     if (len > 0) {
1034         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1035             return ret;
1036         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1037         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1038             return ret;
1039         count -= len;
1040         if (count == 0)
1041             return count1;
1042         sector_num++;
1043         buf += len;
1044     }
1045
1046     /* write the sectors "in place" */
1047     nb_sectors = count >> BDRV_SECTOR_BITS;
1048     if (nb_sectors > 0) {
1049         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1050             return ret;
1051         sector_num += nb_sectors;
1052         len = nb_sectors << BDRV_SECTOR_BITS;
1053         buf += len;
1054         count -= len;
1055     }
1056
1057     /* add data from the last sector */
1058     if (count > 0) {
1059         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1060             return ret;
1061         memcpy(tmp_buf, buf, count);
1062         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1063             return ret;
1064     }
1065     return count1;
1066 }
1067
1068 /*
1069  * Writes to the file and ensures that no writes are reordered across this
1070  * request (acts as a barrier)
1071  *
1072  * Returns 0 on success, -errno in error cases.
1073  */
1074 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1075     const void *buf, int count)
1076 {
1077     int ret;
1078
1079     ret = bdrv_pwrite(bs, offset, buf, count);
1080     if (ret < 0) {
1081         return ret;
1082     }
1083
1084     /* No flush needed for cache=writethrough, it uses O_DSYNC */
1085     if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1086         bdrv_flush(bs);
1087     }
1088
1089     return 0;
1090 }
1091
1092 /*
1093  * Writes to the file and ensures that no writes are reordered across this
1094  * request (acts as a barrier)
1095  *
1096  * Returns 0 on success, -errno in error cases.
1097  */
1098 int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1099     const uint8_t *buf, int nb_sectors)
1100 {
1101     return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1102         buf, BDRV_SECTOR_SIZE * nb_sectors);
1103 }
1104
1105 /**
1106  * Truncate file to 'offset' bytes (needed only for file protocols)
1107  */
1108 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1109 {
1110     BlockDriver *drv = bs->drv;
1111     int ret;
1112     if (!drv)
1113         return -ENOMEDIUM;
1114     if (!drv->bdrv_truncate)
1115         return -ENOTSUP;
1116     if (bs->read_only)
1117         return -EACCES;
1118     ret = drv->bdrv_truncate(bs, offset);
1119     if (ret == 0) {
1120         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1121     }
1122     return ret;
1123 }
1124
1125 /**
1126  * Length of a file in bytes. Return < 0 if error or unknown.
1127  */
1128 int64_t bdrv_getlength(BlockDriverState *bs)
1129 {
1130     BlockDriver *drv = bs->drv;
1131     if (!drv)
1132         return -ENOMEDIUM;
1133
1134     /* Fixed size devices use the total_sectors value for speed instead of
1135        issuing a length query (like lseek) on each call.  Also, legacy block
1136        drivers don't provide a bdrv_getlength function and must use
1137        total_sectors. */
1138     if (!bs->growable || !drv->bdrv_getlength) {
1139         return bs->total_sectors * BDRV_SECTOR_SIZE;
1140     }
1141     return drv->bdrv_getlength(bs);
1142 }
1143
1144 /* return 0 as number of sectors if no device present or error */
1145 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1146 {
1147     int64_t length;
1148     length = bdrv_getlength(bs);
1149     if (length < 0)
1150         length = 0;
1151     else
1152         length = length >> BDRV_SECTOR_BITS;
1153     *nb_sectors_ptr = length;
1154 }
1155
1156 struct partition {
1157         uint8_t boot_ind;           /* 0x80 - active */
1158         uint8_t head;               /* starting head */
1159         uint8_t sector;             /* starting sector */
1160         uint8_t cyl;                /* starting cylinder */
1161         uint8_t sys_ind;            /* What partition type */
1162         uint8_t end_head;           /* end head */
1163         uint8_t end_sector;         /* end sector */
1164         uint8_t end_cyl;            /* end cylinder */
1165         uint32_t start_sect;        /* starting sector counting from 0 */
1166         uint32_t nr_sects;          /* nr of sectors in partition */
1167 } __attribute__((packed));
1168
1169 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1170 static int guess_disk_lchs(BlockDriverState *bs,
1171                            int *pcylinders, int *pheads, int *psectors)
1172 {
1173     uint8_t buf[BDRV_SECTOR_SIZE];
1174     int ret, i, heads, sectors, cylinders;
1175     struct partition *p;
1176     uint32_t nr_sects;
1177     uint64_t nb_sectors;
1178
1179     bdrv_get_geometry(bs, &nb_sectors);
1180
1181     ret = bdrv_read(bs, 0, buf, 1);
1182     if (ret < 0)
1183         return -1;
1184     /* test msdos magic */
1185     if (buf[510] != 0x55 || buf[511] != 0xaa)
1186         return -1;
1187     for(i = 0; i < 4; i++) {
1188         p = ((struct partition *)(buf + 0x1be)) + i;
1189         nr_sects = le32_to_cpu(p->nr_sects);
1190         if (nr_sects && p->end_head) {
1191             /* We make the assumption that the partition terminates on
1192                a cylinder boundary */
1193             heads = p->end_head + 1;
1194             sectors = p->end_sector & 63;
1195             if (sectors == 0)
1196                 continue;
1197             cylinders = nb_sectors / (heads * sectors);
1198             if (cylinders < 1 || cylinders > 16383)
1199                 continue;
1200             *pheads = heads;
1201             *psectors = sectors;
1202             *pcylinders = cylinders;
1203 #if 0
1204             printf("guessed geometry: LCHS=%d %d %d\n",
1205                    cylinders, heads, sectors);
1206 #endif
1207             return 0;
1208         }
1209     }
1210     return -1;
1211 }
1212
1213 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1214 {
1215     int translation, lba_detected = 0;
1216     int cylinders, heads, secs;
1217     uint64_t nb_sectors;
1218
1219     /* if a geometry hint is available, use it */
1220     bdrv_get_geometry(bs, &nb_sectors);
1221     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1222     translation = bdrv_get_translation_hint(bs);
1223     if (cylinders != 0) {
1224         *pcyls = cylinders;
1225         *pheads = heads;
1226         *psecs = secs;
1227     } else {
1228         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1229             if (heads > 16) {
1230                 /* if heads > 16, it means that a BIOS LBA
1231                    translation was active, so the default
1232                    hardware geometry is OK */
1233                 lba_detected = 1;
1234                 goto default_geometry;
1235             } else {
1236                 *pcyls = cylinders;
1237                 *pheads = heads;
1238                 *psecs = secs;
1239                 /* disable any translation to be in sync with
1240                    the logical geometry */
1241                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1242                     bdrv_set_translation_hint(bs,
1243                                               BIOS_ATA_TRANSLATION_NONE);
1244                 }
1245             }
1246         } else {
1247         default_geometry:
1248             /* if no geometry, use a standard physical disk geometry */
1249             cylinders = nb_sectors / (16 * 63);
1250
1251             if (cylinders > 16383)
1252                 cylinders = 16383;
1253             else if (cylinders < 2)
1254                 cylinders = 2;
1255             *pcyls = cylinders;
1256             *pheads = 16;
1257             *psecs = 63;
1258             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1259                 if ((*pcyls * *pheads) <= 131072) {
1260                     bdrv_set_translation_hint(bs,
1261                                               BIOS_ATA_TRANSLATION_LARGE);
1262                 } else {
1263                     bdrv_set_translation_hint(bs,
1264                                               BIOS_ATA_TRANSLATION_LBA);
1265                 }
1266             }
1267         }
1268         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1269     }
1270 }
1271
1272 void bdrv_set_geometry_hint(BlockDriverState *bs,
1273                             int cyls, int heads, int secs)
1274 {
1275     bs->cyls = cyls;
1276     bs->heads = heads;
1277     bs->secs = secs;
1278 }
1279
1280 void bdrv_set_type_hint(BlockDriverState *bs, int type)
1281 {
1282     bs->type = type;
1283     bs->removable = ((type == BDRV_TYPE_CDROM ||
1284                       type == BDRV_TYPE_FLOPPY));
1285 }
1286
1287 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1288 {
1289     bs->translation = translation;
1290 }
1291
1292 void bdrv_get_geometry_hint(BlockDriverState *bs,
1293                             int *pcyls, int *pheads, int *psecs)
1294 {
1295     *pcyls = bs->cyls;
1296     *pheads = bs->heads;
1297     *psecs = bs->secs;
1298 }
1299
1300 int bdrv_get_type_hint(BlockDriverState *bs)
1301 {
1302     return bs->type;
1303 }
1304
1305 int bdrv_get_translation_hint(BlockDriverState *bs)
1306 {
1307     return bs->translation;
1308 }
1309
1310 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1311                        BlockErrorAction on_write_error)
1312 {
1313     bs->on_read_error = on_read_error;
1314     bs->on_write_error = on_write_error;
1315 }
1316
1317 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1318 {
1319     return is_read ? bs->on_read_error : bs->on_write_error;
1320 }
1321
1322 void bdrv_set_removable(BlockDriverState *bs, int removable)
1323 {
1324     bs->removable = removable;
1325     if (removable && bs == bs_snapshots) {
1326         bs_snapshots = NULL;
1327     }
1328 }
1329
1330 int bdrv_is_removable(BlockDriverState *bs)
1331 {
1332     return bs->removable;
1333 }
1334
1335 int bdrv_is_read_only(BlockDriverState *bs)
1336 {
1337     return bs->read_only;
1338 }
1339
1340 int bdrv_is_sg(BlockDriverState *bs)
1341 {
1342     return bs->sg;
1343 }
1344
1345 int bdrv_enable_write_cache(BlockDriverState *bs)
1346 {
1347     return bs->enable_write_cache;
1348 }
1349
1350 /* XXX: no longer used */
1351 void bdrv_set_change_cb(BlockDriverState *bs,
1352                         void (*change_cb)(void *opaque), void *opaque)
1353 {
1354     bs->change_cb = change_cb;
1355     bs->change_opaque = opaque;
1356 }
1357
1358 int bdrv_is_encrypted(BlockDriverState *bs)
1359 {
1360     if (bs->backing_hd && bs->backing_hd->encrypted)
1361         return 1;
1362     return bs->encrypted;
1363 }
1364
1365 int bdrv_key_required(BlockDriverState *bs)
1366 {
1367     BlockDriverState *backing_hd = bs->backing_hd;
1368
1369     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1370         return 1;
1371     return (bs->encrypted && !bs->valid_key);
1372 }
1373
1374 int bdrv_set_key(BlockDriverState *bs, const char *key)
1375 {
1376     int ret;
1377     if (bs->backing_hd && bs->backing_hd->encrypted) {
1378         ret = bdrv_set_key(bs->backing_hd, key);
1379         if (ret < 0)
1380             return ret;
1381         if (!bs->encrypted)
1382             return 0;
1383     }
1384     if (!bs->encrypted) {
1385         return -EINVAL;
1386     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1387         return -ENOMEDIUM;
1388     }
1389     ret = bs->drv->bdrv_set_key(bs, key);
1390     if (ret < 0) {
1391         bs->valid_key = 0;
1392     } else if (!bs->valid_key) {
1393         bs->valid_key = 1;
1394         /* call the change callback now, we skipped it on open */
1395         bs->media_changed = 1;
1396         if (bs->change_cb)
1397             bs->change_cb(bs->change_opaque);
1398     }
1399     return ret;
1400 }
1401
1402 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1403 {
1404     if (!bs->drv) {
1405         buf[0] = '\0';
1406     } else {
1407         pstrcpy(buf, buf_size, bs->drv->format_name);
1408     }
1409 }
1410
1411 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1412                          void *opaque)
1413 {
1414     BlockDriver *drv;
1415
1416     QLIST_FOREACH(drv, &bdrv_drivers, list) {
1417         it(opaque, drv->format_name);
1418     }
1419 }
1420
1421 BlockDriverState *bdrv_find(const char *name)
1422 {
1423     BlockDriverState *bs;
1424
1425     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1426         if (!strcmp(name, bs->device_name)) {
1427             return bs;
1428         }
1429     }
1430     return NULL;
1431 }
1432
1433 BlockDriverState *bdrv_next(BlockDriverState *bs)
1434 {
1435     if (!bs) {
1436         return QTAILQ_FIRST(&bdrv_states);
1437     }
1438     return QTAILQ_NEXT(bs, list);
1439 }
1440
1441 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1442 {
1443     BlockDriverState *bs;
1444
1445     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1446         it(opaque, bs);
1447     }
1448 }
1449
1450 const char *bdrv_get_device_name(BlockDriverState *bs)
1451 {
1452     return bs->device_name;
1453 }
1454
1455 void bdrv_flush(BlockDriverState *bs)
1456 {
1457     if (bs->open_flags & BDRV_O_NO_FLUSH) {
1458         return;
1459     }
1460
1461     if (bs->drv && bs->drv->bdrv_flush)
1462         bs->drv->bdrv_flush(bs);
1463 }
1464
1465 void bdrv_flush_all(void)
1466 {
1467     BlockDriverState *bs;
1468
1469     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1470         if (bs->drv && !bdrv_is_read_only(bs) &&
1471             (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1472             bdrv_flush(bs);
1473         }
1474     }
1475 }
1476
1477 int bdrv_has_zero_init(BlockDriverState *bs)
1478 {
1479     assert(bs->drv);
1480
1481     if (bs->drv->bdrv_has_zero_init) {
1482         return bs->drv->bdrv_has_zero_init(bs);
1483     }
1484
1485     return 1;
1486 }
1487
1488 /*
1489  * Returns true iff the specified sector is present in the disk image. Drivers
1490  * not implementing the functionality are assumed to not support backing files,
1491  * hence all their sectors are reported as allocated.
1492  *
1493  * 'pnum' is set to the number of sectors (including and immediately following
1494  * the specified sector) that are known to be in the same
1495  * allocated/unallocated state.
1496  *
1497  * 'nb_sectors' is the max value 'pnum' should be set to.
1498  */
1499 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1500         int *pnum)
1501 {
1502     int64_t n;
1503     if (!bs->drv->bdrv_is_allocated) {
1504         if (sector_num >= bs->total_sectors) {
1505             *pnum = 0;
1506             return 0;
1507         }
1508         n = bs->total_sectors - sector_num;
1509         *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1510         return 1;
1511     }
1512     return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1513 }
1514
1515 void bdrv_mon_event(const BlockDriverState *bdrv,
1516                     BlockMonEventAction action, int is_read)
1517 {
1518     QObject *data;
1519     const char *action_str;
1520
1521     switch (action) {
1522     case BDRV_ACTION_REPORT:
1523         action_str = "report";
1524         break;
1525     case BDRV_ACTION_IGNORE:
1526         action_str = "ignore";
1527         break;
1528     case BDRV_ACTION_STOP:
1529         action_str = "stop";
1530         break;
1531     default:
1532         abort();
1533     }
1534
1535     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1536                               bdrv->device_name,
1537                               action_str,
1538                               is_read ? "read" : "write");
1539     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1540
1541     qobject_decref(data);
1542 }
1543
1544 static void bdrv_print_dict(QObject *obj, void *opaque)
1545 {
1546     QDict *bs_dict;
1547     Monitor *mon = opaque;
1548
1549     bs_dict = qobject_to_qdict(obj);
1550
1551     monitor_printf(mon, "%s: type=%s removable=%d",
1552                         qdict_get_str(bs_dict, "device"),
1553                         qdict_get_str(bs_dict, "type"),
1554                         qdict_get_bool(bs_dict, "removable"));
1555
1556     if (qdict_get_bool(bs_dict, "removable")) {
1557         monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1558     }
1559
1560     if (qdict_haskey(bs_dict, "inserted")) {
1561         QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1562
1563         monitor_printf(mon, " file=");
1564         monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1565         if (qdict_haskey(qdict, "backing_file")) {
1566             monitor_printf(mon, " backing_file=");
1567             monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1568         }
1569         monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1570                             qdict_get_bool(qdict, "ro"),
1571                             qdict_get_str(qdict, "drv"),
1572                             qdict_get_bool(qdict, "encrypted"));
1573     } else {
1574         monitor_printf(mon, " [not inserted]");
1575     }
1576
1577     monitor_printf(mon, "\n");
1578 }
1579
1580 void bdrv_info_print(Monitor *mon, const QObject *data)
1581 {
1582     qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1583 }
1584
1585 void bdrv_info(Monitor *mon, QObject **ret_data)
1586 {
1587     QList *bs_list;
1588     BlockDriverState *bs;
1589
1590     bs_list = qlist_new();
1591
1592     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1593         QObject *bs_obj;
1594         const char *type = "unknown";
1595
1596         switch(bs->type) {
1597         case BDRV_TYPE_HD:
1598             type = "hd";
1599             break;
1600         case BDRV_TYPE_CDROM:
1601             type = "cdrom";
1602             break;
1603         case BDRV_TYPE_FLOPPY:
1604             type = "floppy";
1605             break;
1606         }
1607
1608         bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1609                                     "'removable': %i, 'locked': %i }",
1610                                     bs->device_name, type, bs->removable,
1611                                     bs->locked);
1612
1613         if (bs->drv) {
1614             QObject *obj;
1615             QDict *bs_dict = qobject_to_qdict(bs_obj);
1616
1617             obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1618                                      "'encrypted': %i }",
1619                                      bs->filename, bs->read_only,
1620                                      bs->drv->format_name,
1621                                      bdrv_is_encrypted(bs));
1622             if (bs->backing_file[0] != '\0') {
1623                 QDict *qdict = qobject_to_qdict(obj);
1624                 qdict_put(qdict, "backing_file",
1625                           qstring_from_str(bs->backing_file));
1626             }
1627
1628             qdict_put_obj(bs_dict, "inserted", obj);
1629         }
1630         qlist_append_obj(bs_list, bs_obj);
1631     }
1632
1633     *ret_data = QOBJECT(bs_list);
1634 }
1635
1636 static void bdrv_stats_iter(QObject *data, void *opaque)
1637 {
1638     QDict *qdict;
1639     Monitor *mon = opaque;
1640
1641     qdict = qobject_to_qdict(data);
1642     monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1643
1644     qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1645     monitor_printf(mon, " rd_bytes=%" PRId64
1646                         " wr_bytes=%" PRId64
1647                         " rd_operations=%" PRId64
1648                         " wr_operations=%" PRId64
1649                         "\n",
1650                         qdict_get_int(qdict, "rd_bytes"),
1651                         qdict_get_int(qdict, "wr_bytes"),
1652                         qdict_get_int(qdict, "rd_operations"),
1653                         qdict_get_int(qdict, "wr_operations"));
1654 }
1655
1656 void bdrv_stats_print(Monitor *mon, const QObject *data)
1657 {
1658     qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1659 }
1660
1661 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1662 {
1663     QObject *res;
1664     QDict *dict;
1665
1666     res = qobject_from_jsonf("{ 'stats': {"
1667                              "'rd_bytes': %" PRId64 ","
1668                              "'wr_bytes': %" PRId64 ","
1669                              "'rd_operations': %" PRId64 ","
1670                              "'wr_operations': %" PRId64 ","
1671                              "'wr_highest_offset': %" PRId64
1672                              "} }",
1673                              bs->rd_bytes, bs->wr_bytes,
1674                              bs->rd_ops, bs->wr_ops,
1675                              bs->wr_highest_sector *
1676                              (uint64_t)BDRV_SECTOR_SIZE);
1677     dict  = qobject_to_qdict(res);
1678
1679     if (*bs->device_name) {
1680         qdict_put(dict, "device", qstring_from_str(bs->device_name));
1681     }
1682
1683     if (bs->file) {
1684         QObject *parent = bdrv_info_stats_bs(bs->file);
1685         qdict_put_obj(dict, "parent", parent);
1686     }
1687
1688     return res;
1689 }
1690
1691 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1692 {
1693     QObject *obj;
1694     QList *devices;
1695     BlockDriverState *bs;
1696
1697     devices = qlist_new();
1698
1699     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1700         obj = bdrv_info_stats_bs(bs);
1701         qlist_append_obj(devices, obj);
1702     }
1703
1704     *ret_data = QOBJECT(devices);
1705 }
1706
1707 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1708 {
1709     if (bs->backing_hd && bs->backing_hd->encrypted)
1710         return bs->backing_file;
1711     else if (bs->encrypted)
1712         return bs->filename;
1713     else
1714         return NULL;
1715 }
1716
1717 void bdrv_get_backing_filename(BlockDriverState *bs,
1718                                char *filename, int filename_size)
1719 {
1720     if (!bs->backing_file) {
1721         pstrcpy(filename, filename_size, "");
1722     } else {
1723         pstrcpy(filename, filename_size, bs->backing_file);
1724     }
1725 }
1726
1727 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1728                           const uint8_t *buf, int nb_sectors)
1729 {
1730     BlockDriver *drv = bs->drv;
1731     if (!drv)
1732         return -ENOMEDIUM;
1733     if (!drv->bdrv_write_compressed)
1734         return -ENOTSUP;
1735     if (bdrv_check_request(bs, sector_num, nb_sectors))
1736         return -EIO;
1737
1738     if (bs->dirty_bitmap) {
1739         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1740     }
1741
1742     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1743 }
1744
1745 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1746 {
1747     BlockDriver *drv = bs->drv;
1748     if (!drv)
1749         return -ENOMEDIUM;
1750     if (!drv->bdrv_get_info)
1751         return -ENOTSUP;
1752     memset(bdi, 0, sizeof(*bdi));
1753     return drv->bdrv_get_info(bs, bdi);
1754 }
1755
1756 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1757                       int64_t pos, int size)
1758 {
1759     BlockDriver *drv = bs->drv;
1760     if (!drv)
1761         return -ENOMEDIUM;
1762     if (drv->bdrv_save_vmstate)
1763         return drv->bdrv_save_vmstate(bs, buf, pos, size);
1764     if (bs->file)
1765         return bdrv_save_vmstate(bs->file, buf, pos, size);
1766     return -ENOTSUP;
1767 }
1768
1769 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1770                       int64_t pos, int size)
1771 {
1772     BlockDriver *drv = bs->drv;
1773     if (!drv)
1774         return -ENOMEDIUM;
1775     if (drv->bdrv_load_vmstate)
1776         return drv->bdrv_load_vmstate(bs, buf, pos, size);
1777     if (bs->file)
1778         return bdrv_load_vmstate(bs->file, buf, pos, size);
1779     return -ENOTSUP;
1780 }
1781
1782 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1783 {
1784     BlockDriver *drv = bs->drv;
1785
1786     if (!drv || !drv->bdrv_debug_event) {
1787         return;
1788     }
1789
1790     return drv->bdrv_debug_event(bs, event);
1791
1792 }
1793
1794 /**************************************************************/
1795 /* handling of snapshots */
1796
1797 int bdrv_can_snapshot(BlockDriverState *bs)
1798 {
1799     BlockDriver *drv = bs->drv;
1800     if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1801         return 0;
1802     }
1803
1804     if (!drv->bdrv_snapshot_create) {
1805         if (bs->file != NULL) {
1806             return bdrv_can_snapshot(bs->file);
1807         }
1808         return 0;
1809     }
1810
1811     return 1;
1812 }
1813
1814 int bdrv_is_snapshot(BlockDriverState *bs)
1815 {
1816     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
1817 }
1818
1819 BlockDriverState *bdrv_snapshots(void)
1820 {
1821     BlockDriverState *bs;
1822
1823     if (bs_snapshots) {
1824         return bs_snapshots;
1825     }
1826
1827     bs = NULL;
1828     while ((bs = bdrv_next(bs))) {
1829         if (bdrv_can_snapshot(bs)) {
1830             bs_snapshots = bs;
1831             return bs;
1832         }
1833     }
1834     return NULL;
1835 }
1836
1837 int bdrv_snapshot_create(BlockDriverState *bs,
1838                          QEMUSnapshotInfo *sn_info)
1839 {
1840     BlockDriver *drv = bs->drv;
1841     if (!drv)
1842         return -ENOMEDIUM;
1843     if (drv->bdrv_snapshot_create)
1844         return drv->bdrv_snapshot_create(bs, sn_info);
1845     if (bs->file)
1846         return bdrv_snapshot_create(bs->file, sn_info);
1847     return -ENOTSUP;
1848 }
1849
1850 int bdrv_snapshot_goto(BlockDriverState *bs,
1851                        const char *snapshot_id)
1852 {
1853     BlockDriver *drv = bs->drv;
1854     int ret, open_ret;
1855
1856     if (!drv)
1857         return -ENOMEDIUM;
1858     if (drv->bdrv_snapshot_goto)
1859         return drv->bdrv_snapshot_goto(bs, snapshot_id);
1860
1861     if (bs->file) {
1862         drv->bdrv_close(bs);
1863         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
1864         open_ret = drv->bdrv_open(bs, bs->open_flags);
1865         if (open_ret < 0) {
1866             bdrv_delete(bs->file);
1867             bs->drv = NULL;
1868             return open_ret;
1869         }
1870         return ret;
1871     }
1872
1873     return -ENOTSUP;
1874 }
1875
1876 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1877 {
1878     BlockDriver *drv = bs->drv;
1879     if (!drv)
1880         return -ENOMEDIUM;
1881     if (drv->bdrv_snapshot_delete)
1882         return drv->bdrv_snapshot_delete(bs, snapshot_id);
1883     if (bs->file)
1884         return bdrv_snapshot_delete(bs->file, snapshot_id);
1885     return -ENOTSUP;
1886 }
1887
1888 int bdrv_snapshot_list(BlockDriverState *bs,
1889                        QEMUSnapshotInfo **psn_info)
1890 {
1891     BlockDriver *drv = bs->drv;
1892     if (!drv)
1893         return -ENOMEDIUM;
1894     if (drv->bdrv_snapshot_list)
1895         return drv->bdrv_snapshot_list(bs, psn_info);
1896     if (bs->file)
1897         return bdrv_snapshot_list(bs->file, psn_info);
1898     return -ENOTSUP;
1899 }
1900
1901 #define NB_SUFFIXES 4
1902
1903 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1904 {
1905     static const char suffixes[NB_SUFFIXES] = "KMGT";
1906     int64_t base;
1907     int i;
1908
1909     if (size <= 999) {
1910         snprintf(buf, buf_size, "%" PRId64, size);
1911     } else {
1912         base = 1024;
1913         for(i = 0; i < NB_SUFFIXES; i++) {
1914             if (size < (10 * base)) {
1915                 snprintf(buf, buf_size, "%0.1f%c",
1916                          (double)size / base,
1917                          suffixes[i]);
1918                 break;
1919             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1920                 snprintf(buf, buf_size, "%" PRId64 "%c",
1921                          ((size + (base >> 1)) / base),
1922                          suffixes[i]);
1923                 break;
1924             }
1925             base = base * 1024;
1926         }
1927     }
1928     return buf;
1929 }
1930
1931 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1932 {
1933     char buf1[128], date_buf[128], clock_buf[128];
1934 #ifdef _WIN32
1935     struct tm *ptm;
1936 #else
1937     struct tm tm;
1938 #endif
1939     time_t ti;
1940     int64_t secs;
1941
1942     if (!sn) {
1943         snprintf(buf, buf_size,
1944                  "%-10s%-20s%7s%20s%15s",
1945                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1946     } else {
1947         ti = sn->date_sec;
1948 #ifdef _WIN32
1949         ptm = localtime(&ti);
1950         strftime(date_buf, sizeof(date_buf),
1951                  "%Y-%m-%d %H:%M:%S", ptm);
1952 #else
1953         localtime_r(&ti, &tm);
1954         strftime(date_buf, sizeof(date_buf),
1955                  "%Y-%m-%d %H:%M:%S", &tm);
1956 #endif
1957         secs = sn->vm_clock_nsec / 1000000000;
1958         snprintf(clock_buf, sizeof(clock_buf),
1959                  "%02d:%02d:%02d.%03d",
1960                  (int)(secs / 3600),
1961                  (int)((secs / 60) % 60),
1962                  (int)(secs % 60),
1963                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
1964         snprintf(buf, buf_size,
1965                  "%-10s%-20s%7s%20s%15s",
1966                  sn->id_str, sn->name,
1967                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1968                  date_buf,
1969                  clock_buf);
1970     }
1971     return buf;
1972 }
1973
1974
1975 /**************************************************************/
1976 /* async I/Os */
1977
1978 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1979                                  QEMUIOVector *qiov, int nb_sectors,
1980                                  BlockDriverCompletionFunc *cb, void *opaque)
1981 {
1982     BlockDriver *drv = bs->drv;
1983     BlockDriverAIOCB *ret;
1984
1985     if (!drv)
1986         return NULL;
1987     if (bdrv_check_request(bs, sector_num, nb_sectors))
1988         return NULL;
1989
1990     ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1991                               cb, opaque);
1992
1993     if (ret) {
1994         /* Update stats even though technically transfer has not happened. */
1995         bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1996         bs->rd_ops ++;
1997     }
1998
1999     return ret;
2000 }
2001
2002 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2003                                   QEMUIOVector *qiov, int nb_sectors,
2004                                   BlockDriverCompletionFunc *cb, void *opaque)
2005 {
2006     BlockDriver *drv = bs->drv;
2007     BlockDriverAIOCB *ret;
2008
2009     if (!drv)
2010         return NULL;
2011     if (bs->read_only)
2012         return NULL;
2013     if (bdrv_check_request(bs, sector_num, nb_sectors))
2014         return NULL;
2015
2016     if (bs->dirty_bitmap) {
2017         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2018     }
2019
2020     ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2021                                cb, opaque);
2022
2023     if (ret) {
2024         /* Update stats even though technically transfer has not happened. */
2025         bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2026         bs->wr_ops ++;
2027         if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2028             bs->wr_highest_sector = sector_num + nb_sectors - 1;
2029         }
2030     }
2031
2032     return ret;
2033 }
2034
2035
2036 typedef struct MultiwriteCB {
2037     int error;
2038     int num_requests;
2039     int num_callbacks;
2040     struct {
2041         BlockDriverCompletionFunc *cb;
2042         void *opaque;
2043         QEMUIOVector *free_qiov;
2044         void *free_buf;
2045     } callbacks[];
2046 } MultiwriteCB;
2047
2048 static void multiwrite_user_cb(MultiwriteCB *mcb)
2049 {
2050     int i;
2051
2052     for (i = 0; i < mcb->num_callbacks; i++) {
2053         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2054         if (mcb->callbacks[i].free_qiov) {
2055             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2056         }
2057         qemu_free(mcb->callbacks[i].free_qiov);
2058         qemu_vfree(mcb->callbacks[i].free_buf);
2059     }
2060 }
2061
2062 static void multiwrite_cb(void *opaque, int ret)
2063 {
2064     MultiwriteCB *mcb = opaque;
2065
2066     if (ret < 0 && !mcb->error) {
2067         mcb->error = ret;
2068     }
2069
2070     mcb->num_requests--;
2071     if (mcb->num_requests == 0) {
2072         multiwrite_user_cb(mcb);
2073         qemu_free(mcb);
2074     }
2075 }
2076
2077 static int multiwrite_req_compare(const void *a, const void *b)
2078 {
2079     const BlockRequest *req1 = a, *req2 = b;
2080
2081     /*
2082      * Note that we can't simply subtract req2->sector from req1->sector
2083      * here as that could overflow the return value.
2084      */
2085     if (req1->sector > req2->sector) {
2086         return 1;
2087     } else if (req1->sector < req2->sector) {
2088         return -1;
2089     } else {
2090         return 0;
2091     }
2092 }
2093
2094 /*
2095  * Takes a bunch of requests and tries to merge them. Returns the number of
2096  * requests that remain after merging.
2097  */
2098 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2099     int num_reqs, MultiwriteCB *mcb)
2100 {
2101     int i, outidx;
2102
2103     // Sort requests by start sector
2104     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2105
2106     // Check if adjacent requests touch the same clusters. If so, combine them,
2107     // filling up gaps with zero sectors.
2108     outidx = 0;
2109     for (i = 1; i < num_reqs; i++) {
2110         int merge = 0;
2111         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2112
2113         // This handles the cases that are valid for all block drivers, namely
2114         // exactly sequential writes and overlapping writes.
2115         if (reqs[i].sector <= oldreq_last) {
2116             merge = 1;
2117         }
2118
2119         // The block driver may decide that it makes sense to combine requests
2120         // even if there is a gap of some sectors between them. In this case,
2121         // the gap is filled with zeros (therefore only applicable for yet
2122         // unused space in format like qcow2).
2123         if (!merge && bs->drv->bdrv_merge_requests) {
2124             merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2125         }
2126
2127         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2128             merge = 0;
2129         }
2130
2131         if (merge) {
2132             size_t size;
2133             QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2134             qemu_iovec_init(qiov,
2135                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2136
2137             // Add the first request to the merged one. If the requests are
2138             // overlapping, drop the last sectors of the first request.
2139             size = (reqs[i].sector - reqs[outidx].sector) << 9;
2140             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2141
2142             // We might need to add some zeros between the two requests
2143             if (reqs[i].sector > oldreq_last) {
2144                 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2145                 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2146                 memset(buf, 0, zero_bytes);
2147                 qemu_iovec_add(qiov, buf, zero_bytes);
2148                 mcb->callbacks[i].free_buf = buf;
2149             }
2150
2151             // Add the second request
2152             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2153
2154             reqs[outidx].nb_sectors = qiov->size >> 9;
2155             reqs[outidx].qiov = qiov;
2156
2157             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2158         } else {
2159             outidx++;
2160             reqs[outidx].sector     = reqs[i].sector;
2161             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2162             reqs[outidx].qiov       = reqs[i].qiov;
2163         }
2164     }
2165
2166     return outidx + 1;
2167 }
2168
2169 /*
2170  * Submit multiple AIO write requests at once.
2171  *
2172  * On success, the function returns 0 and all requests in the reqs array have
2173  * been submitted. In error case this function returns -1, and any of the
2174  * requests may or may not be submitted yet. In particular, this means that the
2175  * callback will be called for some of the requests, for others it won't. The
2176  * caller must check the error field of the BlockRequest to wait for the right
2177  * callbacks (if error != 0, no callback will be called).
2178  *
2179  * The implementation may modify the contents of the reqs array, e.g. to merge
2180  * requests. However, the fields opaque and error are left unmodified as they
2181  * are used to signal failure for a single request to the caller.
2182  */
2183 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2184 {
2185     BlockDriverAIOCB *acb;
2186     MultiwriteCB *mcb;
2187     int i;
2188
2189     if (num_reqs == 0) {
2190         return 0;
2191     }
2192
2193     // Create MultiwriteCB structure
2194     mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2195     mcb->num_requests = 0;
2196     mcb->num_callbacks = num_reqs;
2197
2198     for (i = 0; i < num_reqs; i++) {
2199         mcb->callbacks[i].cb = reqs[i].cb;
2200         mcb->callbacks[i].opaque = reqs[i].opaque;
2201     }
2202
2203     // Check for mergable requests
2204     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2205
2206     /*
2207      * Run the aio requests. As soon as one request can't be submitted
2208      * successfully, fail all requests that are not yet submitted (we must
2209      * return failure for all requests anyway)
2210      *
2211      * num_requests cannot be set to the right value immediately: If
2212      * bdrv_aio_writev fails for some request, num_requests would be too high
2213      * and therefore multiwrite_cb() would never recognize the multiwrite
2214      * request as completed. We also cannot use the loop variable i to set it
2215      * when the first request fails because the callback may already have been
2216      * called for previously submitted requests. Thus, num_requests must be
2217      * incremented for each request that is submitted.
2218      *
2219      * The problem that callbacks may be called early also means that we need
2220      * to take care that num_requests doesn't become 0 before all requests are
2221      * submitted - multiwrite_cb() would consider the multiwrite request
2222      * completed. A dummy request that is "completed" by a manual call to
2223      * multiwrite_cb() takes care of this.
2224      */
2225     mcb->num_requests = 1;
2226
2227     for (i = 0; i < num_reqs; i++) {
2228         mcb->num_requests++;
2229         acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2230             reqs[i].nb_sectors, multiwrite_cb, mcb);
2231
2232         if (acb == NULL) {
2233             // We can only fail the whole thing if no request has been
2234             // submitted yet. Otherwise we'll wait for the submitted AIOs to
2235             // complete and report the error in the callback.
2236             if (i == 0) {
2237                 goto fail;
2238             } else {
2239                 multiwrite_cb(mcb, -EIO);
2240                 break;
2241             }
2242         }
2243     }
2244
2245     /* Complete the dummy request */
2246     multiwrite_cb(mcb, 0);
2247
2248     return 0;
2249
2250 fail:
2251     for (i = 0; i < mcb->num_callbacks; i++) {
2252         reqs[i].error = -EIO;
2253     }
2254     qemu_free(mcb);
2255     return -1;
2256 }
2257
2258 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2259         BlockDriverCompletionFunc *cb, void *opaque)
2260 {
2261     BlockDriver *drv = bs->drv;
2262
2263     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2264         return bdrv_aio_noop_em(bs, cb, opaque);
2265     }
2266
2267     if (!drv)
2268         return NULL;
2269     return drv->bdrv_aio_flush(bs, cb, opaque);
2270 }
2271
2272 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2273 {
2274     acb->pool->cancel(acb);
2275 }
2276
2277
2278 /**************************************************************/
2279 /* async block device emulation */
2280
2281 typedef struct BlockDriverAIOCBSync {
2282     BlockDriverAIOCB common;
2283     QEMUBH *bh;
2284     int ret;
2285     /* vector translation state */
2286     QEMUIOVector *qiov;
2287     uint8_t *bounce;
2288     int is_write;
2289 } BlockDriverAIOCBSync;
2290
2291 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2292 {
2293     BlockDriverAIOCBSync *acb =
2294         container_of(blockacb, BlockDriverAIOCBSync, common);
2295     qemu_bh_delete(acb->bh);
2296     acb->bh = NULL;
2297     qemu_aio_release(acb);
2298 }
2299
2300 static AIOPool bdrv_em_aio_pool = {
2301     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2302     .cancel             = bdrv_aio_cancel_em,
2303 };
2304
2305 static void bdrv_aio_bh_cb(void *opaque)
2306 {
2307     BlockDriverAIOCBSync *acb = opaque;
2308
2309     if (!acb->is_write)
2310         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2311     qemu_vfree(acb->bounce);
2312     acb->common.cb(acb->common.opaque, acb->ret);
2313     qemu_bh_delete(acb->bh);
2314     acb->bh = NULL;
2315     qemu_aio_release(acb);
2316 }
2317
2318 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2319                                             int64_t sector_num,
2320                                             QEMUIOVector *qiov,
2321                                             int nb_sectors,
2322                                             BlockDriverCompletionFunc *cb,
2323                                             void *opaque,
2324                                             int is_write)
2325
2326 {
2327     BlockDriverAIOCBSync *acb;
2328
2329     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2330     acb->is_write = is_write;
2331     acb->qiov = qiov;
2332     acb->bounce = qemu_blockalign(bs, qiov->size);
2333
2334     if (!acb->bh)
2335         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2336
2337     if (is_write) {
2338         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2339         acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2340     } else {
2341         acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2342     }
2343
2344     qemu_bh_schedule(acb->bh);
2345
2346     return &acb->common;
2347 }
2348
2349 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2350         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2351         BlockDriverCompletionFunc *cb, void *opaque)
2352 {
2353     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2354 }
2355
2356 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2357         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2358         BlockDriverCompletionFunc *cb, void *opaque)
2359 {
2360     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2361 }
2362
2363 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2364         BlockDriverCompletionFunc *cb, void *opaque)
2365 {
2366     BlockDriverAIOCBSync *acb;
2367
2368     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2369     acb->is_write = 1; /* don't bounce in the completion hadler */
2370     acb->qiov = NULL;
2371     acb->bounce = NULL;
2372     acb->ret = 0;
2373
2374     if (!acb->bh)
2375         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2376
2377     bdrv_flush(bs);
2378     qemu_bh_schedule(acb->bh);
2379     return &acb->common;
2380 }
2381
2382 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2383         BlockDriverCompletionFunc *cb, void *opaque)
2384 {
2385     BlockDriverAIOCBSync *acb;
2386
2387     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2388     acb->is_write = 1; /* don't bounce in the completion handler */
2389     acb->qiov = NULL;
2390     acb->bounce = NULL;
2391     acb->ret = 0;
2392
2393     if (!acb->bh) {
2394         acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2395     }
2396
2397     qemu_bh_schedule(acb->bh);
2398     return &acb->common;
2399 }
2400
2401 /**************************************************************/
2402 /* sync block device emulation */
2403
2404 static void bdrv_rw_em_cb(void *opaque, int ret)
2405 {
2406     *(int *)opaque = ret;
2407 }
2408
2409 #define NOT_DONE 0x7fffffff
2410
2411 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2412                         uint8_t *buf, int nb_sectors)
2413 {
2414     int async_ret;
2415     BlockDriverAIOCB *acb;
2416     struct iovec iov;
2417     QEMUIOVector qiov;
2418
2419     async_context_push();
2420
2421     async_ret = NOT_DONE;
2422     iov.iov_base = (void *)buf;
2423     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2424     qemu_iovec_init_external(&qiov, &iov, 1);
2425     acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2426         bdrv_rw_em_cb, &async_ret);
2427     if (acb == NULL) {
2428         async_ret = -1;
2429         goto fail;
2430     }
2431
2432     while (async_ret == NOT_DONE) {
2433         qemu_aio_wait();
2434     }
2435
2436
2437 fail:
2438     async_context_pop();
2439     return async_ret;
2440 }
2441
2442 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2443                          const uint8_t *buf, int nb_sectors)
2444 {
2445     int async_ret;
2446     BlockDriverAIOCB *acb;
2447     struct iovec iov;
2448     QEMUIOVector qiov;
2449
2450     async_context_push();
2451
2452     async_ret = NOT_DONE;
2453     iov.iov_base = (void *)buf;
2454     iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2455     qemu_iovec_init_external(&qiov, &iov, 1);
2456     acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2457         bdrv_rw_em_cb, &async_ret);
2458     if (acb == NULL) {
2459         async_ret = -1;
2460         goto fail;
2461     }
2462     while (async_ret == NOT_DONE) {
2463         qemu_aio_wait();
2464     }
2465
2466 fail:
2467     async_context_pop();
2468     return async_ret;
2469 }
2470
2471 void bdrv_init(void)
2472 {
2473     module_call_init(MODULE_INIT_BLOCK);
2474 }
2475
2476 void bdrv_init_with_whitelist(void)
2477 {
2478     use_bdrv_whitelist = 1;
2479     bdrv_init();
2480 }
2481
2482 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2483                    BlockDriverCompletionFunc *cb, void *opaque)
2484 {
2485     BlockDriverAIOCB *acb;
2486
2487     if (pool->free_aiocb) {
2488         acb = pool->free_aiocb;
2489         pool->free_aiocb = acb->next;
2490     } else {
2491         acb = qemu_mallocz(pool->aiocb_size);
2492         acb->pool = pool;
2493     }
2494     acb->bs = bs;
2495     acb->cb = cb;
2496     acb->opaque = opaque;
2497     return acb;
2498 }
2499
2500 void qemu_aio_release(void *p)
2501 {
2502     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2503     AIOPool *pool = acb->pool;
2504     acb->next = pool->free_aiocb;
2505     pool->free_aiocb = acb;
2506 }
2507
2508 /**************************************************************/
2509 /* removable device support */
2510
2511 /**
2512  * Return TRUE if the media is present
2513  */
2514 int bdrv_is_inserted(BlockDriverState *bs)
2515 {
2516     BlockDriver *drv = bs->drv;
2517     int ret;
2518     if (!drv)
2519         return 0;
2520     if (!drv->bdrv_is_inserted)
2521         return !bs->tray_open;
2522     ret = drv->bdrv_is_inserted(bs);
2523     return ret;
2524 }
2525
2526 /**
2527  * Return TRUE if the media changed since the last call to this
2528  * function. It is currently only used for floppy disks
2529  */
2530 int bdrv_media_changed(BlockDriverState *bs)
2531 {
2532     BlockDriver *drv = bs->drv;
2533     int ret;
2534
2535     if (!drv || !drv->bdrv_media_changed)
2536         ret = -ENOTSUP;
2537     else
2538         ret = drv->bdrv_media_changed(bs);
2539     if (ret == -ENOTSUP)
2540         ret = bs->media_changed;
2541     bs->media_changed = 0;
2542     return ret;
2543 }
2544
2545 /**
2546  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2547  */
2548 int bdrv_eject(BlockDriverState *bs, int eject_flag)
2549 {
2550     BlockDriver *drv = bs->drv;
2551     int ret;
2552
2553     if (bs->locked) {
2554         return -EBUSY;
2555     }
2556
2557     if (!drv || !drv->bdrv_eject) {
2558         ret = -ENOTSUP;
2559     } else {
2560         ret = drv->bdrv_eject(bs, eject_flag);
2561     }
2562     if (ret == -ENOTSUP) {
2563         ret = 0;
2564     }
2565     if (ret >= 0) {
2566         bs->tray_open = eject_flag;
2567     }
2568
2569     return ret;
2570 }
2571
2572 int bdrv_is_locked(BlockDriverState *bs)
2573 {
2574     return bs->locked;
2575 }
2576
2577 /**
2578  * Lock or unlock the media (if it is locked, the user won't be able
2579  * to eject it manually).
2580  */
2581 void bdrv_set_locked(BlockDriverState *bs, int locked)
2582 {
2583     BlockDriver *drv = bs->drv;
2584
2585     bs->locked = locked;
2586     if (drv && drv->bdrv_set_locked) {
2587         drv->bdrv_set_locked(bs, locked);
2588     }
2589 }
2590
2591 /* needed for generic scsi interface */
2592
2593 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2594 {
2595     BlockDriver *drv = bs->drv;
2596
2597     if (drv && drv->bdrv_ioctl)
2598         return drv->bdrv_ioctl(bs, req, buf);
2599     return -ENOTSUP;
2600 }
2601
2602 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2603         unsigned long int req, void *buf,
2604         BlockDriverCompletionFunc *cb, void *opaque)
2605 {
2606     BlockDriver *drv = bs->drv;
2607
2608     if (drv && drv->bdrv_aio_ioctl)
2609         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2610     return NULL;
2611 }
2612
2613
2614
2615 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2616 {
2617     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2618 }
2619
2620 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2621 {
2622     int64_t bitmap_size;
2623
2624     bs->dirty_count = 0;
2625     if (enable) {
2626         if (!bs->dirty_bitmap) {
2627             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2628                     BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2629             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2630
2631             bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2632         }
2633     } else {
2634         if (bs->dirty_bitmap) {
2635             qemu_free(bs->dirty_bitmap);
2636             bs->dirty_bitmap = NULL;
2637         }
2638     }
2639 }
2640
2641 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2642 {
2643     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2644
2645     if (bs->dirty_bitmap &&
2646         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2647         return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2648             (1 << (chunk % (sizeof(unsigned long) * 8)));
2649     } else {
2650         return 0;
2651     }
2652 }
2653
2654 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2655                       int nr_sectors)
2656 {
2657     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2658 }
2659
2660 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2661 {
2662     return bs->dirty_count;
2663 }
This page took 0.167489 seconds and 4 git commands to generate.