2 * QEMU Enhanced Disk Format
4 * Copyright IBM, Corp. 2010
10 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
11 * See the COPYING.LIB file in the top-level directory.
15 #include "qemu/osdep.h"
16 #include "qapi/error.h"
17 #include "qemu/timer.h"
18 #include "qemu/bswap.h"
21 #include "sysemu/block-backend.h"
23 static int bdrv_qed_probe(const uint8_t *buf, int buf_size,
26 const QEDHeader *header = (const QEDHeader *)buf;
28 if (buf_size < sizeof(*header)) {
31 if (le32_to_cpu(header->magic) != QED_MAGIC) {
38 * Check whether an image format is raw
40 * @fmt: Backing file format, may be NULL
42 static bool qed_fmt_is_raw(const char *fmt)
44 return fmt && strcmp(fmt, "raw") == 0;
47 static void qed_header_le_to_cpu(const QEDHeader *le, QEDHeader *cpu)
49 cpu->magic = le32_to_cpu(le->magic);
50 cpu->cluster_size = le32_to_cpu(le->cluster_size);
51 cpu->table_size = le32_to_cpu(le->table_size);
52 cpu->header_size = le32_to_cpu(le->header_size);
53 cpu->features = le64_to_cpu(le->features);
54 cpu->compat_features = le64_to_cpu(le->compat_features);
55 cpu->autoclear_features = le64_to_cpu(le->autoclear_features);
56 cpu->l1_table_offset = le64_to_cpu(le->l1_table_offset);
57 cpu->image_size = le64_to_cpu(le->image_size);
58 cpu->backing_filename_offset = le32_to_cpu(le->backing_filename_offset);
59 cpu->backing_filename_size = le32_to_cpu(le->backing_filename_size);
62 static void qed_header_cpu_to_le(const QEDHeader *cpu, QEDHeader *le)
64 le->magic = cpu_to_le32(cpu->magic);
65 le->cluster_size = cpu_to_le32(cpu->cluster_size);
66 le->table_size = cpu_to_le32(cpu->table_size);
67 le->header_size = cpu_to_le32(cpu->header_size);
68 le->features = cpu_to_le64(cpu->features);
69 le->compat_features = cpu_to_le64(cpu->compat_features);
70 le->autoclear_features = cpu_to_le64(cpu->autoclear_features);
71 le->l1_table_offset = cpu_to_le64(cpu->l1_table_offset);
72 le->image_size = cpu_to_le64(cpu->image_size);
73 le->backing_filename_offset = cpu_to_le32(cpu->backing_filename_offset);
74 le->backing_filename_size = cpu_to_le32(cpu->backing_filename_size);
77 int qed_write_header_sync(BDRVQEDState *s)
82 qed_header_cpu_to_le(&s->header, &le);
83 ret = bdrv_pwrite(s->bs->file, 0, &le, sizeof(le));
84 if (ret != sizeof(le)) {
91 * Update header in-place (does not rewrite backing filename or other strings)
93 * This function only updates known header fields in-place and does not affect
94 * extra data after the QED header.
96 * No new allocating reqs can start while this function runs.
98 static int coroutine_fn qed_write_header(BDRVQEDState *s)
100 /* We must write full sectors for O_DIRECT but cannot necessarily generate
101 * the data following the header if an unrecognized compat feature is
102 * active. Therefore, first read the sectors containing the header, update
103 * them, and write back.
106 int nsectors = DIV_ROUND_UP(sizeof(QEDHeader), BDRV_SECTOR_SIZE);
107 size_t len = nsectors * BDRV_SECTOR_SIZE;
113 assert(s->allocating_acb || s->allocating_write_reqs_plugged);
115 buf = qemu_blockalign(s->bs, len);
116 iov = (struct iovec) {
120 qemu_iovec_init_external(&qiov, &iov, 1);
122 ret = bdrv_co_preadv(s->bs->file, 0, qiov.size, &qiov, 0);
128 qed_header_cpu_to_le(&s->header, (QEDHeader *) buf);
130 ret = bdrv_co_pwritev(s->bs->file, 0, qiov.size, &qiov, 0);
141 static uint64_t qed_max_image_size(uint32_t cluster_size, uint32_t table_size)
143 uint64_t table_entries;
146 table_entries = (table_size * cluster_size) / sizeof(uint64_t);
147 l2_size = table_entries * cluster_size;
149 return l2_size * table_entries;
152 static bool qed_is_cluster_size_valid(uint32_t cluster_size)
154 if (cluster_size < QED_MIN_CLUSTER_SIZE ||
155 cluster_size > QED_MAX_CLUSTER_SIZE) {
158 if (cluster_size & (cluster_size - 1)) {
159 return false; /* not power of 2 */
164 static bool qed_is_table_size_valid(uint32_t table_size)
166 if (table_size < QED_MIN_TABLE_SIZE ||
167 table_size > QED_MAX_TABLE_SIZE) {
170 if (table_size & (table_size - 1)) {
171 return false; /* not power of 2 */
176 static bool qed_is_image_size_valid(uint64_t image_size, uint32_t cluster_size,
179 if (image_size % BDRV_SECTOR_SIZE != 0) {
180 return false; /* not multiple of sector size */
182 if (image_size > qed_max_image_size(cluster_size, table_size)) {
183 return false; /* image is too large */
189 * Read a string of known length from the image file
192 * @offset: File offset to start of string, in bytes
193 * @n: String length in bytes
194 * @buf: Destination buffer
195 * @buflen: Destination buffer length in bytes
196 * @ret: 0 on success, -errno on failure
198 * The string is NUL-terminated.
200 static int qed_read_string(BdrvChild *file, uint64_t offset, size_t n,
201 char *buf, size_t buflen)
207 ret = bdrv_pread(file, offset, buf, n);
216 * Allocate new clusters
219 * @n: Number of contiguous clusters to allocate
220 * @ret: Offset of first allocated cluster
222 * This function only produces the offset where the new clusters should be
223 * written. It updates BDRVQEDState but does not make any changes to the image
226 * Called with table_lock held.
228 static uint64_t qed_alloc_clusters(BDRVQEDState *s, unsigned int n)
230 uint64_t offset = s->file_size;
231 s->file_size += n * s->header.cluster_size;
235 QEDTable *qed_alloc_table(BDRVQEDState *s)
237 /* Honor O_DIRECT memory alignment requirements */
238 return qemu_blockalign(s->bs,
239 s->header.cluster_size * s->header.table_size);
243 * Allocate a new zeroed L2 table
245 * Called with table_lock held.
247 static CachedL2Table *qed_new_l2_table(BDRVQEDState *s)
249 CachedL2Table *l2_table = qed_alloc_l2_cache_entry(&s->l2_cache);
251 l2_table->table = qed_alloc_table(s);
252 l2_table->offset = qed_alloc_clusters(s, s->header.table_size);
254 memset(l2_table->table->offsets, 0,
255 s->header.cluster_size * s->header.table_size);
259 static bool qed_plug_allocating_write_reqs(BDRVQEDState *s)
261 qemu_co_mutex_lock(&s->table_lock);
263 /* No reentrancy is allowed. */
264 assert(!s->allocating_write_reqs_plugged);
265 if (s->allocating_acb != NULL) {
266 /* Another allocating write came concurrently. This cannot happen
267 * from bdrv_qed_co_drain_begin, but it can happen when the timer runs.
269 qemu_co_mutex_unlock(&s->table_lock);
273 s->allocating_write_reqs_plugged = true;
274 qemu_co_mutex_unlock(&s->table_lock);
278 static void qed_unplug_allocating_write_reqs(BDRVQEDState *s)
280 qemu_co_mutex_lock(&s->table_lock);
281 assert(s->allocating_write_reqs_plugged);
282 s->allocating_write_reqs_plugged = false;
283 qemu_co_queue_next(&s->allocating_write_reqs);
284 qemu_co_mutex_unlock(&s->table_lock);
287 static void coroutine_fn qed_need_check_timer_entry(void *opaque)
289 BDRVQEDState *s = opaque;
292 trace_qed_need_check_timer_cb(s);
294 if (!qed_plug_allocating_write_reqs(s)) {
298 /* Ensure writes are on disk before clearing flag */
299 ret = bdrv_co_flush(s->bs->file->bs);
301 qed_unplug_allocating_write_reqs(s);
305 s->header.features &= ~QED_F_NEED_CHECK;
306 ret = qed_write_header(s);
309 qed_unplug_allocating_write_reqs(s);
311 ret = bdrv_co_flush(s->bs);
315 static void qed_need_check_timer_cb(void *opaque)
317 Coroutine *co = qemu_coroutine_create(qed_need_check_timer_entry, opaque);
318 qemu_coroutine_enter(co);
321 static void qed_start_need_check_timer(BDRVQEDState *s)
323 trace_qed_start_need_check_timer(s);
325 /* Use QEMU_CLOCK_VIRTUAL so we don't alter the image file while suspended for
328 timer_mod(s->need_check_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
329 NANOSECONDS_PER_SECOND * QED_NEED_CHECK_TIMEOUT);
332 /* It's okay to call this multiple times or when no timer is started */
333 static void qed_cancel_need_check_timer(BDRVQEDState *s)
335 trace_qed_cancel_need_check_timer(s);
336 timer_del(s->need_check_timer);
339 static void bdrv_qed_detach_aio_context(BlockDriverState *bs)
341 BDRVQEDState *s = bs->opaque;
343 qed_cancel_need_check_timer(s);
344 timer_free(s->need_check_timer);
347 static void bdrv_qed_attach_aio_context(BlockDriverState *bs,
348 AioContext *new_context)
350 BDRVQEDState *s = bs->opaque;
352 s->need_check_timer = aio_timer_new(new_context,
353 QEMU_CLOCK_VIRTUAL, SCALE_NS,
354 qed_need_check_timer_cb, s);
355 if (s->header.features & QED_F_NEED_CHECK) {
356 qed_start_need_check_timer(s);
360 static void coroutine_fn bdrv_qed_co_drain_begin(BlockDriverState *bs)
362 BDRVQEDState *s = bs->opaque;
364 /* Fire the timer immediately in order to start doing I/O as soon as the
367 if (s->need_check_timer && timer_pending(s->need_check_timer)) {
368 qed_cancel_need_check_timer(s);
369 qed_need_check_timer_entry(s);
373 static void bdrv_qed_init_state(BlockDriverState *bs)
375 BDRVQEDState *s = bs->opaque;
377 memset(s, 0, sizeof(BDRVQEDState));
379 qemu_co_mutex_init(&s->table_lock);
380 qemu_co_queue_init(&s->allocating_write_reqs);
383 static int bdrv_qed_do_open(BlockDriverState *bs, QDict *options, int flags,
386 BDRVQEDState *s = bs->opaque;
391 ret = bdrv_pread(bs->file, 0, &le_header, sizeof(le_header));
395 qed_header_le_to_cpu(&le_header, &s->header);
397 if (s->header.magic != QED_MAGIC) {
398 error_setg(errp, "Image not in QED format");
401 if (s->header.features & ~QED_FEATURE_MASK) {
402 /* image uses unsupported feature bits */
403 error_setg(errp, "Unsupported QED features: %" PRIx64,
404 s->header.features & ~QED_FEATURE_MASK);
407 if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
411 /* Round down file size to the last cluster */
412 file_size = bdrv_getlength(bs->file->bs);
416 s->file_size = qed_start_of_cluster(s, file_size);
418 if (!qed_is_table_size_valid(s->header.table_size)) {
421 if (!qed_is_image_size_valid(s->header.image_size,
422 s->header.cluster_size,
423 s->header.table_size)) {
426 if (!qed_check_table_offset(s, s->header.l1_table_offset)) {
430 s->table_nelems = (s->header.cluster_size * s->header.table_size) /
432 s->l2_shift = ctz32(s->header.cluster_size);
433 s->l2_mask = s->table_nelems - 1;
434 s->l1_shift = s->l2_shift + ctz32(s->table_nelems);
436 /* Header size calculation must not overflow uint32_t */
437 if (s->header.header_size > UINT32_MAX / s->header.cluster_size) {
441 if ((s->header.features & QED_F_BACKING_FILE)) {
442 if ((uint64_t)s->header.backing_filename_offset +
443 s->header.backing_filename_size >
444 s->header.cluster_size * s->header.header_size) {
448 ret = qed_read_string(bs->file, s->header.backing_filename_offset,
449 s->header.backing_filename_size, bs->backing_file,
450 sizeof(bs->backing_file));
455 if (s->header.features & QED_F_BACKING_FORMAT_NO_PROBE) {
456 pstrcpy(bs->backing_format, sizeof(bs->backing_format), "raw");
460 /* Reset unknown autoclear feature bits. This is a backwards
461 * compatibility mechanism that allows images to be opened by older
462 * programs, which "knock out" unknown feature bits. When an image is
463 * opened by a newer program again it can detect that the autoclear
464 * feature is no longer valid.
466 if ((s->header.autoclear_features & ~QED_AUTOCLEAR_FEATURE_MASK) != 0 &&
467 !bdrv_is_read_only(bs->file->bs) && !(flags & BDRV_O_INACTIVE)) {
468 s->header.autoclear_features &= QED_AUTOCLEAR_FEATURE_MASK;
470 ret = qed_write_header_sync(s);
475 /* From here on only known autoclear feature bits are valid */
476 bdrv_flush(bs->file->bs);
479 s->l1_table = qed_alloc_table(s);
480 qed_init_l2_cache(&s->l2_cache);
482 ret = qed_read_l1_table_sync(s);
487 /* If image was not closed cleanly, check consistency */
488 if (!(flags & BDRV_O_CHECK) && (s->header.features & QED_F_NEED_CHECK)) {
489 /* Read-only images cannot be fixed. There is no risk of corruption
490 * since write operations are not possible. Therefore, allow
491 * potentially inconsistent images to be opened read-only. This can
492 * aid data recovery from an otherwise inconsistent image.
494 if (!bdrv_is_read_only(bs->file->bs) &&
495 !(flags & BDRV_O_INACTIVE)) {
496 BdrvCheckResult result = {0};
498 ret = qed_check(s, &result, true);
505 bdrv_qed_attach_aio_context(bs, bdrv_get_aio_context(bs));
509 qed_free_l2_cache(&s->l2_cache);
510 qemu_vfree(s->l1_table);
515 static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
518 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
524 bdrv_qed_init_state(bs);
525 return bdrv_qed_do_open(bs, options, flags, errp);
528 static void bdrv_qed_refresh_limits(BlockDriverState *bs, Error **errp)
530 BDRVQEDState *s = bs->opaque;
532 bs->bl.pwrite_zeroes_alignment = s->header.cluster_size;
535 /* We have nothing to do for QED reopen, stubs just return
537 static int bdrv_qed_reopen_prepare(BDRVReopenState *state,
538 BlockReopenQueue *queue, Error **errp)
543 static void bdrv_qed_close(BlockDriverState *bs)
545 BDRVQEDState *s = bs->opaque;
547 bdrv_qed_detach_aio_context(bs);
549 /* Ensure writes reach stable storage */
550 bdrv_flush(bs->file->bs);
552 /* Clean shutdown, no check required on next open */
553 if (s->header.features & QED_F_NEED_CHECK) {
554 s->header.features &= ~QED_F_NEED_CHECK;
555 qed_write_header_sync(s);
558 qed_free_l2_cache(&s->l2_cache);
559 qemu_vfree(s->l1_table);
562 static int qed_create(const char *filename, uint32_t cluster_size,
563 uint64_t image_size, uint32_t table_size,
564 const char *backing_file, const char *backing_fmt,
565 QemuOpts *opts, Error **errp)
569 .cluster_size = cluster_size,
570 .table_size = table_size,
573 .compat_features = 0,
574 .l1_table_offset = cluster_size,
575 .image_size = image_size,
578 uint8_t *l1_table = NULL;
579 size_t l1_size = header.cluster_size * header.table_size;
580 Error *local_err = NULL;
584 ret = bdrv_create_file(filename, opts, &local_err);
586 error_propagate(errp, local_err);
590 blk = blk_new_open(filename, NULL, NULL,
591 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
594 error_propagate(errp, local_err);
598 blk_set_allow_write_beyond_eof(blk, true);
600 /* File must start empty and grow, check truncate is supported */
601 ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
607 header.features |= QED_F_BACKING_FILE;
608 header.backing_filename_offset = sizeof(le_header);
609 header.backing_filename_size = strlen(backing_file);
611 if (qed_fmt_is_raw(backing_fmt)) {
612 header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
616 qed_header_cpu_to_le(&header, &le_header);
617 ret = blk_pwrite(blk, 0, &le_header, sizeof(le_header), 0);
621 ret = blk_pwrite(blk, sizeof(le_header), backing_file,
622 header.backing_filename_size, 0);
627 l1_table = g_malloc0(l1_size);
628 ret = blk_pwrite(blk, header.l1_table_offset, l1_table, l1_size, 0);
633 ret = 0; /* success */
640 static int bdrv_qed_create(const char *filename, QemuOpts *opts, Error **errp)
642 uint64_t image_size = 0;
643 uint32_t cluster_size = QED_DEFAULT_CLUSTER_SIZE;
644 uint32_t table_size = QED_DEFAULT_TABLE_SIZE;
645 char *backing_file = NULL;
646 char *backing_fmt = NULL;
649 image_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
651 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
652 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
653 cluster_size = qemu_opt_get_size_del(opts,
654 BLOCK_OPT_CLUSTER_SIZE,
655 QED_DEFAULT_CLUSTER_SIZE);
656 table_size = qemu_opt_get_size_del(opts, BLOCK_OPT_TABLE_SIZE,
657 QED_DEFAULT_TABLE_SIZE);
659 if (!qed_is_cluster_size_valid(cluster_size)) {
660 error_setg(errp, "QED cluster size must be within range [%u, %u] "
662 QED_MIN_CLUSTER_SIZE, QED_MAX_CLUSTER_SIZE);
666 if (!qed_is_table_size_valid(table_size)) {
667 error_setg(errp, "QED table size must be within range [%u, %u] "
669 QED_MIN_TABLE_SIZE, QED_MAX_TABLE_SIZE);
673 if (!qed_is_image_size_valid(image_size, cluster_size, table_size)) {
674 error_setg(errp, "QED image size must be a non-zero multiple of "
675 "cluster size and less than %" PRIu64 " bytes",
676 qed_max_image_size(cluster_size, table_size));
681 ret = qed_create(filename, cluster_size, image_size, table_size,
682 backing_file, backing_fmt, opts, errp);
685 g_free(backing_file);
691 BlockDriverState *bs;
696 BlockDriverState **file;
699 /* Called with table_lock held. */
700 static void qed_is_allocated_cb(void *opaque, int ret, uint64_t offset, size_t len)
702 QEDIsAllocatedCB *cb = opaque;
703 BDRVQEDState *s = cb->bs->opaque;
704 *cb->pnum = len / BDRV_SECTOR_SIZE;
706 case QED_CLUSTER_FOUND:
707 offset |= qed_offset_into_cluster(s, cb->pos);
708 cb->status = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
709 *cb->file = cb->bs->file->bs;
711 case QED_CLUSTER_ZERO:
712 cb->status = BDRV_BLOCK_ZERO;
729 static int64_t coroutine_fn bdrv_qed_co_get_block_status(BlockDriverState *bs,
731 int nb_sectors, int *pnum,
732 BlockDriverState **file)
734 BDRVQEDState *s = bs->opaque;
735 size_t len = (size_t)nb_sectors * BDRV_SECTOR_SIZE;
736 QEDIsAllocatedCB cb = {
738 .pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE,
739 .status = BDRV_BLOCK_OFFSET_MASK,
743 QEDRequest request = { .l2_table = NULL };
747 qemu_co_mutex_lock(&s->table_lock);
748 ret = qed_find_cluster(s, &request, cb.pos, &len, &offset);
749 qed_is_allocated_cb(&cb, ret, offset, len);
751 /* The callback was invoked immediately */
752 assert(cb.status != BDRV_BLOCK_OFFSET_MASK);
754 qed_unref_l2_cache_entry(request.l2_table);
755 qemu_co_mutex_unlock(&s->table_lock);
760 static BDRVQEDState *acb_to_s(QEDAIOCB *acb)
762 return acb->bs->opaque;
766 * Read from the backing file or zero-fill if no backing file
769 * @pos: Byte position in device
770 * @qiov: Destination I/O vector
771 * @backing_qiov: Possibly shortened copy of qiov, to be allocated here
772 * @cb: Completion function
773 * @opaque: User data for completion function
775 * This function reads qiov->size bytes starting at pos from the backing file.
776 * If there is no backing file then zeroes are read.
778 static int coroutine_fn qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
780 QEMUIOVector **backing_qiov)
782 uint64_t backing_length = 0;
786 /* If there is a backing file, get its length. Treat the absence of a
787 * backing file like a zero length backing file.
789 if (s->bs->backing) {
790 int64_t l = bdrv_getlength(s->bs->backing->bs);
797 /* Zero all sectors if reading beyond the end of the backing file */
798 if (pos >= backing_length ||
799 pos + qiov->size > backing_length) {
800 qemu_iovec_memset(qiov, 0, 0, qiov->size);
803 /* Complete now if there are no backing file sectors to read */
804 if (pos >= backing_length) {
808 /* If the read straddles the end of the backing file, shorten it */
809 size = MIN((uint64_t)backing_length - pos, qiov->size);
811 assert(*backing_qiov == NULL);
812 *backing_qiov = g_new(QEMUIOVector, 1);
813 qemu_iovec_init(*backing_qiov, qiov->niov);
814 qemu_iovec_concat(*backing_qiov, qiov, 0, size);
816 BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);
817 ret = bdrv_co_preadv(s->bs->backing, pos, size, *backing_qiov, 0);
825 * Copy data from backing file into the image
828 * @pos: Byte position in device
829 * @len: Number of bytes
830 * @offset: Byte offset in image file
832 static int coroutine_fn qed_copy_from_backing_file(BDRVQEDState *s,
833 uint64_t pos, uint64_t len,
837 QEMUIOVector *backing_qiov = NULL;
841 /* Skip copy entirely if there is no work to do */
846 iov = (struct iovec) {
847 .iov_base = qemu_blockalign(s->bs, len),
850 qemu_iovec_init_external(&qiov, &iov, 1);
852 ret = qed_read_backing_file(s, pos, &qiov, &backing_qiov);
855 qemu_iovec_destroy(backing_qiov);
856 g_free(backing_qiov);
864 BLKDBG_EVENT(s->bs->file, BLKDBG_COW_WRITE);
865 ret = bdrv_co_pwritev(s->bs->file, offset, qiov.size, &qiov, 0);
871 qemu_vfree(iov.iov_base);
876 * Link one or more contiguous clusters into a table
880 * @index: First cluster index
881 * @n: Number of contiguous clusters
882 * @cluster: First cluster offset
884 * The cluster offset may be an allocated byte offset in the image file, the
885 * zero cluster marker, or the unallocated cluster marker.
887 * Called with table_lock held.
889 static void coroutine_fn qed_update_l2_table(BDRVQEDState *s, QEDTable *table,
890 int index, unsigned int n,
894 for (i = index; i < index + n; i++) {
895 table->offsets[i] = cluster;
896 if (!qed_offset_is_unalloc_cluster(cluster) &&
897 !qed_offset_is_zero_cluster(cluster)) {
898 cluster += s->header.cluster_size;
903 /* Called with table_lock held. */
904 static void coroutine_fn qed_aio_complete(QEDAIOCB *acb)
906 BDRVQEDState *s = acb_to_s(acb);
909 qemu_iovec_destroy(&acb->cur_qiov);
910 qed_unref_l2_cache_entry(acb->request.l2_table);
912 /* Free the buffer we may have allocated for zero writes */
913 if (acb->flags & QED_AIOCB_ZERO) {
914 qemu_vfree(acb->qiov->iov[0].iov_base);
915 acb->qiov->iov[0].iov_base = NULL;
918 /* Start next allocating write request waiting behind this one. Note that
919 * requests enqueue themselves when they first hit an unallocated cluster
920 * but they wait until the entire request is finished before waking up the
921 * next request in the queue. This ensures that we don't cycle through
922 * requests multiple times but rather finish one at a time completely.
924 if (acb == s->allocating_acb) {
925 s->allocating_acb = NULL;
926 if (!qemu_co_queue_empty(&s->allocating_write_reqs)) {
927 qemu_co_queue_next(&s->allocating_write_reqs);
928 } else if (s->header.features & QED_F_NEED_CHECK) {
929 qed_start_need_check_timer(s);
935 * Update L1 table with new L2 table offset and write it out
937 * Called with table_lock held.
939 static int coroutine_fn qed_aio_write_l1_update(QEDAIOCB *acb)
941 BDRVQEDState *s = acb_to_s(acb);
942 CachedL2Table *l2_table = acb->request.l2_table;
943 uint64_t l2_offset = l2_table->offset;
946 index = qed_l1_index(s, acb->cur_pos);
947 s->l1_table->offsets[index] = l2_table->offset;
949 ret = qed_write_l1_table(s, index, 1);
951 /* Commit the current L2 table to the cache */
952 qed_commit_l2_cache_entry(&s->l2_cache, l2_table);
954 /* This is guaranteed to succeed because we just committed the entry to the
957 acb->request.l2_table = qed_find_l2_cache_entry(&s->l2_cache, l2_offset);
958 assert(acb->request.l2_table != NULL);
965 * Update L2 table with new cluster offsets and write them out
967 * Called with table_lock held.
969 static int coroutine_fn qed_aio_write_l2_update(QEDAIOCB *acb, uint64_t offset)
971 BDRVQEDState *s = acb_to_s(acb);
972 bool need_alloc = acb->find_cluster_ret == QED_CLUSTER_L1;
976 qed_unref_l2_cache_entry(acb->request.l2_table);
977 acb->request.l2_table = qed_new_l2_table(s);
980 index = qed_l2_index(s, acb->cur_pos);
981 qed_update_l2_table(s, acb->request.l2_table->table, index, acb->cur_nclusters,
985 /* Write out the whole new L2 table */
986 ret = qed_write_l2_table(s, &acb->request, 0, s->table_nelems, true);
990 return qed_aio_write_l1_update(acb);
992 /* Write out only the updated part of the L2 table */
993 ret = qed_write_l2_table(s, &acb->request, index, acb->cur_nclusters,
1003 * Write data to the image file
1005 * Called with table_lock *not* held.
1007 static int coroutine_fn qed_aio_write_main(QEDAIOCB *acb)
1009 BDRVQEDState *s = acb_to_s(acb);
1010 uint64_t offset = acb->cur_cluster +
1011 qed_offset_into_cluster(s, acb->cur_pos);
1013 trace_qed_aio_write_main(s, acb, 0, offset, acb->cur_qiov.size);
1015 BLKDBG_EVENT(s->bs->file, BLKDBG_WRITE_AIO);
1016 return bdrv_co_pwritev(s->bs->file, offset, acb->cur_qiov.size,
1021 * Populate untouched regions of new data cluster
1023 * Called with table_lock held.
1025 static int coroutine_fn qed_aio_write_cow(QEDAIOCB *acb)
1027 BDRVQEDState *s = acb_to_s(acb);
1028 uint64_t start, len, offset;
1031 qemu_co_mutex_unlock(&s->table_lock);
1033 /* Populate front untouched region of new data cluster */
1034 start = qed_start_of_cluster(s, acb->cur_pos);
1035 len = qed_offset_into_cluster(s, acb->cur_pos);
1037 trace_qed_aio_write_prefill(s, acb, start, len, acb->cur_cluster);
1038 ret = qed_copy_from_backing_file(s, start, len, acb->cur_cluster);
1043 /* Populate back untouched region of new data cluster */
1044 start = acb->cur_pos + acb->cur_qiov.size;
1045 len = qed_start_of_cluster(s, start + s->header.cluster_size - 1) - start;
1046 offset = acb->cur_cluster +
1047 qed_offset_into_cluster(s, acb->cur_pos) +
1050 trace_qed_aio_write_postfill(s, acb, start, len, offset);
1051 ret = qed_copy_from_backing_file(s, start, len, offset);
1056 ret = qed_aio_write_main(acb);
1061 if (s->bs->backing) {
1063 * Flush new data clusters before updating the L2 table
1065 * This flush is necessary when a backing file is in use. A crash
1066 * during an allocating write could result in empty clusters in the
1067 * image. If the write only touched a subregion of the cluster,
1068 * then backing image sectors have been lost in the untouched
1069 * region. The solution is to flush after writing a new data
1070 * cluster and before updating the L2 table.
1072 ret = bdrv_co_flush(s->bs->file->bs);
1076 qemu_co_mutex_lock(&s->table_lock);
1081 * Check if the QED_F_NEED_CHECK bit should be set during allocating write
1083 static bool qed_should_set_need_check(BDRVQEDState *s)
1085 /* The flush before L2 update path ensures consistency */
1086 if (s->bs->backing) {
1090 return !(s->header.features & QED_F_NEED_CHECK);
1094 * Write new data cluster
1096 * @acb: Write request
1097 * @len: Length in bytes
1099 * This path is taken when writing to previously unallocated clusters.
1101 * Called with table_lock held.
1103 static int coroutine_fn qed_aio_write_alloc(QEDAIOCB *acb, size_t len)
1105 BDRVQEDState *s = acb_to_s(acb);
1108 /* Cancel timer when the first allocating request comes in */
1109 if (s->allocating_acb == NULL) {
1110 qed_cancel_need_check_timer(s);
1113 /* Freeze this request if another allocating write is in progress */
1114 if (s->allocating_acb != acb || s->allocating_write_reqs_plugged) {
1115 if (s->allocating_acb != NULL) {
1116 qemu_co_queue_wait(&s->allocating_write_reqs, &s->table_lock);
1117 assert(s->allocating_acb == NULL);
1119 s->allocating_acb = acb;
1120 return -EAGAIN; /* start over with looking up table entries */
1123 acb->cur_nclusters = qed_bytes_to_clusters(s,
1124 qed_offset_into_cluster(s, acb->cur_pos) + len);
1125 qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1127 if (acb->flags & QED_AIOCB_ZERO) {
1128 /* Skip ahead if the clusters are already zero */
1129 if (acb->find_cluster_ret == QED_CLUSTER_ZERO) {
1132 acb->cur_cluster = 1;
1134 acb->cur_cluster = qed_alloc_clusters(s, acb->cur_nclusters);
1137 if (qed_should_set_need_check(s)) {
1138 s->header.features |= QED_F_NEED_CHECK;
1139 ret = qed_write_header(s);
1145 if (!(acb->flags & QED_AIOCB_ZERO)) {
1146 ret = qed_aio_write_cow(acb);
1152 return qed_aio_write_l2_update(acb, acb->cur_cluster);
1156 * Write data cluster in place
1158 * @acb: Write request
1159 * @offset: Cluster offset in bytes
1160 * @len: Length in bytes
1162 * This path is taken when writing to already allocated clusters.
1164 * Called with table_lock held.
1166 static int coroutine_fn qed_aio_write_inplace(QEDAIOCB *acb, uint64_t offset,
1169 BDRVQEDState *s = acb_to_s(acb);
1172 qemu_co_mutex_unlock(&s->table_lock);
1174 /* Allocate buffer for zero writes */
1175 if (acb->flags & QED_AIOCB_ZERO) {
1176 struct iovec *iov = acb->qiov->iov;
1178 if (!iov->iov_base) {
1179 iov->iov_base = qemu_try_blockalign(acb->bs, iov->iov_len);
1180 if (iov->iov_base == NULL) {
1184 memset(iov->iov_base, 0, iov->iov_len);
1188 /* Calculate the I/O vector */
1189 acb->cur_cluster = offset;
1190 qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1192 /* Do the actual write. */
1193 r = qed_aio_write_main(acb);
1195 qemu_co_mutex_lock(&s->table_lock);
1200 * Write data cluster
1202 * @opaque: Write request
1203 * @ret: QED_CLUSTER_FOUND, QED_CLUSTER_L2 or QED_CLUSTER_L1
1204 * @offset: Cluster offset in bytes
1205 * @len: Length in bytes
1207 * Called with table_lock held.
1209 static int coroutine_fn qed_aio_write_data(void *opaque, int ret,
1210 uint64_t offset, size_t len)
1212 QEDAIOCB *acb = opaque;
1214 trace_qed_aio_write_data(acb_to_s(acb), acb, ret, offset, len);
1216 acb->find_cluster_ret = ret;
1219 case QED_CLUSTER_FOUND:
1220 return qed_aio_write_inplace(acb, offset, len);
1222 case QED_CLUSTER_L2:
1223 case QED_CLUSTER_L1:
1224 case QED_CLUSTER_ZERO:
1225 return qed_aio_write_alloc(acb, len);
1228 g_assert_not_reached();
1235 * @opaque: Read request
1236 * @ret: QED_CLUSTER_FOUND, QED_CLUSTER_L2 or QED_CLUSTER_L1
1237 * @offset: Cluster offset in bytes
1238 * @len: Length in bytes
1240 * Called with table_lock held.
1242 static int coroutine_fn qed_aio_read_data(void *opaque, int ret,
1243 uint64_t offset, size_t len)
1245 QEDAIOCB *acb = opaque;
1246 BDRVQEDState *s = acb_to_s(acb);
1247 BlockDriverState *bs = acb->bs;
1250 qemu_co_mutex_unlock(&s->table_lock);
1252 /* Adjust offset into cluster */
1253 offset += qed_offset_into_cluster(s, acb->cur_pos);
1255 trace_qed_aio_read_data(s, acb, ret, offset, len);
1257 qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1259 /* Handle zero cluster and backing file reads, otherwise read
1260 * data cluster directly.
1262 if (ret == QED_CLUSTER_ZERO) {
1263 qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
1265 } else if (ret != QED_CLUSTER_FOUND) {
1266 r = qed_read_backing_file(s, acb->cur_pos, &acb->cur_qiov,
1267 &acb->backing_qiov);
1269 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1270 r = bdrv_co_preadv(bs->file, offset, acb->cur_qiov.size,
1274 qemu_co_mutex_lock(&s->table_lock);
1279 * Begin next I/O or complete the request
1281 static int coroutine_fn qed_aio_next_io(QEDAIOCB *acb)
1283 BDRVQEDState *s = acb_to_s(acb);
1288 qemu_co_mutex_lock(&s->table_lock);
1290 trace_qed_aio_next_io(s, acb, 0, acb->cur_pos + acb->cur_qiov.size);
1292 if (acb->backing_qiov) {
1293 qemu_iovec_destroy(acb->backing_qiov);
1294 g_free(acb->backing_qiov);
1295 acb->backing_qiov = NULL;
1298 acb->qiov_offset += acb->cur_qiov.size;
1299 acb->cur_pos += acb->cur_qiov.size;
1300 qemu_iovec_reset(&acb->cur_qiov);
1302 /* Complete request */
1303 if (acb->cur_pos >= acb->end_pos) {
1308 /* Find next cluster and start I/O */
1309 len = acb->end_pos - acb->cur_pos;
1310 ret = qed_find_cluster(s, &acb->request, acb->cur_pos, &len, &offset);
1315 if (acb->flags & QED_AIOCB_WRITE) {
1316 ret = qed_aio_write_data(acb, ret, offset, len);
1318 ret = qed_aio_read_data(acb, ret, offset, len);
1321 if (ret < 0 && ret != -EAGAIN) {
1326 trace_qed_aio_complete(s, acb, ret);
1327 qed_aio_complete(acb);
1328 qemu_co_mutex_unlock(&s->table_lock);
1332 static int coroutine_fn qed_co_request(BlockDriverState *bs, int64_t sector_num,
1333 QEMUIOVector *qiov, int nb_sectors,
1338 .cur_pos = (uint64_t) sector_num * BDRV_SECTOR_SIZE,
1339 .end_pos = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE,
1343 qemu_iovec_init(&acb.cur_qiov, qiov->niov);
1345 trace_qed_aio_setup(bs->opaque, &acb, sector_num, nb_sectors, NULL, flags);
1348 return qed_aio_next_io(&acb);
1351 static int coroutine_fn bdrv_qed_co_readv(BlockDriverState *bs,
1352 int64_t sector_num, int nb_sectors,
1355 return qed_co_request(bs, sector_num, qiov, nb_sectors, 0);
1358 static int coroutine_fn bdrv_qed_co_writev(BlockDriverState *bs,
1359 int64_t sector_num, int nb_sectors,
1362 return qed_co_request(bs, sector_num, qiov, nb_sectors, QED_AIOCB_WRITE);
1365 static int coroutine_fn bdrv_qed_co_pwrite_zeroes(BlockDriverState *bs,
1368 BdrvRequestFlags flags)
1370 BDRVQEDState *s = bs->opaque;
1374 /* Fall back if the request is not aligned */
1375 if (qed_offset_into_cluster(s, offset) ||
1376 qed_offset_into_cluster(s, bytes)) {
1380 /* Zero writes start without an I/O buffer. If a buffer becomes necessary
1381 * then it will be allocated during request processing.
1383 iov.iov_base = NULL;
1384 iov.iov_len = bytes;
1386 qemu_iovec_init_external(&qiov, &iov, 1);
1387 return qed_co_request(bs, offset >> BDRV_SECTOR_BITS, &qiov,
1388 bytes >> BDRV_SECTOR_BITS,
1389 QED_AIOCB_WRITE | QED_AIOCB_ZERO);
1392 static int bdrv_qed_truncate(BlockDriverState *bs, int64_t offset,
1393 PreallocMode prealloc, Error **errp)
1395 BDRVQEDState *s = bs->opaque;
1396 uint64_t old_image_size;
1399 if (prealloc != PREALLOC_MODE_OFF) {
1400 error_setg(errp, "Unsupported preallocation mode '%s'",
1401 PreallocMode_str(prealloc));
1405 if (!qed_is_image_size_valid(offset, s->header.cluster_size,
1406 s->header.table_size)) {
1407 error_setg(errp, "Invalid image size specified");
1411 if ((uint64_t)offset < s->header.image_size) {
1412 error_setg(errp, "Shrinking images is currently not supported");
1416 old_image_size = s->header.image_size;
1417 s->header.image_size = offset;
1418 ret = qed_write_header_sync(s);
1420 s->header.image_size = old_image_size;
1421 error_setg_errno(errp, -ret, "Failed to update the image size");
1426 static int64_t bdrv_qed_getlength(BlockDriverState *bs)
1428 BDRVQEDState *s = bs->opaque;
1429 return s->header.image_size;
1432 static int bdrv_qed_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1434 BDRVQEDState *s = bs->opaque;
1436 memset(bdi, 0, sizeof(*bdi));
1437 bdi->cluster_size = s->header.cluster_size;
1438 bdi->is_dirty = s->header.features & QED_F_NEED_CHECK;
1439 bdi->unallocated_blocks_are_zero = true;
1440 bdi->can_write_zeroes_with_unmap = true;
1444 static int bdrv_qed_change_backing_file(BlockDriverState *bs,
1445 const char *backing_file,
1446 const char *backing_fmt)
1448 BDRVQEDState *s = bs->opaque;
1449 QEDHeader new_header, le_header;
1451 size_t buffer_len, backing_file_len;
1454 /* Refuse to set backing filename if unknown compat feature bits are
1455 * active. If the image uses an unknown compat feature then we may not
1456 * know the layout of data following the header structure and cannot safely
1459 if (backing_file && (s->header.compat_features &
1460 ~QED_COMPAT_FEATURE_MASK)) {
1464 memcpy(&new_header, &s->header, sizeof(new_header));
1466 new_header.features &= ~(QED_F_BACKING_FILE |
1467 QED_F_BACKING_FORMAT_NO_PROBE);
1469 /* Adjust feature flags */
1471 new_header.features |= QED_F_BACKING_FILE;
1473 if (qed_fmt_is_raw(backing_fmt)) {
1474 new_header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
1478 /* Calculate new header size */
1479 backing_file_len = 0;
1482 backing_file_len = strlen(backing_file);
1485 buffer_len = sizeof(new_header);
1486 new_header.backing_filename_offset = buffer_len;
1487 new_header.backing_filename_size = backing_file_len;
1488 buffer_len += backing_file_len;
1490 /* Make sure we can rewrite header without failing */
1491 if (buffer_len > new_header.header_size * new_header.cluster_size) {
1495 /* Prepare new header */
1496 buffer = g_malloc(buffer_len);
1498 qed_header_cpu_to_le(&new_header, &le_header);
1499 memcpy(buffer, &le_header, sizeof(le_header));
1500 buffer_len = sizeof(le_header);
1503 memcpy(buffer + buffer_len, backing_file, backing_file_len);
1504 buffer_len += backing_file_len;
1507 /* Write new header */
1508 ret = bdrv_pwrite_sync(bs->file, 0, buffer, buffer_len);
1511 memcpy(&s->header, &new_header, sizeof(new_header));
1516 static void bdrv_qed_invalidate_cache(BlockDriverState *bs, Error **errp)
1518 BDRVQEDState *s = bs->opaque;
1519 Error *local_err = NULL;
1524 bdrv_qed_init_state(bs);
1525 if (qemu_in_coroutine()) {
1526 qemu_co_mutex_lock(&s->table_lock);
1528 ret = bdrv_qed_do_open(bs, NULL, bs->open_flags, &local_err);
1529 if (qemu_in_coroutine()) {
1530 qemu_co_mutex_unlock(&s->table_lock);
1533 error_propagate(errp, local_err);
1534 error_prepend(errp, "Could not reopen qed layer: ");
1536 } else if (ret < 0) {
1537 error_setg_errno(errp, -ret, "Could not reopen qed layer");
1542 static int bdrv_qed_check(BlockDriverState *bs, BdrvCheckResult *result,
1545 BDRVQEDState *s = bs->opaque;
1547 return qed_check(s, result, !!fix);
1550 static QemuOptsList qed_create_opts = {
1551 .name = "qed-create-opts",
1552 .head = QTAILQ_HEAD_INITIALIZER(qed_create_opts.head),
1555 .name = BLOCK_OPT_SIZE,
1556 .type = QEMU_OPT_SIZE,
1557 .help = "Virtual disk size"
1560 .name = BLOCK_OPT_BACKING_FILE,
1561 .type = QEMU_OPT_STRING,
1562 .help = "File name of a base image"
1565 .name = BLOCK_OPT_BACKING_FMT,
1566 .type = QEMU_OPT_STRING,
1567 .help = "Image format of the base image"
1570 .name = BLOCK_OPT_CLUSTER_SIZE,
1571 .type = QEMU_OPT_SIZE,
1572 .help = "Cluster size (in bytes)",
1573 .def_value_str = stringify(QED_DEFAULT_CLUSTER_SIZE)
1576 .name = BLOCK_OPT_TABLE_SIZE,
1577 .type = QEMU_OPT_SIZE,
1578 .help = "L1/L2 table size (in clusters)"
1580 { /* end of list */ }
1584 static BlockDriver bdrv_qed = {
1585 .format_name = "qed",
1586 .instance_size = sizeof(BDRVQEDState),
1587 .create_opts = &qed_create_opts,
1588 .supports_backing = true,
1590 .bdrv_probe = bdrv_qed_probe,
1591 .bdrv_open = bdrv_qed_open,
1592 .bdrv_close = bdrv_qed_close,
1593 .bdrv_reopen_prepare = bdrv_qed_reopen_prepare,
1594 .bdrv_child_perm = bdrv_format_default_perms,
1595 .bdrv_create = bdrv_qed_create,
1596 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1597 .bdrv_co_get_block_status = bdrv_qed_co_get_block_status,
1598 .bdrv_co_readv = bdrv_qed_co_readv,
1599 .bdrv_co_writev = bdrv_qed_co_writev,
1600 .bdrv_co_pwrite_zeroes = bdrv_qed_co_pwrite_zeroes,
1601 .bdrv_truncate = bdrv_qed_truncate,
1602 .bdrv_getlength = bdrv_qed_getlength,
1603 .bdrv_get_info = bdrv_qed_get_info,
1604 .bdrv_refresh_limits = bdrv_qed_refresh_limits,
1605 .bdrv_change_backing_file = bdrv_qed_change_backing_file,
1606 .bdrv_invalidate_cache = bdrv_qed_invalidate_cache,
1607 .bdrv_check = bdrv_qed_check,
1608 .bdrv_detach_aio_context = bdrv_qed_detach_aio_context,
1609 .bdrv_attach_aio_context = bdrv_qed_attach_aio_context,
1610 .bdrv_co_drain_begin = bdrv_qed_co_drain_begin,
1613 static void bdrv_qed_init(void)
1615 bdrv_register(&bdrv_qed);
1618 block_init(bdrv_qed_init);