]> git.ipfire.org Git - thirdparty/qemu.git/blob - block.c
block: Add options QDict to bdrv_open() prototype
[thirdparty/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/monitor.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "qemu/module.h"
31 #include "qapi/qmp/qjson.h"
32 #include "sysemu/sysemu.h"
33 #include "qemu/notify.h"
34 #include "block/coroutine.h"
35 #include "qmp-commands.h"
36 #include "qemu/timer.h"
37
38 #ifdef CONFIG_BSD
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <sys/ioctl.h>
42 #include <sys/queue.h>
43 #ifndef __DragonFly__
44 #include <sys/disk.h>
45 #endif
46 #endif
47
48 #ifdef _WIN32
49 #include <windows.h>
50 #endif
51
52 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
53
54 typedef enum {
55 BDRV_REQ_COPY_ON_READ = 0x1,
56 BDRV_REQ_ZERO_WRITE = 0x2,
57 } BdrvRequestFlags;
58
59 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
60 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
62 BlockDriverCompletionFunc *cb, void *opaque);
63 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
65 BlockDriverCompletionFunc *cb, void *opaque);
66 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67 int64_t sector_num, int nb_sectors,
68 QEMUIOVector *iov);
69 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70 int64_t sector_num, int nb_sectors,
71 QEMUIOVector *iov);
72 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
73 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74 BdrvRequestFlags flags);
75 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
76 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77 BdrvRequestFlags flags);
78 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79 int64_t sector_num,
80 QEMUIOVector *qiov,
81 int nb_sectors,
82 BlockDriverCompletionFunc *cb,
83 void *opaque,
84 bool is_write);
85 static void coroutine_fn bdrv_co_do_rw(void *opaque);
86 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87 int64_t sector_num, int nb_sectors);
88
89 static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
90 bool is_write, double elapsed_time, uint64_t *wait);
91 static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
92 double elapsed_time, uint64_t *wait);
93 static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
94 bool is_write, int64_t *wait);
95
96 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
97 QTAILQ_HEAD_INITIALIZER(bdrv_states);
98
99 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
100 QLIST_HEAD_INITIALIZER(bdrv_drivers);
101
102 /* The device to use for VM snapshots */
103 static BlockDriverState *bs_snapshots;
104
105 /* If non-zero, use only whitelisted block drivers */
106 static int use_bdrv_whitelist;
107
108 #ifdef _WIN32
109 static int is_windows_drive_prefix(const char *filename)
110 {
111 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
112 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
113 filename[1] == ':');
114 }
115
116 int is_windows_drive(const char *filename)
117 {
118 if (is_windows_drive_prefix(filename) &&
119 filename[2] == '\0')
120 return 1;
121 if (strstart(filename, "\\\\.\\", NULL) ||
122 strstart(filename, "//./", NULL))
123 return 1;
124 return 0;
125 }
126 #endif
127
128 /* throttling disk I/O limits */
129 void bdrv_io_limits_disable(BlockDriverState *bs)
130 {
131 bs->io_limits_enabled = false;
132
133 while (qemu_co_queue_next(&bs->throttled_reqs));
134
135 if (bs->block_timer) {
136 qemu_del_timer(bs->block_timer);
137 qemu_free_timer(bs->block_timer);
138 bs->block_timer = NULL;
139 }
140
141 bs->slice_start = 0;
142 bs->slice_end = 0;
143 bs->slice_time = 0;
144 memset(&bs->io_base, 0, sizeof(bs->io_base));
145 }
146
147 static void bdrv_block_timer(void *opaque)
148 {
149 BlockDriverState *bs = opaque;
150
151 qemu_co_queue_next(&bs->throttled_reqs);
152 }
153
154 void bdrv_io_limits_enable(BlockDriverState *bs)
155 {
156 qemu_co_queue_init(&bs->throttled_reqs);
157 bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
158 bs->io_limits_enabled = true;
159 }
160
161 bool bdrv_io_limits_enabled(BlockDriverState *bs)
162 {
163 BlockIOLimit *io_limits = &bs->io_limits;
164 return io_limits->bps[BLOCK_IO_LIMIT_READ]
165 || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
166 || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
167 || io_limits->iops[BLOCK_IO_LIMIT_READ]
168 || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
169 || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
170 }
171
172 static void bdrv_io_limits_intercept(BlockDriverState *bs,
173 bool is_write, int nb_sectors)
174 {
175 int64_t wait_time = -1;
176
177 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
178 qemu_co_queue_wait(&bs->throttled_reqs);
179 }
180
181 /* In fact, we hope to keep each request's timing, in FIFO mode. The next
182 * throttled requests will not be dequeued until the current request is
183 * allowed to be serviced. So if the current request still exceeds the
184 * limits, it will be inserted to the head. All requests followed it will
185 * be still in throttled_reqs queue.
186 */
187
188 while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
189 qemu_mod_timer(bs->block_timer,
190 wait_time + qemu_get_clock_ns(vm_clock));
191 qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
192 }
193
194 qemu_co_queue_next(&bs->throttled_reqs);
195 }
196
197 /* check if the path starts with "<protocol>:" */
198 static int path_has_protocol(const char *path)
199 {
200 const char *p;
201
202 #ifdef _WIN32
203 if (is_windows_drive(path) ||
204 is_windows_drive_prefix(path)) {
205 return 0;
206 }
207 p = path + strcspn(path, ":/\\");
208 #else
209 p = path + strcspn(path, ":/");
210 #endif
211
212 return *p == ':';
213 }
214
215 int path_is_absolute(const char *path)
216 {
217 #ifdef _WIN32
218 /* specific case for names like: "\\.\d:" */
219 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
220 return 1;
221 }
222 return (*path == '/' || *path == '\\');
223 #else
224 return (*path == '/');
225 #endif
226 }
227
228 /* if filename is absolute, just copy it to dest. Otherwise, build a
229 path to it by considering it is relative to base_path. URL are
230 supported. */
231 void path_combine(char *dest, int dest_size,
232 const char *base_path,
233 const char *filename)
234 {
235 const char *p, *p1;
236 int len;
237
238 if (dest_size <= 0)
239 return;
240 if (path_is_absolute(filename)) {
241 pstrcpy(dest, dest_size, filename);
242 } else {
243 p = strchr(base_path, ':');
244 if (p)
245 p++;
246 else
247 p = base_path;
248 p1 = strrchr(base_path, '/');
249 #ifdef _WIN32
250 {
251 const char *p2;
252 p2 = strrchr(base_path, '\\');
253 if (!p1 || p2 > p1)
254 p1 = p2;
255 }
256 #endif
257 if (p1)
258 p1++;
259 else
260 p1 = base_path;
261 if (p1 > p)
262 p = p1;
263 len = p - base_path;
264 if (len > dest_size - 1)
265 len = dest_size - 1;
266 memcpy(dest, base_path, len);
267 dest[len] = '\0';
268 pstrcat(dest, dest_size, filename);
269 }
270 }
271
272 void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
273 {
274 if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
275 pstrcpy(dest, sz, bs->backing_file);
276 } else {
277 path_combine(dest, sz, bs->filename, bs->backing_file);
278 }
279 }
280
281 void bdrv_register(BlockDriver *bdrv)
282 {
283 /* Block drivers without coroutine functions need emulation */
284 if (!bdrv->bdrv_co_readv) {
285 bdrv->bdrv_co_readv = bdrv_co_readv_em;
286 bdrv->bdrv_co_writev = bdrv_co_writev_em;
287
288 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
289 * the block driver lacks aio we need to emulate that too.
290 */
291 if (!bdrv->bdrv_aio_readv) {
292 /* add AIO emulation layer */
293 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
294 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
295 }
296 }
297
298 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
299 }
300
301 /* create a new block device (by default it is empty) */
302 BlockDriverState *bdrv_new(const char *device_name)
303 {
304 BlockDriverState *bs;
305
306 bs = g_malloc0(sizeof(BlockDriverState));
307 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
308 if (device_name[0] != '\0') {
309 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
310 }
311 bdrv_iostatus_disable(bs);
312 notifier_list_init(&bs->close_notifiers);
313
314 return bs;
315 }
316
317 void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
318 {
319 notifier_list_add(&bs->close_notifiers, notify);
320 }
321
322 BlockDriver *bdrv_find_format(const char *format_name)
323 {
324 BlockDriver *drv1;
325 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
326 if (!strcmp(drv1->format_name, format_name)) {
327 return drv1;
328 }
329 }
330 return NULL;
331 }
332
333 static int bdrv_is_whitelisted(BlockDriver *drv)
334 {
335 static const char *whitelist[] = {
336 CONFIG_BDRV_WHITELIST
337 };
338 const char **p;
339
340 if (!whitelist[0])
341 return 1; /* no whitelist, anything goes */
342
343 for (p = whitelist; *p; p++) {
344 if (!strcmp(drv->format_name, *p)) {
345 return 1;
346 }
347 }
348 return 0;
349 }
350
351 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
352 {
353 BlockDriver *drv = bdrv_find_format(format_name);
354 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
355 }
356
357 typedef struct CreateCo {
358 BlockDriver *drv;
359 char *filename;
360 QEMUOptionParameter *options;
361 int ret;
362 } CreateCo;
363
364 static void coroutine_fn bdrv_create_co_entry(void *opaque)
365 {
366 CreateCo *cco = opaque;
367 assert(cco->drv);
368
369 cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
370 }
371
372 int bdrv_create(BlockDriver *drv, const char* filename,
373 QEMUOptionParameter *options)
374 {
375 int ret;
376
377 Coroutine *co;
378 CreateCo cco = {
379 .drv = drv,
380 .filename = g_strdup(filename),
381 .options = options,
382 .ret = NOT_DONE,
383 };
384
385 if (!drv->bdrv_create) {
386 ret = -ENOTSUP;
387 goto out;
388 }
389
390 if (qemu_in_coroutine()) {
391 /* Fast-path if already in coroutine context */
392 bdrv_create_co_entry(&cco);
393 } else {
394 co = qemu_coroutine_create(bdrv_create_co_entry);
395 qemu_coroutine_enter(co, &cco);
396 while (cco.ret == NOT_DONE) {
397 qemu_aio_wait();
398 }
399 }
400
401 ret = cco.ret;
402
403 out:
404 g_free(cco.filename);
405 return ret;
406 }
407
408 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
409 {
410 BlockDriver *drv;
411
412 drv = bdrv_find_protocol(filename);
413 if (drv == NULL) {
414 return -ENOENT;
415 }
416
417 return bdrv_create(drv, filename, options);
418 }
419
420 /*
421 * Create a uniquely-named empty temporary file.
422 * Return 0 upon success, otherwise a negative errno value.
423 */
424 int get_tmp_filename(char *filename, int size)
425 {
426 #ifdef _WIN32
427 char temp_dir[MAX_PATH];
428 /* GetTempFileName requires that its output buffer (4th param)
429 have length MAX_PATH or greater. */
430 assert(size >= MAX_PATH);
431 return (GetTempPath(MAX_PATH, temp_dir)
432 && GetTempFileName(temp_dir, "qem", 0, filename)
433 ? 0 : -GetLastError());
434 #else
435 int fd;
436 const char *tmpdir;
437 tmpdir = getenv("TMPDIR");
438 if (!tmpdir)
439 tmpdir = "/tmp";
440 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
441 return -EOVERFLOW;
442 }
443 fd = mkstemp(filename);
444 if (fd < 0) {
445 return -errno;
446 }
447 if (close(fd) != 0) {
448 unlink(filename);
449 return -errno;
450 }
451 return 0;
452 #endif
453 }
454
455 /*
456 * Detect host devices. By convention, /dev/cdrom[N] is always
457 * recognized as a host CDROM.
458 */
459 static BlockDriver *find_hdev_driver(const char *filename)
460 {
461 int score_max = 0, score;
462 BlockDriver *drv = NULL, *d;
463
464 QLIST_FOREACH(d, &bdrv_drivers, list) {
465 if (d->bdrv_probe_device) {
466 score = d->bdrv_probe_device(filename);
467 if (score > score_max) {
468 score_max = score;
469 drv = d;
470 }
471 }
472 }
473
474 return drv;
475 }
476
477 BlockDriver *bdrv_find_protocol(const char *filename)
478 {
479 BlockDriver *drv1;
480 char protocol[128];
481 int len;
482 const char *p;
483
484 /* TODO Drivers without bdrv_file_open must be specified explicitly */
485
486 /*
487 * XXX(hch): we really should not let host device detection
488 * override an explicit protocol specification, but moving this
489 * later breaks access to device names with colons in them.
490 * Thanks to the brain-dead persistent naming schemes on udev-
491 * based Linux systems those actually are quite common.
492 */
493 drv1 = find_hdev_driver(filename);
494 if (drv1) {
495 return drv1;
496 }
497
498 if (!path_has_protocol(filename)) {
499 return bdrv_find_format("file");
500 }
501 p = strchr(filename, ':');
502 assert(p != NULL);
503 len = p - filename;
504 if (len > sizeof(protocol) - 1)
505 len = sizeof(protocol) - 1;
506 memcpy(protocol, filename, len);
507 protocol[len] = '\0';
508 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
509 if (drv1->protocol_name &&
510 !strcmp(drv1->protocol_name, protocol)) {
511 return drv1;
512 }
513 }
514 return NULL;
515 }
516
517 static int find_image_format(BlockDriverState *bs, const char *filename,
518 BlockDriver **pdrv)
519 {
520 int score, score_max;
521 BlockDriver *drv1, *drv;
522 uint8_t buf[2048];
523 int ret = 0;
524
525 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
526 if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
527 drv = bdrv_find_format("raw");
528 if (!drv) {
529 ret = -ENOENT;
530 }
531 *pdrv = drv;
532 return ret;
533 }
534
535 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
536 if (ret < 0) {
537 *pdrv = NULL;
538 return ret;
539 }
540
541 score_max = 0;
542 drv = NULL;
543 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
544 if (drv1->bdrv_probe) {
545 score = drv1->bdrv_probe(buf, ret, filename);
546 if (score > score_max) {
547 score_max = score;
548 drv = drv1;
549 }
550 }
551 }
552 if (!drv) {
553 ret = -ENOENT;
554 }
555 *pdrv = drv;
556 return ret;
557 }
558
559 /**
560 * Set the current 'total_sectors' value
561 */
562 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
563 {
564 BlockDriver *drv = bs->drv;
565
566 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
567 if (bs->sg)
568 return 0;
569
570 /* query actual device if possible, otherwise just trust the hint */
571 if (drv->bdrv_getlength) {
572 int64_t length = drv->bdrv_getlength(bs);
573 if (length < 0) {
574 return length;
575 }
576 hint = length >> BDRV_SECTOR_BITS;
577 }
578
579 bs->total_sectors = hint;
580 return 0;
581 }
582
583 /**
584 * Set open flags for a given discard mode
585 *
586 * Return 0 on success, -1 if the discard mode was invalid.
587 */
588 int bdrv_parse_discard_flags(const char *mode, int *flags)
589 {
590 *flags &= ~BDRV_O_UNMAP;
591
592 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
593 /* do nothing */
594 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
595 *flags |= BDRV_O_UNMAP;
596 } else {
597 return -1;
598 }
599
600 return 0;
601 }
602
603 /**
604 * Set open flags for a given cache mode
605 *
606 * Return 0 on success, -1 if the cache mode was invalid.
607 */
608 int bdrv_parse_cache_flags(const char *mode, int *flags)
609 {
610 *flags &= ~BDRV_O_CACHE_MASK;
611
612 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
613 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
614 } else if (!strcmp(mode, "directsync")) {
615 *flags |= BDRV_O_NOCACHE;
616 } else if (!strcmp(mode, "writeback")) {
617 *flags |= BDRV_O_CACHE_WB;
618 } else if (!strcmp(mode, "unsafe")) {
619 *flags |= BDRV_O_CACHE_WB;
620 *flags |= BDRV_O_NO_FLUSH;
621 } else if (!strcmp(mode, "writethrough")) {
622 /* this is the default */
623 } else {
624 return -1;
625 }
626
627 return 0;
628 }
629
630 /**
631 * The copy-on-read flag is actually a reference count so multiple users may
632 * use the feature without worrying about clobbering its previous state.
633 * Copy-on-read stays enabled until all users have called to disable it.
634 */
635 void bdrv_enable_copy_on_read(BlockDriverState *bs)
636 {
637 bs->copy_on_read++;
638 }
639
640 void bdrv_disable_copy_on_read(BlockDriverState *bs)
641 {
642 assert(bs->copy_on_read > 0);
643 bs->copy_on_read--;
644 }
645
646 static int bdrv_open_flags(BlockDriverState *bs, int flags)
647 {
648 int open_flags = flags | BDRV_O_CACHE_WB;
649
650 /*
651 * Clear flags that are internal to the block layer before opening the
652 * image.
653 */
654 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
655
656 /*
657 * Snapshots should be writable.
658 */
659 if (bs->is_temporary) {
660 open_flags |= BDRV_O_RDWR;
661 }
662
663 return open_flags;
664 }
665
666 /*
667 * Common part for opening disk images and files
668 */
669 static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
670 const char *filename,
671 int flags, BlockDriver *drv)
672 {
673 int ret, open_flags;
674
675 assert(drv != NULL);
676 assert(bs->file == NULL);
677
678 trace_bdrv_open_common(bs, filename, flags, drv->format_name);
679
680 bs->open_flags = flags;
681 bs->buffer_alignment = 512;
682
683 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
684 if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
685 bdrv_enable_copy_on_read(bs);
686 }
687
688 pstrcpy(bs->filename, sizeof(bs->filename), filename);
689
690 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
691 return -ENOTSUP;
692 }
693
694 bs->drv = drv;
695 bs->opaque = g_malloc0(drv->instance_size);
696
697 bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
698 open_flags = bdrv_open_flags(bs, flags);
699
700 bs->read_only = !(open_flags & BDRV_O_RDWR);
701
702 /* Open the image, either directly or using a protocol */
703 if (drv->bdrv_file_open) {
704 if (file != NULL) {
705 bdrv_swap(file, bs);
706 ret = 0;
707 } else {
708 ret = drv->bdrv_file_open(bs, filename, open_flags);
709 }
710 } else {
711 assert(file != NULL);
712 bs->file = file;
713 ret = drv->bdrv_open(bs, NULL, open_flags);
714 }
715
716 if (ret < 0) {
717 goto free_and_fail;
718 }
719
720 ret = refresh_total_sectors(bs, bs->total_sectors);
721 if (ret < 0) {
722 goto free_and_fail;
723 }
724
725 #ifndef _WIN32
726 if (bs->is_temporary) {
727 unlink(filename);
728 }
729 #endif
730 return 0;
731
732 free_and_fail:
733 bs->file = NULL;
734 g_free(bs->opaque);
735 bs->opaque = NULL;
736 bs->drv = NULL;
737 return ret;
738 }
739
740 /*
741 * Opens a file using a protocol (file, host_device, nbd, ...)
742 */
743 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
744 {
745 BlockDriverState *bs;
746 BlockDriver *drv;
747 int ret;
748
749 drv = bdrv_find_protocol(filename);
750 if (!drv) {
751 return -ENOENT;
752 }
753
754 bs = bdrv_new("");
755 ret = bdrv_open_common(bs, NULL, filename, flags, drv);
756 if (ret < 0) {
757 bdrv_delete(bs);
758 return ret;
759 }
760 bs->growable = 1;
761 *pbs = bs;
762 return 0;
763 }
764
765 int bdrv_open_backing_file(BlockDriverState *bs)
766 {
767 char backing_filename[PATH_MAX];
768 int back_flags, ret;
769 BlockDriver *back_drv = NULL;
770
771 if (bs->backing_hd != NULL) {
772 return 0;
773 }
774
775 bs->open_flags &= ~BDRV_O_NO_BACKING;
776 if (bs->backing_file[0] == '\0') {
777 return 0;
778 }
779
780 bs->backing_hd = bdrv_new("");
781 bdrv_get_full_backing_filename(bs, backing_filename,
782 sizeof(backing_filename));
783
784 if (bs->backing_format[0] != '\0') {
785 back_drv = bdrv_find_format(bs->backing_format);
786 }
787
788 /* backing files always opened read-only */
789 back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
790
791 ret = bdrv_open(bs->backing_hd, backing_filename, NULL,
792 back_flags, back_drv);
793 if (ret < 0) {
794 bdrv_delete(bs->backing_hd);
795 bs->backing_hd = NULL;
796 bs->open_flags |= BDRV_O_NO_BACKING;
797 return ret;
798 }
799 return 0;
800 }
801
802 /*
803 * Opens a disk image (raw, qcow2, vmdk, ...)
804 *
805 * options is a QDict of options to pass to the block drivers, or NULL for an
806 * empty set of options. The reference to the QDict belongs to the block layer
807 * after the call (even on failure), so if the caller intends to reuse the
808 * dictionary, it needs to use QINCREF() before calling bdrv_open.
809 */
810 int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
811 int flags, BlockDriver *drv)
812 {
813 int ret;
814 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
815 char tmp_filename[PATH_MAX + 1];
816 BlockDriverState *file = NULL;
817
818 /* NULL means an empty set of options */
819 if (options == NULL) {
820 options = qdict_new();
821 }
822
823 bs->options = options;
824
825 /* For snapshot=on, create a temporary qcow2 overlay */
826 if (flags & BDRV_O_SNAPSHOT) {
827 BlockDriverState *bs1;
828 int64_t total_size;
829 int is_protocol = 0;
830 BlockDriver *bdrv_qcow2;
831 QEMUOptionParameter *options;
832 char backing_filename[PATH_MAX];
833
834 /* if snapshot, we create a temporary backing file and open it
835 instead of opening 'filename' directly */
836
837 /* if there is a backing file, use it */
838 bs1 = bdrv_new("");
839 ret = bdrv_open(bs1, filename, NULL, 0, drv);
840 if (ret < 0) {
841 bdrv_delete(bs1);
842 goto fail;
843 }
844 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
845
846 if (bs1->drv && bs1->drv->protocol_name)
847 is_protocol = 1;
848
849 bdrv_delete(bs1);
850
851 ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
852 if (ret < 0) {
853 goto fail;
854 }
855
856 /* Real path is meaningless for protocols */
857 if (is_protocol) {
858 snprintf(backing_filename, sizeof(backing_filename),
859 "%s", filename);
860 } else if (!realpath(filename, backing_filename)) {
861 ret = -errno;
862 goto fail;
863 }
864
865 bdrv_qcow2 = bdrv_find_format("qcow2");
866 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
867
868 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
869 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
870 if (drv) {
871 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
872 drv->format_name);
873 }
874
875 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
876 free_option_parameters(options);
877 if (ret < 0) {
878 goto fail;
879 }
880
881 filename = tmp_filename;
882 drv = bdrv_qcow2;
883 bs->is_temporary = 1;
884 }
885
886 /* Open image file without format layer */
887 if (flags & BDRV_O_RDWR) {
888 flags |= BDRV_O_ALLOW_RDWR;
889 }
890
891 ret = bdrv_file_open(&file, filename, bdrv_open_flags(bs, flags));
892 if (ret < 0) {
893 goto fail;
894 }
895
896 /* Find the right image format driver */
897 if (!drv) {
898 ret = find_image_format(file, filename, &drv);
899 }
900
901 if (!drv) {
902 goto unlink_and_fail;
903 }
904
905 /* Open the image */
906 ret = bdrv_open_common(bs, file, filename, flags, drv);
907 if (ret < 0) {
908 goto unlink_and_fail;
909 }
910
911 if (bs->file != file) {
912 bdrv_delete(file);
913 file = NULL;
914 }
915
916 /* If there is a backing file, use it */
917 if ((flags & BDRV_O_NO_BACKING) == 0) {
918 ret = bdrv_open_backing_file(bs);
919 if (ret < 0) {
920 bdrv_close(bs);
921 return ret;
922 }
923 }
924
925 if (!bdrv_key_required(bs)) {
926 bdrv_dev_change_media_cb(bs, true);
927 }
928
929 /* throttling disk I/O limits */
930 if (bs->io_limits_enabled) {
931 bdrv_io_limits_enable(bs);
932 }
933
934 return 0;
935
936 unlink_and_fail:
937 if (file != NULL) {
938 bdrv_delete(file);
939 }
940 if (bs->is_temporary) {
941 unlink(filename);
942 }
943 fail:
944 QDECREF(bs->options);
945 bs->options = NULL;
946
947 return ret;
948 }
949
950 typedef struct BlockReopenQueueEntry {
951 bool prepared;
952 BDRVReopenState state;
953 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
954 } BlockReopenQueueEntry;
955
956 /*
957 * Adds a BlockDriverState to a simple queue for an atomic, transactional
958 * reopen of multiple devices.
959 *
960 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
961 * already performed, or alternatively may be NULL a new BlockReopenQueue will
962 * be created and initialized. This newly created BlockReopenQueue should be
963 * passed back in for subsequent calls that are intended to be of the same
964 * atomic 'set'.
965 *
966 * bs is the BlockDriverState to add to the reopen queue.
967 *
968 * flags contains the open flags for the associated bs
969 *
970 * returns a pointer to bs_queue, which is either the newly allocated
971 * bs_queue, or the existing bs_queue being used.
972 *
973 */
974 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
975 BlockDriverState *bs, int flags)
976 {
977 assert(bs != NULL);
978
979 BlockReopenQueueEntry *bs_entry;
980 if (bs_queue == NULL) {
981 bs_queue = g_new0(BlockReopenQueue, 1);
982 QSIMPLEQ_INIT(bs_queue);
983 }
984
985 if (bs->file) {
986 bdrv_reopen_queue(bs_queue, bs->file, flags);
987 }
988
989 bs_entry = g_new0(BlockReopenQueueEntry, 1);
990 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
991
992 bs_entry->state.bs = bs;
993 bs_entry->state.flags = flags;
994
995 return bs_queue;
996 }
997
998 /*
999 * Reopen multiple BlockDriverStates atomically & transactionally.
1000 *
1001 * The queue passed in (bs_queue) must have been built up previous
1002 * via bdrv_reopen_queue().
1003 *
1004 * Reopens all BDS specified in the queue, with the appropriate
1005 * flags. All devices are prepared for reopen, and failure of any
1006 * device will cause all device changes to be abandonded, and intermediate
1007 * data cleaned up.
1008 *
1009 * If all devices prepare successfully, then the changes are committed
1010 * to all devices.
1011 *
1012 */
1013 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1014 {
1015 int ret = -1;
1016 BlockReopenQueueEntry *bs_entry, *next;
1017 Error *local_err = NULL;
1018
1019 assert(bs_queue != NULL);
1020
1021 bdrv_drain_all();
1022
1023 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1024 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1025 error_propagate(errp, local_err);
1026 goto cleanup;
1027 }
1028 bs_entry->prepared = true;
1029 }
1030
1031 /* If we reach this point, we have success and just need to apply the
1032 * changes
1033 */
1034 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1035 bdrv_reopen_commit(&bs_entry->state);
1036 }
1037
1038 ret = 0;
1039
1040 cleanup:
1041 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1042 if (ret && bs_entry->prepared) {
1043 bdrv_reopen_abort(&bs_entry->state);
1044 }
1045 g_free(bs_entry);
1046 }
1047 g_free(bs_queue);
1048 return ret;
1049 }
1050
1051
1052 /* Reopen a single BlockDriverState with the specified flags. */
1053 int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1054 {
1055 int ret = -1;
1056 Error *local_err = NULL;
1057 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1058
1059 ret = bdrv_reopen_multiple(queue, &local_err);
1060 if (local_err != NULL) {
1061 error_propagate(errp, local_err);
1062 }
1063 return ret;
1064 }
1065
1066
1067 /*
1068 * Prepares a BlockDriverState for reopen. All changes are staged in the
1069 * 'opaque' field of the BDRVReopenState, which is used and allocated by
1070 * the block driver layer .bdrv_reopen_prepare()
1071 *
1072 * bs is the BlockDriverState to reopen
1073 * flags are the new open flags
1074 * queue is the reopen queue
1075 *
1076 * Returns 0 on success, non-zero on error. On error errp will be set
1077 * as well.
1078 *
1079 * On failure, bdrv_reopen_abort() will be called to clean up any data.
1080 * It is the responsibility of the caller to then call the abort() or
1081 * commit() for any other BDS that have been left in a prepare() state
1082 *
1083 */
1084 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1085 Error **errp)
1086 {
1087 int ret = -1;
1088 Error *local_err = NULL;
1089 BlockDriver *drv;
1090
1091 assert(reopen_state != NULL);
1092 assert(reopen_state->bs->drv != NULL);
1093 drv = reopen_state->bs->drv;
1094
1095 /* if we are to stay read-only, do not allow permission change
1096 * to r/w */
1097 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1098 reopen_state->flags & BDRV_O_RDWR) {
1099 error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1100 reopen_state->bs->device_name);
1101 goto error;
1102 }
1103
1104
1105 ret = bdrv_flush(reopen_state->bs);
1106 if (ret) {
1107 error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1108 strerror(-ret));
1109 goto error;
1110 }
1111
1112 if (drv->bdrv_reopen_prepare) {
1113 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1114 if (ret) {
1115 if (local_err != NULL) {
1116 error_propagate(errp, local_err);
1117 } else {
1118 error_set(errp, QERR_OPEN_FILE_FAILED,
1119 reopen_state->bs->filename);
1120 }
1121 goto error;
1122 }
1123 } else {
1124 /* It is currently mandatory to have a bdrv_reopen_prepare()
1125 * handler for each supported drv. */
1126 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1127 drv->format_name, reopen_state->bs->device_name,
1128 "reopening of file");
1129 ret = -1;
1130 goto error;
1131 }
1132
1133 ret = 0;
1134
1135 error:
1136 return ret;
1137 }
1138
1139 /*
1140 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1141 * makes them final by swapping the staging BlockDriverState contents into
1142 * the active BlockDriverState contents.
1143 */
1144 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1145 {
1146 BlockDriver *drv;
1147
1148 assert(reopen_state != NULL);
1149 drv = reopen_state->bs->drv;
1150 assert(drv != NULL);
1151
1152 /* If there are any driver level actions to take */
1153 if (drv->bdrv_reopen_commit) {
1154 drv->bdrv_reopen_commit(reopen_state);
1155 }
1156
1157 /* set BDS specific flags now */
1158 reopen_state->bs->open_flags = reopen_state->flags;
1159 reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1160 BDRV_O_CACHE_WB);
1161 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1162 }
1163
1164 /*
1165 * Abort the reopen, and delete and free the staged changes in
1166 * reopen_state
1167 */
1168 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1169 {
1170 BlockDriver *drv;
1171
1172 assert(reopen_state != NULL);
1173 drv = reopen_state->bs->drv;
1174 assert(drv != NULL);
1175
1176 if (drv->bdrv_reopen_abort) {
1177 drv->bdrv_reopen_abort(reopen_state);
1178 }
1179 }
1180
1181
1182 void bdrv_close(BlockDriverState *bs)
1183 {
1184 bdrv_flush(bs);
1185 if (bs->job) {
1186 block_job_cancel_sync(bs->job);
1187 }
1188 bdrv_drain_all();
1189 notifier_list_notify(&bs->close_notifiers, bs);
1190
1191 if (bs->drv) {
1192 if (bs == bs_snapshots) {
1193 bs_snapshots = NULL;
1194 }
1195 if (bs->backing_hd) {
1196 bdrv_delete(bs->backing_hd);
1197 bs->backing_hd = NULL;
1198 }
1199 bs->drv->bdrv_close(bs);
1200 g_free(bs->opaque);
1201 #ifdef _WIN32
1202 if (bs->is_temporary) {
1203 unlink(bs->filename);
1204 }
1205 #endif
1206 bs->opaque = NULL;
1207 bs->drv = NULL;
1208 bs->copy_on_read = 0;
1209 bs->backing_file[0] = '\0';
1210 bs->backing_format[0] = '\0';
1211 bs->total_sectors = 0;
1212 bs->encrypted = 0;
1213 bs->valid_key = 0;
1214 bs->sg = 0;
1215 bs->growable = 0;
1216 QDECREF(bs->options);
1217 bs->options = NULL;
1218
1219 if (bs->file != NULL) {
1220 bdrv_delete(bs->file);
1221 bs->file = NULL;
1222 }
1223 }
1224
1225 bdrv_dev_change_media_cb(bs, false);
1226
1227 /*throttling disk I/O limits*/
1228 if (bs->io_limits_enabled) {
1229 bdrv_io_limits_disable(bs);
1230 }
1231 }
1232
1233 void bdrv_close_all(void)
1234 {
1235 BlockDriverState *bs;
1236
1237 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1238 bdrv_close(bs);
1239 }
1240 }
1241
1242 /*
1243 * Wait for pending requests to complete across all BlockDriverStates
1244 *
1245 * This function does not flush data to disk, use bdrv_flush_all() for that
1246 * after calling this function.
1247 *
1248 * Note that completion of an asynchronous I/O operation can trigger any
1249 * number of other I/O operations on other devices---for example a coroutine
1250 * can be arbitrarily complex and a constant flow of I/O can come until the
1251 * coroutine is complete. Because of this, it is not possible to have a
1252 * function to drain a single device's I/O queue.
1253 */
1254 void bdrv_drain_all(void)
1255 {
1256 BlockDriverState *bs;
1257 bool busy;
1258
1259 do {
1260 busy = qemu_aio_wait();
1261
1262 /* FIXME: We do not have timer support here, so this is effectively
1263 * a busy wait.
1264 */
1265 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1266 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
1267 qemu_co_queue_restart_all(&bs->throttled_reqs);
1268 busy = true;
1269 }
1270 }
1271 } while (busy);
1272
1273 /* If requests are still pending there is a bug somewhere */
1274 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1275 assert(QLIST_EMPTY(&bs->tracked_requests));
1276 assert(qemu_co_queue_empty(&bs->throttled_reqs));
1277 }
1278 }
1279
1280 /* make a BlockDriverState anonymous by removing from bdrv_state list.
1281 Also, NULL terminate the device_name to prevent double remove */
1282 void bdrv_make_anon(BlockDriverState *bs)
1283 {
1284 if (bs->device_name[0] != '\0') {
1285 QTAILQ_REMOVE(&bdrv_states, bs, list);
1286 }
1287 bs->device_name[0] = '\0';
1288 }
1289
1290 static void bdrv_rebind(BlockDriverState *bs)
1291 {
1292 if (bs->drv && bs->drv->bdrv_rebind) {
1293 bs->drv->bdrv_rebind(bs);
1294 }
1295 }
1296
1297 static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
1298 BlockDriverState *bs_src)
1299 {
1300 /* move some fields that need to stay attached to the device */
1301 bs_dest->open_flags = bs_src->open_flags;
1302
1303 /* dev info */
1304 bs_dest->dev_ops = bs_src->dev_ops;
1305 bs_dest->dev_opaque = bs_src->dev_opaque;
1306 bs_dest->dev = bs_src->dev;
1307 bs_dest->buffer_alignment = bs_src->buffer_alignment;
1308 bs_dest->copy_on_read = bs_src->copy_on_read;
1309
1310 bs_dest->enable_write_cache = bs_src->enable_write_cache;
1311
1312 /* i/o timing parameters */
1313 bs_dest->slice_time = bs_src->slice_time;
1314 bs_dest->slice_start = bs_src->slice_start;
1315 bs_dest->slice_end = bs_src->slice_end;
1316 bs_dest->io_limits = bs_src->io_limits;
1317 bs_dest->io_base = bs_src->io_base;
1318 bs_dest->throttled_reqs = bs_src->throttled_reqs;
1319 bs_dest->block_timer = bs_src->block_timer;
1320 bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
1321
1322 /* r/w error */
1323 bs_dest->on_read_error = bs_src->on_read_error;
1324 bs_dest->on_write_error = bs_src->on_write_error;
1325
1326 /* i/o status */
1327 bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
1328 bs_dest->iostatus = bs_src->iostatus;
1329
1330 /* dirty bitmap */
1331 bs_dest->dirty_bitmap = bs_src->dirty_bitmap;
1332
1333 /* job */
1334 bs_dest->in_use = bs_src->in_use;
1335 bs_dest->job = bs_src->job;
1336
1337 /* keep the same entry in bdrv_states */
1338 pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
1339 bs_src->device_name);
1340 bs_dest->list = bs_src->list;
1341 }
1342
1343 /*
1344 * Swap bs contents for two image chains while they are live,
1345 * while keeping required fields on the BlockDriverState that is
1346 * actually attached to a device.
1347 *
1348 * This will modify the BlockDriverState fields, and swap contents
1349 * between bs_new and bs_old. Both bs_new and bs_old are modified.
1350 *
1351 * bs_new is required to be anonymous.
1352 *
1353 * This function does not create any image files.
1354 */
1355 void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
1356 {
1357 BlockDriverState tmp;
1358
1359 /* bs_new must be anonymous and shouldn't have anything fancy enabled */
1360 assert(bs_new->device_name[0] == '\0');
1361 assert(bs_new->dirty_bitmap == NULL);
1362 assert(bs_new->job == NULL);
1363 assert(bs_new->dev == NULL);
1364 assert(bs_new->in_use == 0);
1365 assert(bs_new->io_limits_enabled == false);
1366 assert(bs_new->block_timer == NULL);
1367
1368 tmp = *bs_new;
1369 *bs_new = *bs_old;
1370 *bs_old = tmp;
1371
1372 /* there are some fields that should not be swapped, move them back */
1373 bdrv_move_feature_fields(&tmp, bs_old);
1374 bdrv_move_feature_fields(bs_old, bs_new);
1375 bdrv_move_feature_fields(bs_new, &tmp);
1376
1377 /* bs_new shouldn't be in bdrv_states even after the swap! */
1378 assert(bs_new->device_name[0] == '\0');
1379
1380 /* Check a few fields that should remain attached to the device */
1381 assert(bs_new->dev == NULL);
1382 assert(bs_new->job == NULL);
1383 assert(bs_new->in_use == 0);
1384 assert(bs_new->io_limits_enabled == false);
1385 assert(bs_new->block_timer == NULL);
1386
1387 bdrv_rebind(bs_new);
1388 bdrv_rebind(bs_old);
1389 }
1390
1391 /*
1392 * Add new bs contents at the top of an image chain while the chain is
1393 * live, while keeping required fields on the top layer.
1394 *
1395 * This will modify the BlockDriverState fields, and swap contents
1396 * between bs_new and bs_top. Both bs_new and bs_top are modified.
1397 *
1398 * bs_new is required to be anonymous.
1399 *
1400 * This function does not create any image files.
1401 */
1402 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
1403 {
1404 bdrv_swap(bs_new, bs_top);
1405
1406 /* The contents of 'tmp' will become bs_top, as we are
1407 * swapping bs_new and bs_top contents. */
1408 bs_top->backing_hd = bs_new;
1409 bs_top->open_flags &= ~BDRV_O_NO_BACKING;
1410 pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
1411 bs_new->filename);
1412 pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
1413 bs_new->drv ? bs_new->drv->format_name : "");
1414 }
1415
1416 void bdrv_delete(BlockDriverState *bs)
1417 {
1418 assert(!bs->dev);
1419 assert(!bs->job);
1420 assert(!bs->in_use);
1421
1422 /* remove from list, if necessary */
1423 bdrv_make_anon(bs);
1424
1425 bdrv_close(bs);
1426
1427 assert(bs != bs_snapshots);
1428 g_free(bs);
1429 }
1430
1431 int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1432 /* TODO change to DeviceState *dev when all users are qdevified */
1433 {
1434 if (bs->dev) {
1435 return -EBUSY;
1436 }
1437 bs->dev = dev;
1438 bdrv_iostatus_reset(bs);
1439 return 0;
1440 }
1441
1442 /* TODO qdevified devices don't use this, remove when devices are qdevified */
1443 void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
1444 {
1445 if (bdrv_attach_dev(bs, dev) < 0) {
1446 abort();
1447 }
1448 }
1449
1450 void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1451 /* TODO change to DeviceState *dev when all users are qdevified */
1452 {
1453 assert(bs->dev == dev);
1454 bs->dev = NULL;
1455 bs->dev_ops = NULL;
1456 bs->dev_opaque = NULL;
1457 bs->buffer_alignment = 512;
1458 }
1459
1460 /* TODO change to return DeviceState * when all users are qdevified */
1461 void *bdrv_get_attached_dev(BlockDriverState *bs)
1462 {
1463 return bs->dev;
1464 }
1465
1466 void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
1467 void *opaque)
1468 {
1469 bs->dev_ops = ops;
1470 bs->dev_opaque = opaque;
1471 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
1472 bs_snapshots = NULL;
1473 }
1474 }
1475
1476 void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1477 enum MonitorEvent ev,
1478 BlockErrorAction action, bool is_read)
1479 {
1480 QObject *data;
1481 const char *action_str;
1482
1483 switch (action) {
1484 case BDRV_ACTION_REPORT:
1485 action_str = "report";
1486 break;
1487 case BDRV_ACTION_IGNORE:
1488 action_str = "ignore";
1489 break;
1490 case BDRV_ACTION_STOP:
1491 action_str = "stop";
1492 break;
1493 default:
1494 abort();
1495 }
1496
1497 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1498 bdrv->device_name,
1499 action_str,
1500 is_read ? "read" : "write");
1501 monitor_protocol_event(ev, data);
1502
1503 qobject_decref(data);
1504 }
1505
1506 static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
1507 {
1508 QObject *data;
1509
1510 data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
1511 bdrv_get_device_name(bs), ejected);
1512 monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
1513
1514 qobject_decref(data);
1515 }
1516
1517 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
1518 {
1519 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
1520 bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
1521 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
1522 if (tray_was_closed) {
1523 /* tray open */
1524 bdrv_emit_qmp_eject_event(bs, true);
1525 }
1526 if (load) {
1527 /* tray close */
1528 bdrv_emit_qmp_eject_event(bs, false);
1529 }
1530 }
1531 }
1532
1533 bool bdrv_dev_has_removable_media(BlockDriverState *bs)
1534 {
1535 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
1536 }
1537
1538 void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1539 {
1540 if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1541 bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1542 }
1543 }
1544
1545 bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1546 {
1547 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1548 return bs->dev_ops->is_tray_open(bs->dev_opaque);
1549 }
1550 return false;
1551 }
1552
1553 static void bdrv_dev_resize_cb(BlockDriverState *bs)
1554 {
1555 if (bs->dev_ops && bs->dev_ops->resize_cb) {
1556 bs->dev_ops->resize_cb(bs->dev_opaque);
1557 }
1558 }
1559
1560 bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1561 {
1562 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1563 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1564 }
1565 return false;
1566 }
1567
1568 /*
1569 * Run consistency checks on an image
1570 *
1571 * Returns 0 if the check could be completed (it doesn't mean that the image is
1572 * free of errors) or -errno when an internal error occurred. The results of the
1573 * check are stored in res.
1574 */
1575 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1576 {
1577 if (bs->drv->bdrv_check == NULL) {
1578 return -ENOTSUP;
1579 }
1580
1581 memset(res, 0, sizeof(*res));
1582 return bs->drv->bdrv_check(bs, res, fix);
1583 }
1584
1585 #define COMMIT_BUF_SECTORS 2048
1586
1587 /* commit COW file into the raw image */
1588 int bdrv_commit(BlockDriverState *bs)
1589 {
1590 BlockDriver *drv = bs->drv;
1591 int64_t sector, total_sectors;
1592 int n, ro, open_flags;
1593 int ret = 0;
1594 uint8_t *buf;
1595 char filename[PATH_MAX];
1596
1597 if (!drv)
1598 return -ENOMEDIUM;
1599
1600 if (!bs->backing_hd) {
1601 return -ENOTSUP;
1602 }
1603
1604 if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
1605 return -EBUSY;
1606 }
1607
1608 ro = bs->backing_hd->read_only;
1609 /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1610 pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
1611 open_flags = bs->backing_hd->open_flags;
1612
1613 if (ro) {
1614 if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
1615 return -EACCES;
1616 }
1617 }
1618
1619 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1620 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
1621
1622 for (sector = 0; sector < total_sectors; sector += n) {
1623 if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
1624
1625 if (bdrv_read(bs, sector, buf, n) != 0) {
1626 ret = -EIO;
1627 goto ro_cleanup;
1628 }
1629
1630 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
1631 ret = -EIO;
1632 goto ro_cleanup;
1633 }
1634 }
1635 }
1636
1637 if (drv->bdrv_make_empty) {
1638 ret = drv->bdrv_make_empty(bs);
1639 bdrv_flush(bs);
1640 }
1641
1642 /*
1643 * Make sure all data we wrote to the backing device is actually
1644 * stable on disk.
1645 */
1646 if (bs->backing_hd)
1647 bdrv_flush(bs->backing_hd);
1648
1649 ro_cleanup:
1650 g_free(buf);
1651
1652 if (ro) {
1653 /* ignoring error return here */
1654 bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
1655 }
1656
1657 return ret;
1658 }
1659
1660 int bdrv_commit_all(void)
1661 {
1662 BlockDriverState *bs;
1663
1664 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1665 if (bs->drv && bs->backing_hd) {
1666 int ret = bdrv_commit(bs);
1667 if (ret < 0) {
1668 return ret;
1669 }
1670 }
1671 }
1672 return 0;
1673 }
1674
1675 struct BdrvTrackedRequest {
1676 BlockDriverState *bs;
1677 int64_t sector_num;
1678 int nb_sectors;
1679 bool is_write;
1680 QLIST_ENTRY(BdrvTrackedRequest) list;
1681 Coroutine *co; /* owner, used for deadlock detection */
1682 CoQueue wait_queue; /* coroutines blocked on this request */
1683 };
1684
1685 /**
1686 * Remove an active request from the tracked requests list
1687 *
1688 * This function should be called when a tracked request is completing.
1689 */
1690 static void tracked_request_end(BdrvTrackedRequest *req)
1691 {
1692 QLIST_REMOVE(req, list);
1693 qemu_co_queue_restart_all(&req->wait_queue);
1694 }
1695
1696 /**
1697 * Add an active request to the tracked requests list
1698 */
1699 static void tracked_request_begin(BdrvTrackedRequest *req,
1700 BlockDriverState *bs,
1701 int64_t sector_num,
1702 int nb_sectors, bool is_write)
1703 {
1704 *req = (BdrvTrackedRequest){
1705 .bs = bs,
1706 .sector_num = sector_num,
1707 .nb_sectors = nb_sectors,
1708 .is_write = is_write,
1709 .co = qemu_coroutine_self(),
1710 };
1711
1712 qemu_co_queue_init(&req->wait_queue);
1713
1714 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1715 }
1716
1717 /**
1718 * Round a region to cluster boundaries
1719 */
1720 void bdrv_round_to_clusters(BlockDriverState *bs,
1721 int64_t sector_num, int nb_sectors,
1722 int64_t *cluster_sector_num,
1723 int *cluster_nb_sectors)
1724 {
1725 BlockDriverInfo bdi;
1726
1727 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1728 *cluster_sector_num = sector_num;
1729 *cluster_nb_sectors = nb_sectors;
1730 } else {
1731 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1732 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1733 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1734 nb_sectors, c);
1735 }
1736 }
1737
1738 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1739 int64_t sector_num, int nb_sectors) {
1740 /* aaaa bbbb */
1741 if (sector_num >= req->sector_num + req->nb_sectors) {
1742 return false;
1743 }
1744 /* bbbb aaaa */
1745 if (req->sector_num >= sector_num + nb_sectors) {
1746 return false;
1747 }
1748 return true;
1749 }
1750
1751 static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1752 int64_t sector_num, int nb_sectors)
1753 {
1754 BdrvTrackedRequest *req;
1755 int64_t cluster_sector_num;
1756 int cluster_nb_sectors;
1757 bool retry;
1758
1759 /* If we touch the same cluster it counts as an overlap. This guarantees
1760 * that allocating writes will be serialized and not race with each other
1761 * for the same cluster. For example, in copy-on-read it ensures that the
1762 * CoR read and write operations are atomic and guest writes cannot
1763 * interleave between them.
1764 */
1765 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
1766 &cluster_sector_num, &cluster_nb_sectors);
1767
1768 do {
1769 retry = false;
1770 QLIST_FOREACH(req, &bs->tracked_requests, list) {
1771 if (tracked_request_overlaps(req, cluster_sector_num,
1772 cluster_nb_sectors)) {
1773 /* Hitting this means there was a reentrant request, for
1774 * example, a block driver issuing nested requests. This must
1775 * never happen since it means deadlock.
1776 */
1777 assert(qemu_coroutine_self() != req->co);
1778
1779 qemu_co_queue_wait(&req->wait_queue);
1780 retry = true;
1781 break;
1782 }
1783 }
1784 } while (retry);
1785 }
1786
1787 /*
1788 * Return values:
1789 * 0 - success
1790 * -EINVAL - backing format specified, but no file
1791 * -ENOSPC - can't update the backing file because no space is left in the
1792 * image file header
1793 * -ENOTSUP - format driver doesn't support changing the backing file
1794 */
1795 int bdrv_change_backing_file(BlockDriverState *bs,
1796 const char *backing_file, const char *backing_fmt)
1797 {
1798 BlockDriver *drv = bs->drv;
1799 int ret;
1800
1801 /* Backing file format doesn't make sense without a backing file */
1802 if (backing_fmt && !backing_file) {
1803 return -EINVAL;
1804 }
1805
1806 if (drv->bdrv_change_backing_file != NULL) {
1807 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1808 } else {
1809 ret = -ENOTSUP;
1810 }
1811
1812 if (ret == 0) {
1813 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1814 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1815 }
1816 return ret;
1817 }
1818
1819 /*
1820 * Finds the image layer in the chain that has 'bs' as its backing file.
1821 *
1822 * active is the current topmost image.
1823 *
1824 * Returns NULL if bs is not found in active's image chain,
1825 * or if active == bs.
1826 */
1827 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
1828 BlockDriverState *bs)
1829 {
1830 BlockDriverState *overlay = NULL;
1831 BlockDriverState *intermediate;
1832
1833 assert(active != NULL);
1834 assert(bs != NULL);
1835
1836 /* if bs is the same as active, then by definition it has no overlay
1837 */
1838 if (active == bs) {
1839 return NULL;
1840 }
1841
1842 intermediate = active;
1843 while (intermediate->backing_hd) {
1844 if (intermediate->backing_hd == bs) {
1845 overlay = intermediate;
1846 break;
1847 }
1848 intermediate = intermediate->backing_hd;
1849 }
1850
1851 return overlay;
1852 }
1853
1854 typedef struct BlkIntermediateStates {
1855 BlockDriverState *bs;
1856 QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
1857 } BlkIntermediateStates;
1858
1859
1860 /*
1861 * Drops images above 'base' up to and including 'top', and sets the image
1862 * above 'top' to have base as its backing file.
1863 *
1864 * Requires that the overlay to 'top' is opened r/w, so that the backing file
1865 * information in 'bs' can be properly updated.
1866 *
1867 * E.g., this will convert the following chain:
1868 * bottom <- base <- intermediate <- top <- active
1869 *
1870 * to
1871 *
1872 * bottom <- base <- active
1873 *
1874 * It is allowed for bottom==base, in which case it converts:
1875 *
1876 * base <- intermediate <- top <- active
1877 *
1878 * to
1879 *
1880 * base <- active
1881 *
1882 * Error conditions:
1883 * if active == top, that is considered an error
1884 *
1885 */
1886 int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
1887 BlockDriverState *base)
1888 {
1889 BlockDriverState *intermediate;
1890 BlockDriverState *base_bs = NULL;
1891 BlockDriverState *new_top_bs = NULL;
1892 BlkIntermediateStates *intermediate_state, *next;
1893 int ret = -EIO;
1894
1895 QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
1896 QSIMPLEQ_INIT(&states_to_delete);
1897
1898 if (!top->drv || !base->drv) {
1899 goto exit;
1900 }
1901
1902 new_top_bs = bdrv_find_overlay(active, top);
1903
1904 if (new_top_bs == NULL) {
1905 /* we could not find the image above 'top', this is an error */
1906 goto exit;
1907 }
1908
1909 /* special case of new_top_bs->backing_hd already pointing to base - nothing
1910 * to do, no intermediate images */
1911 if (new_top_bs->backing_hd == base) {
1912 ret = 0;
1913 goto exit;
1914 }
1915
1916 intermediate = top;
1917
1918 /* now we will go down through the list, and add each BDS we find
1919 * into our deletion queue, until we hit the 'base'
1920 */
1921 while (intermediate) {
1922 intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
1923 intermediate_state->bs = intermediate;
1924 QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
1925
1926 if (intermediate->backing_hd == base) {
1927 base_bs = intermediate->backing_hd;
1928 break;
1929 }
1930 intermediate = intermediate->backing_hd;
1931 }
1932 if (base_bs == NULL) {
1933 /* something went wrong, we did not end at the base. safely
1934 * unravel everything, and exit with error */
1935 goto exit;
1936 }
1937
1938 /* success - we can delete the intermediate states, and link top->base */
1939 ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
1940 base_bs->drv ? base_bs->drv->format_name : "");
1941 if (ret) {
1942 goto exit;
1943 }
1944 new_top_bs->backing_hd = base_bs;
1945
1946
1947 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
1948 /* so that bdrv_close() does not recursively close the chain */
1949 intermediate_state->bs->backing_hd = NULL;
1950 bdrv_delete(intermediate_state->bs);
1951 }
1952 ret = 0;
1953
1954 exit:
1955 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
1956 g_free(intermediate_state);
1957 }
1958 return ret;
1959 }
1960
1961
1962 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1963 size_t size)
1964 {
1965 int64_t len;
1966
1967 if (!bdrv_is_inserted(bs))
1968 return -ENOMEDIUM;
1969
1970 if (bs->growable)
1971 return 0;
1972
1973 len = bdrv_getlength(bs);
1974
1975 if (offset < 0)
1976 return -EIO;
1977
1978 if ((offset > len) || (len - offset < size))
1979 return -EIO;
1980
1981 return 0;
1982 }
1983
1984 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1985 int nb_sectors)
1986 {
1987 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1988 nb_sectors * BDRV_SECTOR_SIZE);
1989 }
1990
1991 typedef struct RwCo {
1992 BlockDriverState *bs;
1993 int64_t sector_num;
1994 int nb_sectors;
1995 QEMUIOVector *qiov;
1996 bool is_write;
1997 int ret;
1998 } RwCo;
1999
2000 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2001 {
2002 RwCo *rwco = opaque;
2003
2004 if (!rwco->is_write) {
2005 rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
2006 rwco->nb_sectors, rwco->qiov, 0);
2007 } else {
2008 rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
2009 rwco->nb_sectors, rwco->qiov, 0);
2010 }
2011 }
2012
2013 /*
2014 * Process a synchronous request using coroutines
2015 */
2016 static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
2017 int nb_sectors, bool is_write)
2018 {
2019 QEMUIOVector qiov;
2020 struct iovec iov = {
2021 .iov_base = (void *)buf,
2022 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
2023 };
2024 Coroutine *co;
2025 RwCo rwco = {
2026 .bs = bs,
2027 .sector_num = sector_num,
2028 .nb_sectors = nb_sectors,
2029 .qiov = &qiov,
2030 .is_write = is_write,
2031 .ret = NOT_DONE,
2032 };
2033
2034 qemu_iovec_init_external(&qiov, &iov, 1);
2035
2036 /**
2037 * In sync call context, when the vcpu is blocked, this throttling timer
2038 * will not fire; so the I/O throttling function has to be disabled here
2039 * if it has been enabled.
2040 */
2041 if (bs->io_limits_enabled) {
2042 fprintf(stderr, "Disabling I/O throttling on '%s' due "
2043 "to synchronous I/O.\n", bdrv_get_device_name(bs));
2044 bdrv_io_limits_disable(bs);
2045 }
2046
2047 if (qemu_in_coroutine()) {
2048 /* Fast-path if already in coroutine context */
2049 bdrv_rw_co_entry(&rwco);
2050 } else {
2051 co = qemu_coroutine_create(bdrv_rw_co_entry);
2052 qemu_coroutine_enter(co, &rwco);
2053 while (rwco.ret == NOT_DONE) {
2054 qemu_aio_wait();
2055 }
2056 }
2057 return rwco.ret;
2058 }
2059
2060 /* return < 0 if error. See bdrv_write() for the return codes */
2061 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
2062 uint8_t *buf, int nb_sectors)
2063 {
2064 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
2065 }
2066
2067 /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
2068 int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
2069 uint8_t *buf, int nb_sectors)
2070 {
2071 bool enabled;
2072 int ret;
2073
2074 enabled = bs->io_limits_enabled;
2075 bs->io_limits_enabled = false;
2076 ret = bdrv_read(bs, 0, buf, 1);
2077 bs->io_limits_enabled = enabled;
2078 return ret;
2079 }
2080
2081 /* Return < 0 if error. Important errors are:
2082 -EIO generic I/O error (may happen for all errors)
2083 -ENOMEDIUM No media inserted.
2084 -EINVAL Invalid sector number or nb_sectors
2085 -EACCES Trying to write a read-only device
2086 */
2087 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2088 const uint8_t *buf, int nb_sectors)
2089 {
2090 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
2091 }
2092
2093 int bdrv_pread(BlockDriverState *bs, int64_t offset,
2094 void *buf, int count1)
2095 {
2096 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
2097 int len, nb_sectors, count;
2098 int64_t sector_num;
2099 int ret;
2100
2101 count = count1;
2102 /* first read to align to sector start */
2103 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
2104 if (len > count)
2105 len = count;
2106 sector_num = offset >> BDRV_SECTOR_BITS;
2107 if (len > 0) {
2108 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2109 return ret;
2110 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
2111 count -= len;
2112 if (count == 0)
2113 return count1;
2114 sector_num++;
2115 buf += len;
2116 }
2117
2118 /* read the sectors "in place" */
2119 nb_sectors = count >> BDRV_SECTOR_BITS;
2120 if (nb_sectors > 0) {
2121 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
2122 return ret;
2123 sector_num += nb_sectors;
2124 len = nb_sectors << BDRV_SECTOR_BITS;
2125 buf += len;
2126 count -= len;
2127 }
2128
2129 /* add data from the last sector */
2130 if (count > 0) {
2131 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2132 return ret;
2133 memcpy(buf, tmp_buf, count);
2134 }
2135 return count1;
2136 }
2137
2138 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
2139 const void *buf, int count1)
2140 {
2141 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
2142 int len, nb_sectors, count;
2143 int64_t sector_num;
2144 int ret;
2145
2146 count = count1;
2147 /* first write to align to sector start */
2148 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
2149 if (len > count)
2150 len = count;
2151 sector_num = offset >> BDRV_SECTOR_BITS;
2152 if (len > 0) {
2153 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2154 return ret;
2155 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
2156 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2157 return ret;
2158 count -= len;
2159 if (count == 0)
2160 return count1;
2161 sector_num++;
2162 buf += len;
2163 }
2164
2165 /* write the sectors "in place" */
2166 nb_sectors = count >> BDRV_SECTOR_BITS;
2167 if (nb_sectors > 0) {
2168 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
2169 return ret;
2170 sector_num += nb_sectors;
2171 len = nb_sectors << BDRV_SECTOR_BITS;
2172 buf += len;
2173 count -= len;
2174 }
2175
2176 /* add data from the last sector */
2177 if (count > 0) {
2178 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2179 return ret;
2180 memcpy(tmp_buf, buf, count);
2181 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2182 return ret;
2183 }
2184 return count1;
2185 }
2186
2187 /*
2188 * Writes to the file and ensures that no writes are reordered across this
2189 * request (acts as a barrier)
2190 *
2191 * Returns 0 on success, -errno in error cases.
2192 */
2193 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2194 const void *buf, int count)
2195 {
2196 int ret;
2197
2198 ret = bdrv_pwrite(bs, offset, buf, count);
2199 if (ret < 0) {
2200 return ret;
2201 }
2202
2203 /* No flush needed for cache modes that already do it */
2204 if (bs->enable_write_cache) {
2205 bdrv_flush(bs);
2206 }
2207
2208 return 0;
2209 }
2210
2211 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2212 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2213 {
2214 /* Perform I/O through a temporary buffer so that users who scribble over
2215 * their read buffer while the operation is in progress do not end up
2216 * modifying the image file. This is critical for zero-copy guest I/O
2217 * where anything might happen inside guest memory.
2218 */
2219 void *bounce_buffer;
2220
2221 BlockDriver *drv = bs->drv;
2222 struct iovec iov;
2223 QEMUIOVector bounce_qiov;
2224 int64_t cluster_sector_num;
2225 int cluster_nb_sectors;
2226 size_t skip_bytes;
2227 int ret;
2228
2229 /* Cover entire cluster so no additional backing file I/O is required when
2230 * allocating cluster in the image file.
2231 */
2232 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2233 &cluster_sector_num, &cluster_nb_sectors);
2234
2235 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2236 cluster_sector_num, cluster_nb_sectors);
2237
2238 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2239 iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2240 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2241
2242 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2243 &bounce_qiov);
2244 if (ret < 0) {
2245 goto err;
2246 }
2247
2248 if (drv->bdrv_co_write_zeroes &&
2249 buffer_is_zero(bounce_buffer, iov.iov_len)) {
2250 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2251 cluster_nb_sectors);
2252 } else {
2253 /* This does not change the data on the disk, it is not necessary
2254 * to flush even in cache=writethrough mode.
2255 */
2256 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2257 &bounce_qiov);
2258 }
2259
2260 if (ret < 0) {
2261 /* It might be okay to ignore write errors for guest requests. If this
2262 * is a deliberate copy-on-read then we don't want to ignore the error.
2263 * Simply report it in all cases.
2264 */
2265 goto err;
2266 }
2267
2268 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
2269 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2270 nb_sectors * BDRV_SECTOR_SIZE);
2271
2272 err:
2273 qemu_vfree(bounce_buffer);
2274 return ret;
2275 }
2276
2277 /*
2278 * Handle a read request in coroutine context
2279 */
2280 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2281 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2282 BdrvRequestFlags flags)
2283 {
2284 BlockDriver *drv = bs->drv;
2285 BdrvTrackedRequest req;
2286 int ret;
2287
2288 if (!drv) {
2289 return -ENOMEDIUM;
2290 }
2291 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2292 return -EIO;
2293 }
2294
2295 /* throttling disk read I/O */
2296 if (bs->io_limits_enabled) {
2297 bdrv_io_limits_intercept(bs, false, nb_sectors);
2298 }
2299
2300 if (bs->copy_on_read) {
2301 flags |= BDRV_REQ_COPY_ON_READ;
2302 }
2303 if (flags & BDRV_REQ_COPY_ON_READ) {
2304 bs->copy_on_read_in_flight++;
2305 }
2306
2307 if (bs->copy_on_read_in_flight) {
2308 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2309 }
2310
2311 tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2312
2313 if (flags & BDRV_REQ_COPY_ON_READ) {
2314 int pnum;
2315
2316 ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2317 if (ret < 0) {
2318 goto out;
2319 }
2320
2321 if (!ret || pnum != nb_sectors) {
2322 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2323 goto out;
2324 }
2325 }
2326
2327 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2328
2329 out:
2330 tracked_request_end(&req);
2331
2332 if (flags & BDRV_REQ_COPY_ON_READ) {
2333 bs->copy_on_read_in_flight--;
2334 }
2335
2336 return ret;
2337 }
2338
2339 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2340 int nb_sectors, QEMUIOVector *qiov)
2341 {
2342 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2343
2344 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2345 }
2346
2347 int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2348 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2349 {
2350 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2351
2352 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2353 BDRV_REQ_COPY_ON_READ);
2354 }
2355
2356 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2357 int64_t sector_num, int nb_sectors)
2358 {
2359 BlockDriver *drv = bs->drv;
2360 QEMUIOVector qiov;
2361 struct iovec iov;
2362 int ret;
2363
2364 /* TODO Emulate only part of misaligned requests instead of letting block
2365 * drivers return -ENOTSUP and emulate everything */
2366
2367 /* First try the efficient write zeroes operation */
2368 if (drv->bdrv_co_write_zeroes) {
2369 ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2370 if (ret != -ENOTSUP) {
2371 return ret;
2372 }
2373 }
2374
2375 /* Fall back to bounce buffer if write zeroes is unsupported */
2376 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2377 iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2378 memset(iov.iov_base, 0, iov.iov_len);
2379 qemu_iovec_init_external(&qiov, &iov, 1);
2380
2381 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2382
2383 qemu_vfree(iov.iov_base);
2384 return ret;
2385 }
2386
2387 /*
2388 * Handle a write request in coroutine context
2389 */
2390 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2391 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2392 BdrvRequestFlags flags)
2393 {
2394 BlockDriver *drv = bs->drv;
2395 BdrvTrackedRequest req;
2396 int ret;
2397
2398 if (!bs->drv) {
2399 return -ENOMEDIUM;
2400 }
2401 if (bs->read_only) {
2402 return -EACCES;
2403 }
2404 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2405 return -EIO;
2406 }
2407
2408 /* throttling disk write I/O */
2409 if (bs->io_limits_enabled) {
2410 bdrv_io_limits_intercept(bs, true, nb_sectors);
2411 }
2412
2413 if (bs->copy_on_read_in_flight) {
2414 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2415 }
2416
2417 tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2418
2419 if (flags & BDRV_REQ_ZERO_WRITE) {
2420 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2421 } else {
2422 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2423 }
2424
2425 if (ret == 0 && !bs->enable_write_cache) {
2426 ret = bdrv_co_flush(bs);
2427 }
2428
2429 if (bs->dirty_bitmap) {
2430 bdrv_set_dirty(bs, sector_num, nb_sectors);
2431 }
2432
2433 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2434 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2435 }
2436
2437 tracked_request_end(&req);
2438
2439 return ret;
2440 }
2441
2442 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2443 int nb_sectors, QEMUIOVector *qiov)
2444 {
2445 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2446
2447 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2448 }
2449
2450 int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2451 int64_t sector_num, int nb_sectors)
2452 {
2453 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2454
2455 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2456 BDRV_REQ_ZERO_WRITE);
2457 }
2458
2459 /**
2460 * Truncate file to 'offset' bytes (needed only for file protocols)
2461 */
2462 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
2463 {
2464 BlockDriver *drv = bs->drv;
2465 int ret;
2466 if (!drv)
2467 return -ENOMEDIUM;
2468 if (!drv->bdrv_truncate)
2469 return -ENOTSUP;
2470 if (bs->read_only)
2471 return -EACCES;
2472 if (bdrv_in_use(bs))
2473 return -EBUSY;
2474
2475 /* There better not be any in-flight IOs when we truncate the device. */
2476 bdrv_drain_all();
2477
2478 ret = drv->bdrv_truncate(bs, offset);
2479 if (ret == 0) {
2480 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2481 bdrv_dev_resize_cb(bs);
2482 }
2483 return ret;
2484 }
2485
2486 /**
2487 * Length of a allocated file in bytes. Sparse files are counted by actual
2488 * allocated space. Return < 0 if error or unknown.
2489 */
2490 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
2491 {
2492 BlockDriver *drv = bs->drv;
2493 if (!drv) {
2494 return -ENOMEDIUM;
2495 }
2496 if (drv->bdrv_get_allocated_file_size) {
2497 return drv->bdrv_get_allocated_file_size(bs);
2498 }
2499 if (bs->file) {
2500 return bdrv_get_allocated_file_size(bs->file);
2501 }
2502 return -ENOTSUP;
2503 }
2504
2505 /**
2506 * Length of a file in bytes. Return < 0 if error or unknown.
2507 */
2508 int64_t bdrv_getlength(BlockDriverState *bs)
2509 {
2510 BlockDriver *drv = bs->drv;
2511 if (!drv)
2512 return -ENOMEDIUM;
2513
2514 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
2515 if (drv->bdrv_getlength) {
2516 return drv->bdrv_getlength(bs);
2517 }
2518 }
2519 return bs->total_sectors * BDRV_SECTOR_SIZE;
2520 }
2521
2522 /* return 0 as number of sectors if no device present or error */
2523 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2524 {
2525 int64_t length;
2526 length = bdrv_getlength(bs);
2527 if (length < 0)
2528 length = 0;
2529 else
2530 length = length >> BDRV_SECTOR_BITS;
2531 *nb_sectors_ptr = length;
2532 }
2533
2534 /* throttling disk io limits */
2535 void bdrv_set_io_limits(BlockDriverState *bs,
2536 BlockIOLimit *io_limits)
2537 {
2538 bs->io_limits = *io_limits;
2539 bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
2540 }
2541
2542 void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2543 BlockdevOnError on_write_error)
2544 {
2545 bs->on_read_error = on_read_error;
2546 bs->on_write_error = on_write_error;
2547 }
2548
2549 BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2550 {
2551 return is_read ? bs->on_read_error : bs->on_write_error;
2552 }
2553
2554 BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
2555 {
2556 BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
2557
2558 switch (on_err) {
2559 case BLOCKDEV_ON_ERROR_ENOSPC:
2560 return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
2561 case BLOCKDEV_ON_ERROR_STOP:
2562 return BDRV_ACTION_STOP;
2563 case BLOCKDEV_ON_ERROR_REPORT:
2564 return BDRV_ACTION_REPORT;
2565 case BLOCKDEV_ON_ERROR_IGNORE:
2566 return BDRV_ACTION_IGNORE;
2567 default:
2568 abort();
2569 }
2570 }
2571
2572 /* This is done by device models because, while the block layer knows
2573 * about the error, it does not know whether an operation comes from
2574 * the device or the block layer (from a job, for example).
2575 */
2576 void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
2577 bool is_read, int error)
2578 {
2579 assert(error >= 0);
2580 bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
2581 if (action == BDRV_ACTION_STOP) {
2582 vm_stop(RUN_STATE_IO_ERROR);
2583 bdrv_iostatus_set_err(bs, error);
2584 }
2585 }
2586
2587 int bdrv_is_read_only(BlockDriverState *bs)
2588 {
2589 return bs->read_only;
2590 }
2591
2592 int bdrv_is_sg(BlockDriverState *bs)
2593 {
2594 return bs->sg;
2595 }
2596
2597 int bdrv_enable_write_cache(BlockDriverState *bs)
2598 {
2599 return bs->enable_write_cache;
2600 }
2601
2602 void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2603 {
2604 bs->enable_write_cache = wce;
2605
2606 /* so a reopen() will preserve wce */
2607 if (wce) {
2608 bs->open_flags |= BDRV_O_CACHE_WB;
2609 } else {
2610 bs->open_flags &= ~BDRV_O_CACHE_WB;
2611 }
2612 }
2613
2614 int bdrv_is_encrypted(BlockDriverState *bs)
2615 {
2616 if (bs->backing_hd && bs->backing_hd->encrypted)
2617 return 1;
2618 return bs->encrypted;
2619 }
2620
2621 int bdrv_key_required(BlockDriverState *bs)
2622 {
2623 BlockDriverState *backing_hd = bs->backing_hd;
2624
2625 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2626 return 1;
2627 return (bs->encrypted && !bs->valid_key);
2628 }
2629
2630 int bdrv_set_key(BlockDriverState *bs, const char *key)
2631 {
2632 int ret;
2633 if (bs->backing_hd && bs->backing_hd->encrypted) {
2634 ret = bdrv_set_key(bs->backing_hd, key);
2635 if (ret < 0)
2636 return ret;
2637 if (!bs->encrypted)
2638 return 0;
2639 }
2640 if (!bs->encrypted) {
2641 return -EINVAL;
2642 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2643 return -ENOMEDIUM;
2644 }
2645 ret = bs->drv->bdrv_set_key(bs, key);
2646 if (ret < 0) {
2647 bs->valid_key = 0;
2648 } else if (!bs->valid_key) {
2649 bs->valid_key = 1;
2650 /* call the change callback now, we skipped it on open */
2651 bdrv_dev_change_media_cb(bs, true);
2652 }
2653 return ret;
2654 }
2655
2656 const char *bdrv_get_format_name(BlockDriverState *bs)
2657 {
2658 return bs->drv ? bs->drv->format_name : NULL;
2659 }
2660
2661 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2662 void *opaque)
2663 {
2664 BlockDriver *drv;
2665
2666 QLIST_FOREACH(drv, &bdrv_drivers, list) {
2667 it(opaque, drv->format_name);
2668 }
2669 }
2670
2671 BlockDriverState *bdrv_find(const char *name)
2672 {
2673 BlockDriverState *bs;
2674
2675 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2676 if (!strcmp(name, bs->device_name)) {
2677 return bs;
2678 }
2679 }
2680 return NULL;
2681 }
2682
2683 BlockDriverState *bdrv_next(BlockDriverState *bs)
2684 {
2685 if (!bs) {
2686 return QTAILQ_FIRST(&bdrv_states);
2687 }
2688 return QTAILQ_NEXT(bs, list);
2689 }
2690
2691 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
2692 {
2693 BlockDriverState *bs;
2694
2695 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2696 it(opaque, bs);
2697 }
2698 }
2699
2700 const char *bdrv_get_device_name(BlockDriverState *bs)
2701 {
2702 return bs->device_name;
2703 }
2704
2705 int bdrv_get_flags(BlockDriverState *bs)
2706 {
2707 return bs->open_flags;
2708 }
2709
2710 void bdrv_flush_all(void)
2711 {
2712 BlockDriverState *bs;
2713
2714 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2715 bdrv_flush(bs);
2716 }
2717 }
2718
2719 int bdrv_has_zero_init(BlockDriverState *bs)
2720 {
2721 assert(bs->drv);
2722
2723 if (bs->drv->bdrv_has_zero_init) {
2724 return bs->drv->bdrv_has_zero_init(bs);
2725 }
2726
2727 return 1;
2728 }
2729
2730 typedef struct BdrvCoIsAllocatedData {
2731 BlockDriverState *bs;
2732 BlockDriverState *base;
2733 int64_t sector_num;
2734 int nb_sectors;
2735 int *pnum;
2736 int ret;
2737 bool done;
2738 } BdrvCoIsAllocatedData;
2739
2740 /*
2741 * Returns true iff the specified sector is present in the disk image. Drivers
2742 * not implementing the functionality are assumed to not support backing files,
2743 * hence all their sectors are reported as allocated.
2744 *
2745 * If 'sector_num' is beyond the end of the disk image the return value is 0
2746 * and 'pnum' is set to 0.
2747 *
2748 * 'pnum' is set to the number of sectors (including and immediately following
2749 * the specified sector) that are known to be in the same
2750 * allocated/unallocated state.
2751 *
2752 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
2753 * beyond the end of the disk image it will be clamped.
2754 */
2755 int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2756 int nb_sectors, int *pnum)
2757 {
2758 int64_t n;
2759
2760 if (sector_num >= bs->total_sectors) {
2761 *pnum = 0;
2762 return 0;
2763 }
2764
2765 n = bs->total_sectors - sector_num;
2766 if (n < nb_sectors) {
2767 nb_sectors = n;
2768 }
2769
2770 if (!bs->drv->bdrv_co_is_allocated) {
2771 *pnum = nb_sectors;
2772 return 1;
2773 }
2774
2775 return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2776 }
2777
2778 /* Coroutine wrapper for bdrv_is_allocated() */
2779 static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2780 {
2781 BdrvCoIsAllocatedData *data = opaque;
2782 BlockDriverState *bs = data->bs;
2783
2784 data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2785 data->pnum);
2786 data->done = true;
2787 }
2788
2789 /*
2790 * Synchronous wrapper around bdrv_co_is_allocated().
2791 *
2792 * See bdrv_co_is_allocated() for details.
2793 */
2794 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2795 int *pnum)
2796 {
2797 Coroutine *co;
2798 BdrvCoIsAllocatedData data = {
2799 .bs = bs,
2800 .sector_num = sector_num,
2801 .nb_sectors = nb_sectors,
2802 .pnum = pnum,
2803 .done = false,
2804 };
2805
2806 co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
2807 qemu_coroutine_enter(co, &data);
2808 while (!data.done) {
2809 qemu_aio_wait();
2810 }
2811 return data.ret;
2812 }
2813
2814 /*
2815 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2816 *
2817 * Return true if the given sector is allocated in any image between
2818 * BASE and TOP (inclusive). BASE can be NULL to check if the given
2819 * sector is allocated in any image of the chain. Return false otherwise.
2820 *
2821 * 'pnum' is set to the number of sectors (including and immediately following
2822 * the specified sector) that are known to be in the same
2823 * allocated/unallocated state.
2824 *
2825 */
2826 int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
2827 BlockDriverState *base,
2828 int64_t sector_num,
2829 int nb_sectors, int *pnum)
2830 {
2831 BlockDriverState *intermediate;
2832 int ret, n = nb_sectors;
2833
2834 intermediate = top;
2835 while (intermediate && intermediate != base) {
2836 int pnum_inter;
2837 ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
2838 &pnum_inter);
2839 if (ret < 0) {
2840 return ret;
2841 } else if (ret) {
2842 *pnum = pnum_inter;
2843 return 1;
2844 }
2845
2846 /*
2847 * [sector_num, nb_sectors] is unallocated on top but intermediate
2848 * might have
2849 *
2850 * [sector_num+x, nr_sectors] allocated.
2851 */
2852 if (n > pnum_inter &&
2853 (intermediate == top ||
2854 sector_num + pnum_inter < intermediate->total_sectors)) {
2855 n = pnum_inter;
2856 }
2857
2858 intermediate = intermediate->backing_hd;
2859 }
2860
2861 *pnum = n;
2862 return 0;
2863 }
2864
2865 /* Coroutine wrapper for bdrv_is_allocated_above() */
2866 static void coroutine_fn bdrv_is_allocated_above_co_entry(void *opaque)
2867 {
2868 BdrvCoIsAllocatedData *data = opaque;
2869 BlockDriverState *top = data->bs;
2870 BlockDriverState *base = data->base;
2871
2872 data->ret = bdrv_co_is_allocated_above(top, base, data->sector_num,
2873 data->nb_sectors, data->pnum);
2874 data->done = true;
2875 }
2876
2877 /*
2878 * Synchronous wrapper around bdrv_co_is_allocated_above().
2879 *
2880 * See bdrv_co_is_allocated_above() for details.
2881 */
2882 int bdrv_is_allocated_above(BlockDriverState *top, BlockDriverState *base,
2883 int64_t sector_num, int nb_sectors, int *pnum)
2884 {
2885 Coroutine *co;
2886 BdrvCoIsAllocatedData data = {
2887 .bs = top,
2888 .base = base,
2889 .sector_num = sector_num,
2890 .nb_sectors = nb_sectors,
2891 .pnum = pnum,
2892 .done = false,
2893 };
2894
2895 co = qemu_coroutine_create(bdrv_is_allocated_above_co_entry);
2896 qemu_coroutine_enter(co, &data);
2897 while (!data.done) {
2898 qemu_aio_wait();
2899 }
2900 return data.ret;
2901 }
2902
2903 BlockInfo *bdrv_query_info(BlockDriverState *bs)
2904 {
2905 BlockInfo *info = g_malloc0(sizeof(*info));
2906 info->device = g_strdup(bs->device_name);
2907 info->type = g_strdup("unknown");
2908 info->locked = bdrv_dev_is_medium_locked(bs);
2909 info->removable = bdrv_dev_has_removable_media(bs);
2910
2911 if (bdrv_dev_has_removable_media(bs)) {
2912 info->has_tray_open = true;
2913 info->tray_open = bdrv_dev_is_tray_open(bs);
2914 }
2915
2916 if (bdrv_iostatus_is_enabled(bs)) {
2917 info->has_io_status = true;
2918 info->io_status = bs->iostatus;
2919 }
2920
2921 if (bs->dirty_bitmap) {
2922 info->has_dirty = true;
2923 info->dirty = g_malloc0(sizeof(*info->dirty));
2924 info->dirty->count = bdrv_get_dirty_count(bs) * BDRV_SECTOR_SIZE;
2925 info->dirty->granularity =
2926 ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bs->dirty_bitmap));
2927 }
2928
2929 if (bs->drv) {
2930 info->has_inserted = true;
2931 info->inserted = g_malloc0(sizeof(*info->inserted));
2932 info->inserted->file = g_strdup(bs->filename);
2933 info->inserted->ro = bs->read_only;
2934 info->inserted->drv = g_strdup(bs->drv->format_name);
2935 info->inserted->encrypted = bs->encrypted;
2936 info->inserted->encryption_key_missing = bdrv_key_required(bs);
2937
2938 if (bs->backing_file[0]) {
2939 info->inserted->has_backing_file = true;
2940 info->inserted->backing_file = g_strdup(bs->backing_file);
2941 }
2942
2943 info->inserted->backing_file_depth = bdrv_get_backing_file_depth(bs);
2944
2945 if (bs->io_limits_enabled) {
2946 info->inserted->bps =
2947 bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
2948 info->inserted->bps_rd =
2949 bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
2950 info->inserted->bps_wr =
2951 bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
2952 info->inserted->iops =
2953 bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
2954 info->inserted->iops_rd =
2955 bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
2956 info->inserted->iops_wr =
2957 bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
2958 }
2959 }
2960 return info;
2961 }
2962
2963 BlockInfoList *qmp_query_block(Error **errp)
2964 {
2965 BlockInfoList *head = NULL, **p_next = &head;
2966 BlockDriverState *bs;
2967
2968 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2969 BlockInfoList *info = g_malloc0(sizeof(*info));
2970 info->value = bdrv_query_info(bs);
2971
2972 *p_next = info;
2973 p_next = &info->next;
2974 }
2975
2976 return head;
2977 }
2978
2979 BlockStats *bdrv_query_stats(const BlockDriverState *bs)
2980 {
2981 BlockStats *s;
2982
2983 s = g_malloc0(sizeof(*s));
2984
2985 if (bs->device_name[0]) {
2986 s->has_device = true;
2987 s->device = g_strdup(bs->device_name);
2988 }
2989
2990 s->stats = g_malloc0(sizeof(*s->stats));
2991 s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
2992 s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
2993 s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
2994 s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
2995 s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
2996 s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
2997 s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
2998 s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
2999 s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
3000
3001 if (bs->file) {
3002 s->has_parent = true;
3003 s->parent = bdrv_query_stats(bs->file);
3004 }
3005
3006 return s;
3007 }
3008
3009 BlockStatsList *qmp_query_blockstats(Error **errp)
3010 {
3011 BlockStatsList *head = NULL, **p_next = &head;
3012 BlockDriverState *bs;
3013
3014 QTAILQ_FOREACH(bs, &bdrv_states, list) {
3015 BlockStatsList *info = g_malloc0(sizeof(*info));
3016 info->value = bdrv_query_stats(bs);
3017
3018 *p_next = info;
3019 p_next = &info->next;
3020 }
3021
3022 return head;
3023 }
3024
3025 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3026 {
3027 if (bs->backing_hd && bs->backing_hd->encrypted)
3028 return bs->backing_file;
3029 else if (bs->encrypted)
3030 return bs->filename;
3031 else
3032 return NULL;
3033 }
3034
3035 void bdrv_get_backing_filename(BlockDriverState *bs,
3036 char *filename, int filename_size)
3037 {
3038 pstrcpy(filename, filename_size, bs->backing_file);
3039 }
3040
3041 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3042 const uint8_t *buf, int nb_sectors)
3043 {
3044 BlockDriver *drv = bs->drv;
3045 if (!drv)
3046 return -ENOMEDIUM;
3047 if (!drv->bdrv_write_compressed)
3048 return -ENOTSUP;
3049 if (bdrv_check_request(bs, sector_num, nb_sectors))
3050 return -EIO;
3051
3052 assert(!bs->dirty_bitmap);
3053
3054 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3055 }
3056
3057 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3058 {
3059 BlockDriver *drv = bs->drv;
3060 if (!drv)
3061 return -ENOMEDIUM;
3062 if (!drv->bdrv_get_info)
3063 return -ENOTSUP;
3064 memset(bdi, 0, sizeof(*bdi));
3065 return drv->bdrv_get_info(bs, bdi);
3066 }
3067
3068 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
3069 int64_t pos, int size)
3070 {
3071 BlockDriver *drv = bs->drv;
3072 if (!drv)
3073 return -ENOMEDIUM;
3074 if (drv->bdrv_save_vmstate)
3075 return drv->bdrv_save_vmstate(bs, buf, pos, size);
3076 if (bs->file)
3077 return bdrv_save_vmstate(bs->file, buf, pos, size);
3078 return -ENOTSUP;
3079 }
3080
3081 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
3082 int64_t pos, int size)
3083 {
3084 BlockDriver *drv = bs->drv;
3085 if (!drv)
3086 return -ENOMEDIUM;
3087 if (drv->bdrv_load_vmstate)
3088 return drv->bdrv_load_vmstate(bs, buf, pos, size);
3089 if (bs->file)
3090 return bdrv_load_vmstate(bs->file, buf, pos, size);
3091 return -ENOTSUP;
3092 }
3093
3094 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
3095 {
3096 BlockDriver *drv = bs->drv;
3097
3098 if (!drv || !drv->bdrv_debug_event) {
3099 return;
3100 }
3101
3102 drv->bdrv_debug_event(bs, event);
3103 }
3104
3105 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3106 const char *tag)
3107 {
3108 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
3109 bs = bs->file;
3110 }
3111
3112 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3113 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3114 }
3115
3116 return -ENOTSUP;
3117 }
3118
3119 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3120 {
3121 while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
3122 bs = bs->file;
3123 }
3124
3125 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3126 return bs->drv->bdrv_debug_resume(bs, tag);
3127 }
3128
3129 return -ENOTSUP;
3130 }
3131
3132 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3133 {
3134 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
3135 bs = bs->file;
3136 }
3137
3138 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3139 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3140 }
3141
3142 return false;
3143 }
3144
3145 /**************************************************************/
3146 /* handling of snapshots */
3147
3148 int bdrv_can_snapshot(BlockDriverState *bs)
3149 {
3150 BlockDriver *drv = bs->drv;
3151 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
3152 return 0;
3153 }
3154
3155 if (!drv->bdrv_snapshot_create) {
3156 if (bs->file != NULL) {
3157 return bdrv_can_snapshot(bs->file);
3158 }
3159 return 0;
3160 }
3161
3162 return 1;
3163 }
3164
3165 int bdrv_is_snapshot(BlockDriverState *bs)
3166 {
3167 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3168 }
3169
3170 BlockDriverState *bdrv_snapshots(void)
3171 {
3172 BlockDriverState *bs;
3173
3174 if (bs_snapshots) {
3175 return bs_snapshots;
3176 }
3177
3178 bs = NULL;
3179 while ((bs = bdrv_next(bs))) {
3180 if (bdrv_can_snapshot(bs)) {
3181 bs_snapshots = bs;
3182 return bs;
3183 }
3184 }
3185 return NULL;
3186 }
3187
3188 int bdrv_snapshot_create(BlockDriverState *bs,
3189 QEMUSnapshotInfo *sn_info)
3190 {
3191 BlockDriver *drv = bs->drv;
3192 if (!drv)
3193 return -ENOMEDIUM;
3194 if (drv->bdrv_snapshot_create)
3195 return drv->bdrv_snapshot_create(bs, sn_info);
3196 if (bs->file)
3197 return bdrv_snapshot_create(bs->file, sn_info);
3198 return -ENOTSUP;
3199 }
3200
3201 int bdrv_snapshot_goto(BlockDriverState *bs,
3202 const char *snapshot_id)
3203 {
3204 BlockDriver *drv = bs->drv;
3205 int ret, open_ret;
3206
3207 if (!drv)
3208 return -ENOMEDIUM;
3209 if (drv->bdrv_snapshot_goto)
3210 return drv->bdrv_snapshot_goto(bs, snapshot_id);
3211
3212 if (bs->file) {
3213 drv->bdrv_close(bs);
3214 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
3215 open_ret = drv->bdrv_open(bs, NULL, bs->open_flags);
3216 if (open_ret < 0) {
3217 bdrv_delete(bs->file);
3218 bs->drv = NULL;
3219 return open_ret;
3220 }
3221 return ret;
3222 }
3223
3224 return -ENOTSUP;
3225 }
3226
3227 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
3228 {
3229 BlockDriver *drv = bs->drv;
3230 if (!drv)
3231 return -ENOMEDIUM;
3232 if (drv->bdrv_snapshot_delete)
3233 return drv->bdrv_snapshot_delete(bs, snapshot_id);
3234 if (bs->file)
3235 return bdrv_snapshot_delete(bs->file, snapshot_id);
3236 return -ENOTSUP;
3237 }
3238
3239 int bdrv_snapshot_list(BlockDriverState *bs,
3240 QEMUSnapshotInfo **psn_info)
3241 {
3242 BlockDriver *drv = bs->drv;
3243 if (!drv)
3244 return -ENOMEDIUM;
3245 if (drv->bdrv_snapshot_list)
3246 return drv->bdrv_snapshot_list(bs, psn_info);
3247 if (bs->file)
3248 return bdrv_snapshot_list(bs->file, psn_info);
3249 return -ENOTSUP;
3250 }
3251
3252 int bdrv_snapshot_load_tmp(BlockDriverState *bs,
3253 const char *snapshot_name)
3254 {
3255 BlockDriver *drv = bs->drv;
3256 if (!drv) {
3257 return -ENOMEDIUM;
3258 }
3259 if (!bs->read_only) {
3260 return -EINVAL;
3261 }
3262 if (drv->bdrv_snapshot_load_tmp) {
3263 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
3264 }
3265 return -ENOTSUP;
3266 }
3267
3268 /* backing_file can either be relative, or absolute, or a protocol. If it is
3269 * relative, it must be relative to the chain. So, passing in bs->filename
3270 * from a BDS as backing_file should not be done, as that may be relative to
3271 * the CWD rather than the chain. */
3272 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3273 const char *backing_file)
3274 {
3275 char *filename_full = NULL;
3276 char *backing_file_full = NULL;
3277 char *filename_tmp = NULL;
3278 int is_protocol = 0;
3279 BlockDriverState *curr_bs = NULL;
3280 BlockDriverState *retval = NULL;
3281
3282 if (!bs || !bs->drv || !backing_file) {
3283 return NULL;
3284 }
3285
3286 filename_full = g_malloc(PATH_MAX);
3287 backing_file_full = g_malloc(PATH_MAX);
3288 filename_tmp = g_malloc(PATH_MAX);
3289
3290 is_protocol = path_has_protocol(backing_file);
3291
3292 for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3293
3294 /* If either of the filename paths is actually a protocol, then
3295 * compare unmodified paths; otherwise make paths relative */
3296 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3297 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3298 retval = curr_bs->backing_hd;
3299 break;
3300 }
3301 } else {
3302 /* If not an absolute filename path, make it relative to the current
3303 * image's filename path */
3304 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3305 backing_file);
3306
3307 /* We are going to compare absolute pathnames */
3308 if (!realpath(filename_tmp, filename_full)) {
3309 continue;
3310 }
3311
3312 /* We need to make sure the backing filename we are comparing against
3313 * is relative to the current image filename (or absolute) */
3314 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3315 curr_bs->backing_file);
3316
3317 if (!realpath(filename_tmp, backing_file_full)) {
3318 continue;
3319 }
3320
3321 if (strcmp(backing_file_full, filename_full) == 0) {
3322 retval = curr_bs->backing_hd;
3323 break;
3324 }
3325 }
3326 }
3327
3328 g_free(filename_full);
3329 g_free(backing_file_full);
3330 g_free(filename_tmp);
3331 return retval;
3332 }
3333
3334 int bdrv_get_backing_file_depth(BlockDriverState *bs)
3335 {
3336 if (!bs->drv) {
3337 return 0;
3338 }
3339
3340 if (!bs->backing_hd) {
3341 return 0;
3342 }
3343
3344 return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3345 }
3346
3347 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3348 {
3349 BlockDriverState *curr_bs = NULL;
3350
3351 if (!bs) {
3352 return NULL;
3353 }
3354
3355 curr_bs = bs;
3356
3357 while (curr_bs->backing_hd) {
3358 curr_bs = curr_bs->backing_hd;
3359 }
3360 return curr_bs;
3361 }
3362
3363 #define NB_SUFFIXES 4
3364
3365 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
3366 {
3367 static const char suffixes[NB_SUFFIXES] = "KMGT";
3368 int64_t base;
3369 int i;
3370
3371 if (size <= 999) {
3372 snprintf(buf, buf_size, "%" PRId64, size);
3373 } else {
3374 base = 1024;
3375 for(i = 0; i < NB_SUFFIXES; i++) {
3376 if (size < (10 * base)) {
3377 snprintf(buf, buf_size, "%0.1f%c",
3378 (double)size / base,
3379 suffixes[i]);
3380 break;
3381 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
3382 snprintf(buf, buf_size, "%" PRId64 "%c",
3383 ((size + (base >> 1)) / base),
3384 suffixes[i]);
3385 break;
3386 }
3387 base = base * 1024;
3388 }
3389 }
3390 return buf;
3391 }
3392
3393 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
3394 {
3395 char buf1[128], date_buf[128], clock_buf[128];
3396 struct tm tm;
3397 time_t ti;
3398 int64_t secs;
3399
3400 if (!sn) {
3401 snprintf(buf, buf_size,
3402 "%-10s%-20s%7s%20s%15s",
3403 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
3404 } else {
3405 ti = sn->date_sec;
3406 localtime_r(&ti, &tm);
3407 strftime(date_buf, sizeof(date_buf),
3408 "%Y-%m-%d %H:%M:%S", &tm);
3409 secs = sn->vm_clock_nsec / 1000000000;
3410 snprintf(clock_buf, sizeof(clock_buf),
3411 "%02d:%02d:%02d.%03d",
3412 (int)(secs / 3600),
3413 (int)((secs / 60) % 60),
3414 (int)(secs % 60),
3415 (int)((sn->vm_clock_nsec / 1000000) % 1000));
3416 snprintf(buf, buf_size,
3417 "%-10s%-20s%7s%20s%15s",
3418 sn->id_str, sn->name,
3419 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
3420 date_buf,
3421 clock_buf);
3422 }
3423 return buf;
3424 }
3425
3426 /**************************************************************/
3427 /* async I/Os */
3428
3429 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3430 QEMUIOVector *qiov, int nb_sectors,
3431 BlockDriverCompletionFunc *cb, void *opaque)
3432 {
3433 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3434
3435 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
3436 cb, opaque, false);
3437 }
3438
3439 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3440 QEMUIOVector *qiov, int nb_sectors,
3441 BlockDriverCompletionFunc *cb, void *opaque)
3442 {
3443 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3444
3445 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
3446 cb, opaque, true);
3447 }
3448
3449
3450 typedef struct MultiwriteCB {
3451 int error;
3452 int num_requests;
3453 int num_callbacks;
3454 struct {
3455 BlockDriverCompletionFunc *cb;
3456 void *opaque;
3457 QEMUIOVector *free_qiov;
3458 } callbacks[];
3459 } MultiwriteCB;
3460
3461 static void multiwrite_user_cb(MultiwriteCB *mcb)
3462 {
3463 int i;
3464
3465 for (i = 0; i < mcb->num_callbacks; i++) {
3466 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
3467 if (mcb->callbacks[i].free_qiov) {
3468 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
3469 }
3470 g_free(mcb->callbacks[i].free_qiov);
3471 }
3472 }
3473
3474 static void multiwrite_cb(void *opaque, int ret)
3475 {
3476 MultiwriteCB *mcb = opaque;
3477
3478 trace_multiwrite_cb(mcb, ret);
3479
3480 if (ret < 0 && !mcb->error) {
3481 mcb->error = ret;
3482 }
3483
3484 mcb->num_requests--;
3485 if (mcb->num_requests == 0) {
3486 multiwrite_user_cb(mcb);
3487 g_free(mcb);
3488 }
3489 }
3490
3491 static int multiwrite_req_compare(const void *a, const void *b)
3492 {
3493 const BlockRequest *req1 = a, *req2 = b;
3494
3495 /*
3496 * Note that we can't simply subtract req2->sector from req1->sector
3497 * here as that could overflow the return value.
3498 */
3499 if (req1->sector > req2->sector) {
3500 return 1;
3501 } else if (req1->sector < req2->sector) {
3502 return -1;
3503 } else {
3504 return 0;
3505 }
3506 }
3507
3508 /*
3509 * Takes a bunch of requests and tries to merge them. Returns the number of
3510 * requests that remain after merging.
3511 */
3512 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
3513 int num_reqs, MultiwriteCB *mcb)
3514 {
3515 int i, outidx;
3516
3517 // Sort requests by start sector
3518 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
3519
3520 // Check if adjacent requests touch the same clusters. If so, combine them,
3521 // filling up gaps with zero sectors.
3522 outidx = 0;
3523 for (i = 1; i < num_reqs; i++) {
3524 int merge = 0;
3525 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
3526
3527 // Handle exactly sequential writes and overlapping writes.
3528 if (reqs[i].sector <= oldreq_last) {
3529 merge = 1;
3530 }
3531
3532 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3533 merge = 0;
3534 }
3535
3536 if (merge) {
3537 size_t size;
3538 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
3539 qemu_iovec_init(qiov,
3540 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
3541
3542 // Add the first request to the merged one. If the requests are
3543 // overlapping, drop the last sectors of the first request.
3544 size = (reqs[i].sector - reqs[outidx].sector) << 9;
3545 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
3546
3547 // We should need to add any zeros between the two requests
3548 assert (reqs[i].sector <= oldreq_last);
3549
3550 // Add the second request
3551 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
3552
3553 reqs[outidx].nb_sectors = qiov->size >> 9;
3554 reqs[outidx].qiov = qiov;
3555
3556 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
3557 } else {
3558 outidx++;
3559 reqs[outidx].sector = reqs[i].sector;
3560 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
3561 reqs[outidx].qiov = reqs[i].qiov;
3562 }
3563 }
3564
3565 return outidx + 1;
3566 }
3567
3568 /*
3569 * Submit multiple AIO write requests at once.
3570 *
3571 * On success, the function returns 0 and all requests in the reqs array have
3572 * been submitted. In error case this function returns -1, and any of the
3573 * requests may or may not be submitted yet. In particular, this means that the
3574 * callback will be called for some of the requests, for others it won't. The
3575 * caller must check the error field of the BlockRequest to wait for the right
3576 * callbacks (if error != 0, no callback will be called).
3577 *
3578 * The implementation may modify the contents of the reqs array, e.g. to merge
3579 * requests. However, the fields opaque and error are left unmodified as they
3580 * are used to signal failure for a single request to the caller.
3581 */
3582 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
3583 {
3584 MultiwriteCB *mcb;
3585 int i;
3586
3587 /* don't submit writes if we don't have a medium */
3588 if (bs->drv == NULL) {
3589 for (i = 0; i < num_reqs; i++) {
3590 reqs[i].error = -ENOMEDIUM;
3591 }
3592 return -1;
3593 }
3594
3595 if (num_reqs == 0) {
3596 return 0;
3597 }
3598
3599 // Create MultiwriteCB structure
3600 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
3601 mcb->num_requests = 0;
3602 mcb->num_callbacks = num_reqs;
3603
3604 for (i = 0; i < num_reqs; i++) {
3605 mcb->callbacks[i].cb = reqs[i].cb;
3606 mcb->callbacks[i].opaque = reqs[i].opaque;
3607 }
3608
3609 // Check for mergable requests
3610 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
3611
3612 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
3613
3614 /* Run the aio requests. */
3615 mcb->num_requests = num_reqs;
3616 for (i = 0; i < num_reqs; i++) {
3617 bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
3618 reqs[i].nb_sectors, multiwrite_cb, mcb);
3619 }
3620
3621 return 0;
3622 }
3623
3624 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
3625 {
3626 acb->aiocb_info->cancel(acb);
3627 }
3628
3629 /* block I/O throttling */
3630 static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
3631 bool is_write, double elapsed_time, uint64_t *wait)
3632 {
3633 uint64_t bps_limit = 0;
3634 double bytes_limit, bytes_base, bytes_res;
3635 double slice_time, wait_time;
3636
3637 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
3638 bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3639 } else if (bs->io_limits.bps[is_write]) {
3640 bps_limit = bs->io_limits.bps[is_write];
3641 } else {
3642 if (wait) {
3643 *wait = 0;
3644 }
3645
3646 return false;
3647 }
3648
3649 slice_time = bs->slice_end - bs->slice_start;
3650 slice_time /= (NANOSECONDS_PER_SECOND);
3651 bytes_limit = bps_limit * slice_time;
3652 bytes_base = bs->nr_bytes[is_write] - bs->io_base.bytes[is_write];
3653 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
3654 bytes_base += bs->nr_bytes[!is_write] - bs->io_base.bytes[!is_write];
3655 }
3656
3657 /* bytes_base: the bytes of data which have been read/written; and
3658 * it is obtained from the history statistic info.
3659 * bytes_res: the remaining bytes of data which need to be read/written.
3660 * (bytes_base + bytes_res) / bps_limit: used to calcuate
3661 * the total time for completing reading/writting all data.
3662 */
3663 bytes_res = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
3664
3665 if (bytes_base + bytes_res <= bytes_limit) {
3666 if (wait) {
3667 *wait = 0;
3668 }
3669
3670 return false;
3671 }
3672
3673 /* Calc approx time to dispatch */
3674 wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
3675
3676 /* When the I/O rate at runtime exceeds the limits,
3677 * bs->slice_end need to be extended in order that the current statistic
3678 * info can be kept until the timer fire, so it is increased and tuned
3679 * based on the result of experiment.
3680 */
3681 bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
3682 bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
3683 if (wait) {
3684 *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
3685 }
3686
3687 return true;
3688 }
3689
3690 static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
3691 double elapsed_time, uint64_t *wait)
3692 {
3693 uint64_t iops_limit = 0;
3694 double ios_limit, ios_base;
3695 double slice_time, wait_time;
3696
3697 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
3698 iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3699 } else if (bs->io_limits.iops[is_write]) {
3700 iops_limit = bs->io_limits.iops[is_write];
3701 } else {
3702 if (wait) {
3703 *wait = 0;
3704 }
3705
3706 return false;
3707 }
3708
3709 slice_time = bs->slice_end - bs->slice_start;
3710 slice_time /= (NANOSECONDS_PER_SECOND);
3711 ios_limit = iops_limit * slice_time;
3712 ios_base = bs->nr_ops[is_write] - bs->io_base.ios[is_write];
3713 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
3714 ios_base += bs->nr_ops[!is_write] - bs->io_base.ios[!is_write];
3715 }
3716
3717 if (ios_base + 1 <= ios_limit) {
3718 if (wait) {
3719 *wait = 0;
3720 }
3721
3722 return false;
3723 }
3724
3725 /* Calc approx time to dispatch */
3726 wait_time = (ios_base + 1) / iops_limit;
3727 if (wait_time > elapsed_time) {
3728 wait_time = wait_time - elapsed_time;
3729 } else {
3730 wait_time = 0;
3731 }
3732
3733 bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
3734 bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
3735 if (wait) {
3736 *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
3737 }
3738
3739 return true;
3740 }
3741
3742 static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
3743 bool is_write, int64_t *wait)
3744 {
3745 int64_t now, max_wait;
3746 uint64_t bps_wait = 0, iops_wait = 0;
3747 double elapsed_time;
3748 int bps_ret, iops_ret;
3749
3750 now = qemu_get_clock_ns(vm_clock);
3751 if ((bs->slice_start < now)
3752 && (bs->slice_end > now)) {
3753 bs->slice_end = now + bs->slice_time;
3754 } else {
3755 bs->slice_time = 5 * BLOCK_IO_SLICE_TIME;
3756 bs->slice_start = now;
3757 bs->slice_end = now + bs->slice_time;
3758
3759 bs->io_base.bytes[is_write] = bs->nr_bytes[is_write];
3760 bs->io_base.bytes[!is_write] = bs->nr_bytes[!is_write];
3761
3762 bs->io_base.ios[is_write] = bs->nr_ops[is_write];
3763 bs->io_base.ios[!is_write] = bs->nr_ops[!is_write];
3764 }
3765
3766 elapsed_time = now - bs->slice_start;
3767 elapsed_time /= (NANOSECONDS_PER_SECOND);
3768
3769 bps_ret = bdrv_exceed_bps_limits(bs, nb_sectors,
3770 is_write, elapsed_time, &bps_wait);
3771 iops_ret = bdrv_exceed_iops_limits(bs, is_write,
3772 elapsed_time, &iops_wait);
3773 if (bps_ret || iops_ret) {
3774 max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
3775 if (wait) {
3776 *wait = max_wait;
3777 }
3778
3779 now = qemu_get_clock_ns(vm_clock);
3780 if (bs->slice_end < now + max_wait) {
3781 bs->slice_end = now + max_wait;
3782 }
3783
3784 return true;
3785 }
3786
3787 if (wait) {
3788 *wait = 0;
3789 }
3790
3791 return false;
3792 }
3793
3794 /**************************************************************/
3795 /* async block device emulation */
3796
3797 typedef struct BlockDriverAIOCBSync {
3798 BlockDriverAIOCB common;
3799 QEMUBH *bh;
3800 int ret;
3801 /* vector translation state */
3802 QEMUIOVector *qiov;
3803 uint8_t *bounce;
3804 int is_write;
3805 } BlockDriverAIOCBSync;
3806
3807 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3808 {
3809 BlockDriverAIOCBSync *acb =
3810 container_of(blockacb, BlockDriverAIOCBSync, common);
3811 qemu_bh_delete(acb->bh);
3812 acb->bh = NULL;
3813 qemu_aio_release(acb);
3814 }
3815
3816 static const AIOCBInfo bdrv_em_aiocb_info = {
3817 .aiocb_size = sizeof(BlockDriverAIOCBSync),
3818 .cancel = bdrv_aio_cancel_em,
3819 };
3820
3821 static void bdrv_aio_bh_cb(void *opaque)
3822 {
3823 BlockDriverAIOCBSync *acb = opaque;
3824
3825 if (!acb->is_write)
3826 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
3827 qemu_vfree(acb->bounce);
3828 acb->common.cb(acb->common.opaque, acb->ret);
3829 qemu_bh_delete(acb->bh);
3830 acb->bh = NULL;
3831 qemu_aio_release(acb);
3832 }
3833
3834 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3835 int64_t sector_num,
3836 QEMUIOVector *qiov,
3837 int nb_sectors,
3838 BlockDriverCompletionFunc *cb,
3839 void *opaque,
3840 int is_write)
3841
3842 {
3843 BlockDriverAIOCBSync *acb;
3844
3845 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
3846 acb->is_write = is_write;
3847 acb->qiov = qiov;
3848 acb->bounce = qemu_blockalign(bs, qiov->size);
3849 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3850
3851 if (is_write) {
3852 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
3853 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3854 } else {
3855 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3856 }
3857
3858 qemu_bh_schedule(acb->bh);
3859
3860 return &acb->common;
3861 }
3862
3863 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3864 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3865 BlockDriverCompletionFunc *cb, void *opaque)
3866 {
3867 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
3868 }
3869
3870 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3871 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3872 BlockDriverCompletionFunc *cb, void *opaque)
3873 {
3874 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3875 }
3876
3877
3878 typedef struct BlockDriverAIOCBCoroutine {
3879 BlockDriverAIOCB common;
3880 BlockRequest req;
3881 bool is_write;
3882 bool *done;
3883 QEMUBH* bh;
3884 } BlockDriverAIOCBCoroutine;
3885
3886 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
3887 {
3888 BlockDriverAIOCBCoroutine *acb =
3889 container_of(blockacb, BlockDriverAIOCBCoroutine, common);
3890 bool done = false;
3891
3892 acb->done = &done;
3893 while (!done) {
3894 qemu_aio_wait();
3895 }
3896 }
3897
3898 static const AIOCBInfo bdrv_em_co_aiocb_info = {
3899 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
3900 .cancel = bdrv_aio_co_cancel_em,
3901 };
3902
3903 static void bdrv_co_em_bh(void *opaque)
3904 {
3905 BlockDriverAIOCBCoroutine *acb = opaque;
3906
3907 acb->common.cb(acb->common.opaque, acb->req.error);
3908
3909 if (acb->done) {
3910 *acb->done = true;
3911 }
3912
3913 qemu_bh_delete(acb->bh);
3914 qemu_aio_release(acb);
3915 }
3916
3917 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3918 static void coroutine_fn bdrv_co_do_rw(void *opaque)
3919 {
3920 BlockDriverAIOCBCoroutine *acb = opaque;
3921 BlockDriverState *bs = acb->common.bs;
3922
3923 if (!acb->is_write) {
3924 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
3925 acb->req.nb_sectors, acb->req.qiov, 0);
3926 } else {
3927 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
3928 acb->req.nb_sectors, acb->req.qiov, 0);
3929 }
3930
3931 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3932 qemu_bh_schedule(acb->bh);
3933 }
3934
3935 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
3936 int64_t sector_num,
3937 QEMUIOVector *qiov,
3938 int nb_sectors,
3939 BlockDriverCompletionFunc *cb,
3940 void *opaque,
3941 bool is_write)
3942 {
3943 Coroutine *co;
3944 BlockDriverAIOCBCoroutine *acb;
3945
3946 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
3947 acb->req.sector = sector_num;
3948 acb->req.nb_sectors = nb_sectors;
3949 acb->req.qiov = qiov;
3950 acb->is_write = is_write;
3951 acb->done = NULL;
3952
3953 co = qemu_coroutine_create(bdrv_co_do_rw);
3954 qemu_coroutine_enter(co, acb);
3955
3956 return &acb->common;
3957 }
3958
3959 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
3960 {
3961 BlockDriverAIOCBCoroutine *acb = opaque;
3962 BlockDriverState *bs = acb->common.bs;
3963
3964 acb->req.error = bdrv_co_flush(bs);
3965 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3966 qemu_bh_schedule(acb->bh);
3967 }
3968
3969 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
3970 BlockDriverCompletionFunc *cb, void *opaque)
3971 {
3972 trace_bdrv_aio_flush(bs, opaque);
3973
3974 Coroutine *co;
3975 BlockDriverAIOCBCoroutine *acb;
3976
3977 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
3978 acb->done = NULL;
3979
3980 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
3981 qemu_coroutine_enter(co, acb);
3982
3983 return &acb->common;
3984 }
3985
3986 static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
3987 {
3988 BlockDriverAIOCBCoroutine *acb = opaque;
3989 BlockDriverState *bs = acb->common.bs;
3990
3991 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
3992 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3993 qemu_bh_schedule(acb->bh);
3994 }
3995
3996 BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
3997 int64_t sector_num, int nb_sectors,
3998 BlockDriverCompletionFunc *cb, void *opaque)
3999 {
4000 Coroutine *co;
4001 BlockDriverAIOCBCoroutine *acb;
4002
4003 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
4004
4005 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4006 acb->req.sector = sector_num;
4007 acb->req.nb_sectors = nb_sectors;
4008 acb->done = NULL;
4009 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
4010 qemu_coroutine_enter(co, acb);
4011
4012 return &acb->common;
4013 }
4014
4015 void bdrv_init(void)
4016 {
4017 module_call_init(MODULE_INIT_BLOCK);
4018 }
4019
4020 void bdrv_init_with_whitelist(void)
4021 {
4022 use_bdrv_whitelist = 1;
4023 bdrv_init();
4024 }
4025
4026 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
4027 BlockDriverCompletionFunc *cb, void *opaque)
4028 {
4029 BlockDriverAIOCB *acb;
4030
4031 acb = g_slice_alloc(aiocb_info->aiocb_size);
4032 acb->aiocb_info = aiocb_info;
4033 acb->bs = bs;
4034 acb->cb = cb;
4035 acb->opaque = opaque;
4036 return acb;
4037 }
4038
4039 void qemu_aio_release(void *p)
4040 {
4041 BlockDriverAIOCB *acb = p;
4042 g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4043 }
4044
4045 /**************************************************************/
4046 /* Coroutine block device emulation */
4047
4048 typedef struct CoroutineIOCompletion {
4049 Coroutine *coroutine;
4050 int ret;
4051 } CoroutineIOCompletion;
4052
4053 static void bdrv_co_io_em_complete(void *opaque, int ret)
4054 {
4055 CoroutineIOCompletion *co = opaque;
4056
4057 co->ret = ret;
4058 qemu_coroutine_enter(co->coroutine, NULL);
4059 }
4060
4061 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4062 int nb_sectors, QEMUIOVector *iov,
4063 bool is_write)
4064 {
4065 CoroutineIOCompletion co = {
4066 .coroutine = qemu_coroutine_self(),
4067 };
4068 BlockDriverAIOCB *acb;
4069
4070 if (is_write) {
4071 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4072 bdrv_co_io_em_complete, &co);
4073 } else {
4074 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4075 bdrv_co_io_em_complete, &co);
4076 }
4077
4078 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4079 if (!acb) {
4080 return -EIO;
4081 }
4082 qemu_coroutine_yield();
4083
4084 return co.ret;
4085 }
4086
4087 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4088 int64_t sector_num, int nb_sectors,
4089 QEMUIOVector *iov)
4090 {
4091 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4092 }
4093
4094 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4095 int64_t sector_num, int nb_sectors,
4096 QEMUIOVector *iov)
4097 {
4098 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4099 }
4100
4101 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4102 {
4103 RwCo *rwco = opaque;
4104
4105 rwco->ret = bdrv_co_flush(rwco->bs);
4106 }
4107
4108 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
4109 {
4110 int ret;
4111
4112 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
4113 return 0;
4114 }
4115
4116 /* Write back cached data to the OS even with cache=unsafe */
4117 if (bs->drv->bdrv_co_flush_to_os) {
4118 ret = bs->drv->bdrv_co_flush_to_os(bs);
4119 if (ret < 0) {
4120 return ret;
4121 }
4122 }
4123
4124 /* But don't actually force it to the disk with cache=unsafe */
4125 if (bs->open_flags & BDRV_O_NO_FLUSH) {
4126 goto flush_parent;
4127 }
4128
4129 if (bs->drv->bdrv_co_flush_to_disk) {
4130 ret = bs->drv->bdrv_co_flush_to_disk(bs);
4131 } else if (bs->drv->bdrv_aio_flush) {
4132 BlockDriverAIOCB *acb;
4133 CoroutineIOCompletion co = {
4134 .coroutine = qemu_coroutine_self(),
4135 };
4136
4137 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
4138 if (acb == NULL) {
4139 ret = -EIO;
4140 } else {
4141 qemu_coroutine_yield();
4142 ret = co.ret;
4143 }
4144 } else {
4145 /*
4146 * Some block drivers always operate in either writethrough or unsafe
4147 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
4148 * know how the server works (because the behaviour is hardcoded or
4149 * depends on server-side configuration), so we can't ensure that
4150 * everything is safe on disk. Returning an error doesn't work because
4151 * that would break guests even if the server operates in writethrough
4152 * mode.
4153 *
4154 * Let's hope the user knows what he's doing.
4155 */
4156 ret = 0;
4157 }
4158 if (ret < 0) {
4159 return ret;
4160 }
4161
4162 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
4163 * in the case of cache=unsafe, so there are no useless flushes.
4164 */
4165 flush_parent:
4166 return bdrv_co_flush(bs->file);
4167 }
4168
4169 void bdrv_invalidate_cache(BlockDriverState *bs)
4170 {
4171 if (bs->drv && bs->drv->bdrv_invalidate_cache) {
4172 bs->drv->bdrv_invalidate_cache(bs);
4173 }
4174 }
4175
4176 void bdrv_invalidate_cache_all(void)
4177 {
4178 BlockDriverState *bs;
4179
4180 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4181 bdrv_invalidate_cache(bs);
4182 }
4183 }
4184
4185 void bdrv_clear_incoming_migration_all(void)
4186 {
4187 BlockDriverState *bs;
4188
4189 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4190 bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
4191 }
4192 }
4193
4194 int bdrv_flush(BlockDriverState *bs)
4195 {
4196 Coroutine *co;
4197 RwCo rwco = {
4198 .bs = bs,
4199 .ret = NOT_DONE,
4200 };
4201
4202 if (qemu_in_coroutine()) {
4203 /* Fast-path if already in coroutine context */
4204 bdrv_flush_co_entry(&rwco);
4205 } else {
4206 co = qemu_coroutine_create(bdrv_flush_co_entry);
4207 qemu_coroutine_enter(co, &rwco);
4208 while (rwco.ret == NOT_DONE) {
4209 qemu_aio_wait();
4210 }
4211 }
4212
4213 return rwco.ret;
4214 }
4215
4216 static void coroutine_fn bdrv_discard_co_entry(void *opaque)
4217 {
4218 RwCo *rwco = opaque;
4219
4220 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
4221 }
4222
4223 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
4224 int nb_sectors)
4225 {
4226 if (!bs->drv) {
4227 return -ENOMEDIUM;
4228 } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
4229 return -EIO;
4230 } else if (bs->read_only) {
4231 return -EROFS;
4232 }
4233
4234 if (bs->dirty_bitmap) {
4235 bdrv_reset_dirty(bs, sector_num, nb_sectors);
4236 }
4237
4238 /* Do nothing if disabled. */
4239 if (!(bs->open_flags & BDRV_O_UNMAP)) {
4240 return 0;
4241 }
4242
4243 if (bs->drv->bdrv_co_discard) {
4244 return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
4245 } else if (bs->drv->bdrv_aio_discard) {
4246 BlockDriverAIOCB *acb;
4247 CoroutineIOCompletion co = {
4248 .coroutine = qemu_coroutine_self(),
4249 };
4250
4251 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
4252 bdrv_co_io_em_complete, &co);
4253 if (acb == NULL) {
4254 return -EIO;
4255 } else {
4256 qemu_coroutine_yield();
4257 return co.ret;
4258 }
4259 } else {
4260 return 0;
4261 }
4262 }
4263
4264 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
4265 {
4266 Coroutine *co;
4267 RwCo rwco = {
4268 .bs = bs,
4269 .sector_num = sector_num,
4270 .nb_sectors = nb_sectors,
4271 .ret = NOT_DONE,
4272 };
4273
4274 if (qemu_in_coroutine()) {
4275 /* Fast-path if already in coroutine context */
4276 bdrv_discard_co_entry(&rwco);
4277 } else {
4278 co = qemu_coroutine_create(bdrv_discard_co_entry);
4279 qemu_coroutine_enter(co, &rwco);
4280 while (rwco.ret == NOT_DONE) {
4281 qemu_aio_wait();
4282 }
4283 }
4284
4285 return rwco.ret;
4286 }
4287
4288 /**************************************************************/
4289 /* removable device support */
4290
4291 /**
4292 * Return TRUE if the media is present
4293 */
4294 int bdrv_is_inserted(BlockDriverState *bs)
4295 {
4296 BlockDriver *drv = bs->drv;
4297
4298 if (!drv)
4299 return 0;
4300 if (!drv->bdrv_is_inserted)
4301 return 1;
4302 return drv->bdrv_is_inserted(bs);
4303 }
4304
4305 /**
4306 * Return whether the media changed since the last call to this
4307 * function, or -ENOTSUP if we don't know. Most drivers don't know.
4308 */
4309 int bdrv_media_changed(BlockDriverState *bs)
4310 {
4311 BlockDriver *drv = bs->drv;
4312
4313 if (drv && drv->bdrv_media_changed) {
4314 return drv->bdrv_media_changed(bs);
4315 }
4316 return -ENOTSUP;
4317 }
4318
4319 /**
4320 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4321 */
4322 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
4323 {
4324 BlockDriver *drv = bs->drv;
4325
4326 if (drv && drv->bdrv_eject) {
4327 drv->bdrv_eject(bs, eject_flag);
4328 }
4329
4330 if (bs->device_name[0] != '\0') {
4331 bdrv_emit_qmp_eject_event(bs, eject_flag);
4332 }
4333 }
4334
4335 /**
4336 * Lock or unlock the media (if it is locked, the user won't be able
4337 * to eject it manually).
4338 */
4339 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
4340 {
4341 BlockDriver *drv = bs->drv;
4342
4343 trace_bdrv_lock_medium(bs, locked);
4344
4345 if (drv && drv->bdrv_lock_medium) {
4346 drv->bdrv_lock_medium(bs, locked);
4347 }
4348 }
4349
4350 /* needed for generic scsi interface */
4351
4352 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4353 {
4354 BlockDriver *drv = bs->drv;
4355
4356 if (drv && drv->bdrv_ioctl)
4357 return drv->bdrv_ioctl(bs, req, buf);
4358 return -ENOTSUP;
4359 }
4360
4361 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4362 unsigned long int req, void *buf,
4363 BlockDriverCompletionFunc *cb, void *opaque)
4364 {
4365 BlockDriver *drv = bs->drv;
4366
4367 if (drv && drv->bdrv_aio_ioctl)
4368 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4369 return NULL;
4370 }
4371
4372 void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
4373 {
4374 bs->buffer_alignment = align;
4375 }
4376
4377 void *qemu_blockalign(BlockDriverState *bs, size_t size)
4378 {
4379 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4380 }
4381
4382 /*
4383 * Check if all memory in this vector is sector aligned.
4384 */
4385 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4386 {
4387 int i;
4388
4389 for (i = 0; i < qiov->niov; i++) {
4390 if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4391 return false;
4392 }
4393 }
4394
4395 return true;
4396 }
4397
4398 void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
4399 {
4400 int64_t bitmap_size;
4401
4402 assert((granularity & (granularity - 1)) == 0);
4403
4404 if (granularity) {
4405 granularity >>= BDRV_SECTOR_BITS;
4406 assert(!bs->dirty_bitmap);
4407 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
4408 bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
4409 } else {
4410 if (bs->dirty_bitmap) {
4411 hbitmap_free(bs->dirty_bitmap);
4412 bs->dirty_bitmap = NULL;
4413 }
4414 }
4415 }
4416
4417 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
4418 {
4419 if (bs->dirty_bitmap) {
4420 return hbitmap_get(bs->dirty_bitmap, sector);
4421 } else {
4422 return 0;
4423 }
4424 }
4425
4426 void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
4427 {
4428 hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
4429 }
4430
4431 void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
4432 int nr_sectors)
4433 {
4434 hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
4435 }
4436
4437 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
4438 int nr_sectors)
4439 {
4440 hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
4441 }
4442
4443 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4444 {
4445 if (bs->dirty_bitmap) {
4446 return hbitmap_count(bs->dirty_bitmap);
4447 } else {
4448 return 0;
4449 }
4450 }
4451
4452 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4453 {
4454 assert(bs->in_use != in_use);
4455 bs->in_use = in_use;
4456 }
4457
4458 int bdrv_in_use(BlockDriverState *bs)
4459 {
4460 return bs->in_use;
4461 }
4462
4463 void bdrv_iostatus_enable(BlockDriverState *bs)
4464 {
4465 bs->iostatus_enabled = true;
4466 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
4467 }
4468
4469 /* The I/O status is only enabled if the drive explicitly
4470 * enables it _and_ the VM is configured to stop on errors */
4471 bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
4472 {
4473 return (bs->iostatus_enabled &&
4474 (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
4475 bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
4476 bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
4477 }
4478
4479 void bdrv_iostatus_disable(BlockDriverState *bs)
4480 {
4481 bs->iostatus_enabled = false;
4482 }
4483
4484 void bdrv_iostatus_reset(BlockDriverState *bs)
4485 {
4486 if (bdrv_iostatus_is_enabled(bs)) {
4487 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
4488 if (bs->job) {
4489 block_job_iostatus_reset(bs->job);
4490 }
4491 }
4492 }
4493
4494 void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
4495 {
4496 assert(bdrv_iostatus_is_enabled(bs));
4497 if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
4498 bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
4499 BLOCK_DEVICE_IO_STATUS_FAILED;
4500 }
4501 }
4502
4503 void
4504 bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4505 enum BlockAcctType type)
4506 {
4507 assert(type < BDRV_MAX_IOTYPE);
4508
4509 cookie->bytes = bytes;
4510 cookie->start_time_ns = get_clock();
4511 cookie->type = type;
4512 }
4513
4514 void
4515 bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4516 {
4517 assert(cookie->type < BDRV_MAX_IOTYPE);
4518
4519 bs->nr_bytes[cookie->type] += cookie->bytes;
4520 bs->nr_ops[cookie->type]++;
4521 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4522 }
4523
4524 void bdrv_img_create(const char *filename, const char *fmt,
4525 const char *base_filename, const char *base_fmt,
4526 char *options, uint64_t img_size, int flags,
4527 Error **errp, bool quiet)
4528 {
4529 QEMUOptionParameter *param = NULL, *create_options = NULL;
4530 QEMUOptionParameter *backing_fmt, *backing_file, *size;
4531 BlockDriverState *bs = NULL;
4532 BlockDriver *drv, *proto_drv;
4533 BlockDriver *backing_drv = NULL;
4534 int ret = 0;
4535
4536 /* Find driver and parse its options */
4537 drv = bdrv_find_format(fmt);
4538 if (!drv) {
4539 error_setg(errp, "Unknown file format '%s'", fmt);
4540 return;
4541 }
4542
4543 proto_drv = bdrv_find_protocol(filename);
4544 if (!proto_drv) {
4545 error_setg(errp, "Unknown protocol '%s'", filename);
4546 return;
4547 }
4548
4549 create_options = append_option_parameters(create_options,
4550 drv->create_options);
4551 create_options = append_option_parameters(create_options,
4552 proto_drv->create_options);
4553
4554 /* Create parameter list with default values */
4555 param = parse_option_parameters("", create_options, param);
4556
4557 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4558
4559 /* Parse -o options */
4560 if (options) {
4561 param = parse_option_parameters(options, create_options, param);
4562 if (param == NULL) {
4563 error_setg(errp, "Invalid options for file format '%s'.", fmt);
4564 goto out;
4565 }
4566 }
4567
4568 if (base_filename) {
4569 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4570 base_filename)) {
4571 error_setg(errp, "Backing file not supported for file format '%s'",
4572 fmt);
4573 goto out;
4574 }
4575 }
4576
4577 if (base_fmt) {
4578 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
4579 error_setg(errp, "Backing file format not supported for file "
4580 "format '%s'", fmt);
4581 goto out;
4582 }
4583 }
4584
4585 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4586 if (backing_file && backing_file->value.s) {
4587 if (!strcmp(filename, backing_file->value.s)) {
4588 error_setg(errp, "Error: Trying to create an image with the "
4589 "same filename as the backing file");
4590 goto out;
4591 }
4592 }
4593
4594 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4595 if (backing_fmt && backing_fmt->value.s) {
4596 backing_drv = bdrv_find_format(backing_fmt->value.s);
4597 if (!backing_drv) {
4598 error_setg(errp, "Unknown backing file format '%s'",
4599 backing_fmt->value.s);
4600 goto out;
4601 }
4602 }
4603
4604 // The size for the image must always be specified, with one exception:
4605 // If we are using a backing file, we can obtain the size from there
4606 size = get_option_parameter(param, BLOCK_OPT_SIZE);
4607 if (size && size->value.n == -1) {
4608 if (backing_file && backing_file->value.s) {
4609 uint64_t size;
4610 char buf[32];
4611 int back_flags;
4612
4613 /* backing files always opened read-only */
4614 back_flags =
4615 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4616
4617 bs = bdrv_new("");
4618
4619 ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4620 backing_drv);
4621 if (ret < 0) {
4622 error_setg_errno(errp, -ret, "Could not open '%s'",
4623 backing_file->value.s);
4624 goto out;
4625 }
4626 bdrv_get_geometry(bs, &size);
4627 size *= 512;
4628
4629 snprintf(buf, sizeof(buf), "%" PRId64, size);
4630 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4631 } else {
4632 error_setg(errp, "Image creation needs a size parameter");
4633 goto out;
4634 }
4635 }
4636
4637 if (!quiet) {
4638 printf("Formatting '%s', fmt=%s ", filename, fmt);
4639 print_option_parameters(param);
4640 puts("");
4641 }
4642 ret = bdrv_create(drv, filename, param);
4643 if (ret < 0) {
4644 if (ret == -ENOTSUP) {
4645 error_setg(errp,"Formatting or formatting option not supported for "
4646 "file format '%s'", fmt);
4647 } else if (ret == -EFBIG) {
4648 error_setg(errp, "The image size is too large for file format '%s'",
4649 fmt);
4650 } else {
4651 error_setg(errp, "%s: error while creating %s: %s", filename, fmt,
4652 strerror(-ret));
4653 }
4654 }
4655
4656 out:
4657 free_option_parameters(create_options);
4658 free_option_parameters(param);
4659
4660 if (bs) {
4661 bdrv_delete(bs);
4662 }
4663 }