xref: /openbmc/qemu/block/qed.c (revision 39164c13)
1 /*
2  * QEMU Enhanced Disk Format
3  *
4  * Copyright IBM, Corp. 2010
5  *
6  * Authors:
7  *  Stefan Hajnoczi   <stefanha@linux.vnet.ibm.com>
8  *  Anthony Liguori   <aliguori@us.ibm.com>
9  *
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.
12  *
13  */
14 
15 #include "qemu/osdep.h"
16 #include "qapi/error.h"
17 #include "qemu/timer.h"
18 #include "qemu/bswap.h"
19 #include "trace.h"
20 #include "qed.h"
21 #include "qapi/qmp/qerror.h"
22 #include "migration/migration.h"
23 #include "sysemu/block-backend.h"
24 
25 static const AIOCBInfo qed_aiocb_info = {
26     .aiocb_size         = sizeof(QEDAIOCB),
27 };
28 
29 static int bdrv_qed_probe(const uint8_t *buf, int buf_size,
30                           const char *filename)
31 {
32     const QEDHeader *header = (const QEDHeader *)buf;
33 
34     if (buf_size < sizeof(*header)) {
35         return 0;
36     }
37     if (le32_to_cpu(header->magic) != QED_MAGIC) {
38         return 0;
39     }
40     return 100;
41 }
42 
43 /**
44  * Check whether an image format is raw
45  *
46  * @fmt:    Backing file format, may be NULL
47  */
48 static bool qed_fmt_is_raw(const char *fmt)
49 {
50     return fmt && strcmp(fmt, "raw") == 0;
51 }
52 
53 static void qed_header_le_to_cpu(const QEDHeader *le, QEDHeader *cpu)
54 {
55     cpu->magic = le32_to_cpu(le->magic);
56     cpu->cluster_size = le32_to_cpu(le->cluster_size);
57     cpu->table_size = le32_to_cpu(le->table_size);
58     cpu->header_size = le32_to_cpu(le->header_size);
59     cpu->features = le64_to_cpu(le->features);
60     cpu->compat_features = le64_to_cpu(le->compat_features);
61     cpu->autoclear_features = le64_to_cpu(le->autoclear_features);
62     cpu->l1_table_offset = le64_to_cpu(le->l1_table_offset);
63     cpu->image_size = le64_to_cpu(le->image_size);
64     cpu->backing_filename_offset = le32_to_cpu(le->backing_filename_offset);
65     cpu->backing_filename_size = le32_to_cpu(le->backing_filename_size);
66 }
67 
68 static void qed_header_cpu_to_le(const QEDHeader *cpu, QEDHeader *le)
69 {
70     le->magic = cpu_to_le32(cpu->magic);
71     le->cluster_size = cpu_to_le32(cpu->cluster_size);
72     le->table_size = cpu_to_le32(cpu->table_size);
73     le->header_size = cpu_to_le32(cpu->header_size);
74     le->features = cpu_to_le64(cpu->features);
75     le->compat_features = cpu_to_le64(cpu->compat_features);
76     le->autoclear_features = cpu_to_le64(cpu->autoclear_features);
77     le->l1_table_offset = cpu_to_le64(cpu->l1_table_offset);
78     le->image_size = cpu_to_le64(cpu->image_size);
79     le->backing_filename_offset = cpu_to_le32(cpu->backing_filename_offset);
80     le->backing_filename_size = cpu_to_le32(cpu->backing_filename_size);
81 }
82 
83 int qed_write_header_sync(BDRVQEDState *s)
84 {
85     QEDHeader le;
86     int ret;
87 
88     qed_header_cpu_to_le(&s->header, &le);
89     ret = bdrv_pwrite(s->bs->file, 0, &le, sizeof(le));
90     if (ret != sizeof(le)) {
91         return ret;
92     }
93     return 0;
94 }
95 
96 typedef struct {
97     GenericCB gencb;
98     BDRVQEDState *s;
99     struct iovec iov;
100     QEMUIOVector qiov;
101     int nsectors;
102     uint8_t *buf;
103 } QEDWriteHeaderCB;
104 
105 static void qed_write_header_cb(void *opaque, int ret)
106 {
107     QEDWriteHeaderCB *write_header_cb = opaque;
108 
109     qemu_vfree(write_header_cb->buf);
110     gencb_complete(write_header_cb, ret);
111 }
112 
113 static void qed_write_header_read_cb(void *opaque, int ret)
114 {
115     QEDWriteHeaderCB *write_header_cb = opaque;
116     BDRVQEDState *s = write_header_cb->s;
117 
118     if (ret) {
119         qed_write_header_cb(write_header_cb, ret);
120         return;
121     }
122 
123     /* Update header */
124     qed_header_cpu_to_le(&s->header, (QEDHeader *)write_header_cb->buf);
125 
126     bdrv_aio_writev(s->bs->file, 0, &write_header_cb->qiov,
127                     write_header_cb->nsectors, qed_write_header_cb,
128                     write_header_cb);
129 }
130 
131 /**
132  * Update header in-place (does not rewrite backing filename or other strings)
133  *
134  * This function only updates known header fields in-place and does not affect
135  * extra data after the QED header.
136  */
137 static void qed_write_header(BDRVQEDState *s, BlockCompletionFunc cb,
138                              void *opaque)
139 {
140     /* We must write full sectors for O_DIRECT but cannot necessarily generate
141      * the data following the header if an unrecognized compat feature is
142      * active.  Therefore, first read the sectors containing the header, update
143      * them, and write back.
144      */
145 
146     int nsectors = DIV_ROUND_UP(sizeof(QEDHeader), BDRV_SECTOR_SIZE);
147     size_t len = nsectors * BDRV_SECTOR_SIZE;
148     QEDWriteHeaderCB *write_header_cb = gencb_alloc(sizeof(*write_header_cb),
149                                                     cb, opaque);
150 
151     write_header_cb->s = s;
152     write_header_cb->nsectors = nsectors;
153     write_header_cb->buf = qemu_blockalign(s->bs, len);
154     write_header_cb->iov.iov_base = write_header_cb->buf;
155     write_header_cb->iov.iov_len = len;
156     qemu_iovec_init_external(&write_header_cb->qiov, &write_header_cb->iov, 1);
157 
158     bdrv_aio_readv(s->bs->file, 0, &write_header_cb->qiov, nsectors,
159                    qed_write_header_read_cb, write_header_cb);
160 }
161 
162 static uint64_t qed_max_image_size(uint32_t cluster_size, uint32_t table_size)
163 {
164     uint64_t table_entries;
165     uint64_t l2_size;
166 
167     table_entries = (table_size * cluster_size) / sizeof(uint64_t);
168     l2_size = table_entries * cluster_size;
169 
170     return l2_size * table_entries;
171 }
172 
173 static bool qed_is_cluster_size_valid(uint32_t cluster_size)
174 {
175     if (cluster_size < QED_MIN_CLUSTER_SIZE ||
176         cluster_size > QED_MAX_CLUSTER_SIZE) {
177         return false;
178     }
179     if (cluster_size & (cluster_size - 1)) {
180         return false; /* not power of 2 */
181     }
182     return true;
183 }
184 
185 static bool qed_is_table_size_valid(uint32_t table_size)
186 {
187     if (table_size < QED_MIN_TABLE_SIZE ||
188         table_size > QED_MAX_TABLE_SIZE) {
189         return false;
190     }
191     if (table_size & (table_size - 1)) {
192         return false; /* not power of 2 */
193     }
194     return true;
195 }
196 
197 static bool qed_is_image_size_valid(uint64_t image_size, uint32_t cluster_size,
198                                     uint32_t table_size)
199 {
200     if (image_size % BDRV_SECTOR_SIZE != 0) {
201         return false; /* not multiple of sector size */
202     }
203     if (image_size > qed_max_image_size(cluster_size, table_size)) {
204         return false; /* image is too large */
205     }
206     return true;
207 }
208 
209 /**
210  * Read a string of known length from the image file
211  *
212  * @file:       Image file
213  * @offset:     File offset to start of string, in bytes
214  * @n:          String length in bytes
215  * @buf:        Destination buffer
216  * @buflen:     Destination buffer length in bytes
217  * @ret:        0 on success, -errno on failure
218  *
219  * The string is NUL-terminated.
220  */
221 static int qed_read_string(BdrvChild *file, uint64_t offset, size_t n,
222                            char *buf, size_t buflen)
223 {
224     int ret;
225     if (n >= buflen) {
226         return -EINVAL;
227     }
228     ret = bdrv_pread(file, offset, buf, n);
229     if (ret < 0) {
230         return ret;
231     }
232     buf[n] = '\0';
233     return 0;
234 }
235 
236 /**
237  * Allocate new clusters
238  *
239  * @s:          QED state
240  * @n:          Number of contiguous clusters to allocate
241  * @ret:        Offset of first allocated cluster
242  *
243  * This function only produces the offset where the new clusters should be
244  * written.  It updates BDRVQEDState but does not make any changes to the image
245  * file.
246  */
247 static uint64_t qed_alloc_clusters(BDRVQEDState *s, unsigned int n)
248 {
249     uint64_t offset = s->file_size;
250     s->file_size += n * s->header.cluster_size;
251     return offset;
252 }
253 
254 QEDTable *qed_alloc_table(BDRVQEDState *s)
255 {
256     /* Honor O_DIRECT memory alignment requirements */
257     return qemu_blockalign(s->bs,
258                            s->header.cluster_size * s->header.table_size);
259 }
260 
261 /**
262  * Allocate a new zeroed L2 table
263  */
264 static CachedL2Table *qed_new_l2_table(BDRVQEDState *s)
265 {
266     CachedL2Table *l2_table = qed_alloc_l2_cache_entry(&s->l2_cache);
267 
268     l2_table->table = qed_alloc_table(s);
269     l2_table->offset = qed_alloc_clusters(s, s->header.table_size);
270 
271     memset(l2_table->table->offsets, 0,
272            s->header.cluster_size * s->header.table_size);
273     return l2_table;
274 }
275 
276 static void qed_aio_next_io(QEDAIOCB *acb, int ret);
277 
278 static void qed_aio_start_io(QEDAIOCB *acb)
279 {
280     qed_aio_next_io(acb, 0);
281 }
282 
283 static void qed_aio_next_io_cb(void *opaque, int ret)
284 {
285     QEDAIOCB *acb = opaque;
286 
287     qed_aio_next_io(acb, ret);
288 }
289 
290 static void qed_plug_allocating_write_reqs(BDRVQEDState *s)
291 {
292     assert(!s->allocating_write_reqs_plugged);
293 
294     s->allocating_write_reqs_plugged = true;
295 }
296 
297 static void qed_unplug_allocating_write_reqs(BDRVQEDState *s)
298 {
299     QEDAIOCB *acb;
300 
301     assert(s->allocating_write_reqs_plugged);
302 
303     s->allocating_write_reqs_plugged = false;
304 
305     acb = QSIMPLEQ_FIRST(&s->allocating_write_reqs);
306     if (acb) {
307         qed_aio_start_io(acb);
308     }
309 }
310 
311 static void qed_finish_clear_need_check(void *opaque, int ret)
312 {
313     /* Do nothing */
314 }
315 
316 static void qed_flush_after_clear_need_check(void *opaque, int ret)
317 {
318     BDRVQEDState *s = opaque;
319 
320     bdrv_aio_flush(s->bs, qed_finish_clear_need_check, s);
321 
322     /* No need to wait until flush completes */
323     qed_unplug_allocating_write_reqs(s);
324 }
325 
326 static void qed_clear_need_check(void *opaque, int ret)
327 {
328     BDRVQEDState *s = opaque;
329 
330     if (ret) {
331         qed_unplug_allocating_write_reqs(s);
332         return;
333     }
334 
335     s->header.features &= ~QED_F_NEED_CHECK;
336     qed_write_header(s, qed_flush_after_clear_need_check, s);
337 }
338 
339 static void qed_need_check_timer_cb(void *opaque)
340 {
341     BDRVQEDState *s = opaque;
342 
343     /* The timer should only fire when allocating writes have drained */
344     assert(!QSIMPLEQ_FIRST(&s->allocating_write_reqs));
345 
346     trace_qed_need_check_timer_cb(s);
347 
348     qed_acquire(s);
349     qed_plug_allocating_write_reqs(s);
350 
351     /* Ensure writes are on disk before clearing flag */
352     bdrv_aio_flush(s->bs->file->bs, qed_clear_need_check, s);
353     qed_release(s);
354 }
355 
356 void qed_acquire(BDRVQEDState *s)
357 {
358     aio_context_acquire(bdrv_get_aio_context(s->bs));
359 }
360 
361 void qed_release(BDRVQEDState *s)
362 {
363     aio_context_release(bdrv_get_aio_context(s->bs));
364 }
365 
366 static void qed_start_need_check_timer(BDRVQEDState *s)
367 {
368     trace_qed_start_need_check_timer(s);
369 
370     /* Use QEMU_CLOCK_VIRTUAL so we don't alter the image file while suspended for
371      * migration.
372      */
373     timer_mod(s->need_check_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
374                    NANOSECONDS_PER_SECOND * QED_NEED_CHECK_TIMEOUT);
375 }
376 
377 /* It's okay to call this multiple times or when no timer is started */
378 static void qed_cancel_need_check_timer(BDRVQEDState *s)
379 {
380     trace_qed_cancel_need_check_timer(s);
381     timer_del(s->need_check_timer);
382 }
383 
384 static void bdrv_qed_detach_aio_context(BlockDriverState *bs)
385 {
386     BDRVQEDState *s = bs->opaque;
387 
388     qed_cancel_need_check_timer(s);
389     timer_free(s->need_check_timer);
390 }
391 
392 static void bdrv_qed_attach_aio_context(BlockDriverState *bs,
393                                         AioContext *new_context)
394 {
395     BDRVQEDState *s = bs->opaque;
396 
397     s->need_check_timer = aio_timer_new(new_context,
398                                         QEMU_CLOCK_VIRTUAL, SCALE_NS,
399                                         qed_need_check_timer_cb, s);
400     if (s->header.features & QED_F_NEED_CHECK) {
401         qed_start_need_check_timer(s);
402     }
403 }
404 
405 static void bdrv_qed_drain(BlockDriverState *bs)
406 {
407     BDRVQEDState *s = bs->opaque;
408 
409     /* Fire the timer immediately in order to start doing I/O as soon as the
410      * header is flushed.
411      */
412     if (s->need_check_timer && timer_pending(s->need_check_timer)) {
413         qed_cancel_need_check_timer(s);
414         qed_need_check_timer_cb(s);
415     }
416 }
417 
418 static int bdrv_qed_do_open(BlockDriverState *bs, QDict *options, int flags,
419                             Error **errp)
420 {
421     BDRVQEDState *s = bs->opaque;
422     QEDHeader le_header;
423     int64_t file_size;
424     int ret;
425 
426     s->bs = bs;
427     QSIMPLEQ_INIT(&s->allocating_write_reqs);
428 
429     ret = bdrv_pread(bs->file, 0, &le_header, sizeof(le_header));
430     if (ret < 0) {
431         return ret;
432     }
433     qed_header_le_to_cpu(&le_header, &s->header);
434 
435     if (s->header.magic != QED_MAGIC) {
436         error_setg(errp, "Image not in QED format");
437         return -EINVAL;
438     }
439     if (s->header.features & ~QED_FEATURE_MASK) {
440         /* image uses unsupported feature bits */
441         error_setg(errp, "Unsupported QED features: %" PRIx64,
442                    s->header.features & ~QED_FEATURE_MASK);
443         return -ENOTSUP;
444     }
445     if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
446         return -EINVAL;
447     }
448 
449     /* Round down file size to the last cluster */
450     file_size = bdrv_getlength(bs->file->bs);
451     if (file_size < 0) {
452         return file_size;
453     }
454     s->file_size = qed_start_of_cluster(s, file_size);
455 
456     if (!qed_is_table_size_valid(s->header.table_size)) {
457         return -EINVAL;
458     }
459     if (!qed_is_image_size_valid(s->header.image_size,
460                                  s->header.cluster_size,
461                                  s->header.table_size)) {
462         return -EINVAL;
463     }
464     if (!qed_check_table_offset(s, s->header.l1_table_offset)) {
465         return -EINVAL;
466     }
467 
468     s->table_nelems = (s->header.cluster_size * s->header.table_size) /
469                       sizeof(uint64_t);
470     s->l2_shift = ctz32(s->header.cluster_size);
471     s->l2_mask = s->table_nelems - 1;
472     s->l1_shift = s->l2_shift + ctz32(s->table_nelems);
473 
474     /* Header size calculation must not overflow uint32_t */
475     if (s->header.header_size > UINT32_MAX / s->header.cluster_size) {
476         return -EINVAL;
477     }
478 
479     if ((s->header.features & QED_F_BACKING_FILE)) {
480         if ((uint64_t)s->header.backing_filename_offset +
481             s->header.backing_filename_size >
482             s->header.cluster_size * s->header.header_size) {
483             return -EINVAL;
484         }
485 
486         ret = qed_read_string(bs->file, s->header.backing_filename_offset,
487                               s->header.backing_filename_size, bs->backing_file,
488                               sizeof(bs->backing_file));
489         if (ret < 0) {
490             return ret;
491         }
492 
493         if (s->header.features & QED_F_BACKING_FORMAT_NO_PROBE) {
494             pstrcpy(bs->backing_format, sizeof(bs->backing_format), "raw");
495         }
496     }
497 
498     /* Reset unknown autoclear feature bits.  This is a backwards
499      * compatibility mechanism that allows images to be opened by older
500      * programs, which "knock out" unknown feature bits.  When an image is
501      * opened by a newer program again it can detect that the autoclear
502      * feature is no longer valid.
503      */
504     if ((s->header.autoclear_features & ~QED_AUTOCLEAR_FEATURE_MASK) != 0 &&
505         !bdrv_is_read_only(bs->file->bs) && !(flags & BDRV_O_INACTIVE)) {
506         s->header.autoclear_features &= QED_AUTOCLEAR_FEATURE_MASK;
507 
508         ret = qed_write_header_sync(s);
509         if (ret) {
510             return ret;
511         }
512 
513         /* From here on only known autoclear feature bits are valid */
514         bdrv_flush(bs->file->bs);
515     }
516 
517     s->l1_table = qed_alloc_table(s);
518     qed_init_l2_cache(&s->l2_cache);
519 
520     ret = qed_read_l1_table_sync(s);
521     if (ret) {
522         goto out;
523     }
524 
525     /* If image was not closed cleanly, check consistency */
526     if (!(flags & BDRV_O_CHECK) && (s->header.features & QED_F_NEED_CHECK)) {
527         /* Read-only images cannot be fixed.  There is no risk of corruption
528          * since write operations are not possible.  Therefore, allow
529          * potentially inconsistent images to be opened read-only.  This can
530          * aid data recovery from an otherwise inconsistent image.
531          */
532         if (!bdrv_is_read_only(bs->file->bs) &&
533             !(flags & BDRV_O_INACTIVE)) {
534             BdrvCheckResult result = {0};
535 
536             ret = qed_check(s, &result, true);
537             if (ret) {
538                 goto out;
539             }
540         }
541     }
542 
543     bdrv_qed_attach_aio_context(bs, bdrv_get_aio_context(bs));
544 
545 out:
546     if (ret) {
547         qed_free_l2_cache(&s->l2_cache);
548         qemu_vfree(s->l1_table);
549     }
550     return ret;
551 }
552 
553 static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
554                          Error **errp)
555 {
556     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
557                                false, errp);
558     if (!bs->file) {
559         return -EINVAL;
560     }
561 
562     return bdrv_qed_do_open(bs, options, flags, errp);
563 }
564 
565 static void bdrv_qed_refresh_limits(BlockDriverState *bs, Error **errp)
566 {
567     BDRVQEDState *s = bs->opaque;
568 
569     bs->bl.pwrite_zeroes_alignment = s->header.cluster_size;
570 }
571 
572 /* We have nothing to do for QED reopen, stubs just return
573  * success */
574 static int bdrv_qed_reopen_prepare(BDRVReopenState *state,
575                                    BlockReopenQueue *queue, Error **errp)
576 {
577     return 0;
578 }
579 
580 static void bdrv_qed_close(BlockDriverState *bs)
581 {
582     BDRVQEDState *s = bs->opaque;
583 
584     bdrv_qed_detach_aio_context(bs);
585 
586     /* Ensure writes reach stable storage */
587     bdrv_flush(bs->file->bs);
588 
589     /* Clean shutdown, no check required on next open */
590     if (s->header.features & QED_F_NEED_CHECK) {
591         s->header.features &= ~QED_F_NEED_CHECK;
592         qed_write_header_sync(s);
593     }
594 
595     qed_free_l2_cache(&s->l2_cache);
596     qemu_vfree(s->l1_table);
597 }
598 
599 static int qed_create(const char *filename, uint32_t cluster_size,
600                       uint64_t image_size, uint32_t table_size,
601                       const char *backing_file, const char *backing_fmt,
602                       QemuOpts *opts, Error **errp)
603 {
604     QEDHeader header = {
605         .magic = QED_MAGIC,
606         .cluster_size = cluster_size,
607         .table_size = table_size,
608         .header_size = 1,
609         .features = 0,
610         .compat_features = 0,
611         .l1_table_offset = cluster_size,
612         .image_size = image_size,
613     };
614     QEDHeader le_header;
615     uint8_t *l1_table = NULL;
616     size_t l1_size = header.cluster_size * header.table_size;
617     Error *local_err = NULL;
618     int ret = 0;
619     BlockBackend *blk;
620 
621     ret = bdrv_create_file(filename, opts, &local_err);
622     if (ret < 0) {
623         error_propagate(errp, local_err);
624         return ret;
625     }
626 
627     blk = blk_new_open(filename, NULL, NULL,
628                        BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
629     if (blk == NULL) {
630         error_propagate(errp, local_err);
631         return -EIO;
632     }
633 
634     blk_set_allow_write_beyond_eof(blk, true);
635 
636     /* File must start empty and grow, check truncate is supported */
637     ret = blk_truncate(blk, 0);
638     if (ret < 0) {
639         goto out;
640     }
641 
642     if (backing_file) {
643         header.features |= QED_F_BACKING_FILE;
644         header.backing_filename_offset = sizeof(le_header);
645         header.backing_filename_size = strlen(backing_file);
646 
647         if (qed_fmt_is_raw(backing_fmt)) {
648             header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
649         }
650     }
651 
652     qed_header_cpu_to_le(&header, &le_header);
653     ret = blk_pwrite(blk, 0, &le_header, sizeof(le_header), 0);
654     if (ret < 0) {
655         goto out;
656     }
657     ret = blk_pwrite(blk, sizeof(le_header), backing_file,
658                      header.backing_filename_size, 0);
659     if (ret < 0) {
660         goto out;
661     }
662 
663     l1_table = g_malloc0(l1_size);
664     ret = blk_pwrite(blk, header.l1_table_offset, l1_table, l1_size, 0);
665     if (ret < 0) {
666         goto out;
667     }
668 
669     ret = 0; /* success */
670 out:
671     g_free(l1_table);
672     blk_unref(blk);
673     return ret;
674 }
675 
676 static int bdrv_qed_create(const char *filename, QemuOpts *opts, Error **errp)
677 {
678     uint64_t image_size = 0;
679     uint32_t cluster_size = QED_DEFAULT_CLUSTER_SIZE;
680     uint32_t table_size = QED_DEFAULT_TABLE_SIZE;
681     char *backing_file = NULL;
682     char *backing_fmt = NULL;
683     int ret;
684 
685     image_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
686                           BDRV_SECTOR_SIZE);
687     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
688     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
689     cluster_size = qemu_opt_get_size_del(opts,
690                                          BLOCK_OPT_CLUSTER_SIZE,
691                                          QED_DEFAULT_CLUSTER_SIZE);
692     table_size = qemu_opt_get_size_del(opts, BLOCK_OPT_TABLE_SIZE,
693                                        QED_DEFAULT_TABLE_SIZE);
694 
695     if (!qed_is_cluster_size_valid(cluster_size)) {
696         error_setg(errp, "QED cluster size must be within range [%u, %u] "
697                          "and power of 2",
698                    QED_MIN_CLUSTER_SIZE, QED_MAX_CLUSTER_SIZE);
699         ret = -EINVAL;
700         goto finish;
701     }
702     if (!qed_is_table_size_valid(table_size)) {
703         error_setg(errp, "QED table size must be within range [%u, %u] "
704                          "and power of 2",
705                    QED_MIN_TABLE_SIZE, QED_MAX_TABLE_SIZE);
706         ret = -EINVAL;
707         goto finish;
708     }
709     if (!qed_is_image_size_valid(image_size, cluster_size, table_size)) {
710         error_setg(errp, "QED image size must be a non-zero multiple of "
711                          "cluster size and less than %" PRIu64 " bytes",
712                    qed_max_image_size(cluster_size, table_size));
713         ret = -EINVAL;
714         goto finish;
715     }
716 
717     ret = qed_create(filename, cluster_size, image_size, table_size,
718                      backing_file, backing_fmt, opts, errp);
719 
720 finish:
721     g_free(backing_file);
722     g_free(backing_fmt);
723     return ret;
724 }
725 
726 typedef struct {
727     BlockDriverState *bs;
728     Coroutine *co;
729     uint64_t pos;
730     int64_t status;
731     int *pnum;
732     BlockDriverState **file;
733 } QEDIsAllocatedCB;
734 
735 static void qed_is_allocated_cb(void *opaque, int ret, uint64_t offset, size_t len)
736 {
737     QEDIsAllocatedCB *cb = opaque;
738     BDRVQEDState *s = cb->bs->opaque;
739     *cb->pnum = len / BDRV_SECTOR_SIZE;
740     switch (ret) {
741     case QED_CLUSTER_FOUND:
742         offset |= qed_offset_into_cluster(s, cb->pos);
743         cb->status = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
744         *cb->file = cb->bs->file->bs;
745         break;
746     case QED_CLUSTER_ZERO:
747         cb->status = BDRV_BLOCK_ZERO;
748         break;
749     case QED_CLUSTER_L2:
750     case QED_CLUSTER_L1:
751         cb->status = 0;
752         break;
753     default:
754         assert(ret < 0);
755         cb->status = ret;
756         break;
757     }
758 
759     if (cb->co) {
760         aio_co_wake(cb->co);
761     }
762 }
763 
764 static int64_t coroutine_fn bdrv_qed_co_get_block_status(BlockDriverState *bs,
765                                                  int64_t sector_num,
766                                                  int nb_sectors, int *pnum,
767                                                  BlockDriverState **file)
768 {
769     BDRVQEDState *s = bs->opaque;
770     size_t len = (size_t)nb_sectors * BDRV_SECTOR_SIZE;
771     QEDIsAllocatedCB cb = {
772         .bs = bs,
773         .pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE,
774         .status = BDRV_BLOCK_OFFSET_MASK,
775         .pnum = pnum,
776         .file = file,
777     };
778     QEDRequest request = { .l2_table = NULL };
779 
780     qed_find_cluster(s, &request, cb.pos, len, qed_is_allocated_cb, &cb);
781 
782     /* Now sleep if the callback wasn't invoked immediately */
783     while (cb.status == BDRV_BLOCK_OFFSET_MASK) {
784         cb.co = qemu_coroutine_self();
785         qemu_coroutine_yield();
786     }
787 
788     qed_unref_l2_cache_entry(request.l2_table);
789 
790     return cb.status;
791 }
792 
793 static BDRVQEDState *acb_to_s(QEDAIOCB *acb)
794 {
795     return acb->common.bs->opaque;
796 }
797 
798 /**
799  * Read from the backing file or zero-fill if no backing file
800  *
801  * @s:              QED state
802  * @pos:            Byte position in device
803  * @qiov:           Destination I/O vector
804  * @backing_qiov:   Possibly shortened copy of qiov, to be allocated here
805  * @cb:             Completion function
806  * @opaque:         User data for completion function
807  *
808  * This function reads qiov->size bytes starting at pos from the backing file.
809  * If there is no backing file then zeroes are read.
810  */
811 static void qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
812                                   QEMUIOVector *qiov,
813                                   QEMUIOVector **backing_qiov,
814                                   BlockCompletionFunc *cb, void *opaque)
815 {
816     uint64_t backing_length = 0;
817     size_t size;
818 
819     /* If there is a backing file, get its length.  Treat the absence of a
820      * backing file like a zero length backing file.
821      */
822     if (s->bs->backing) {
823         int64_t l = bdrv_getlength(s->bs->backing->bs);
824         if (l < 0) {
825             cb(opaque, l);
826             return;
827         }
828         backing_length = l;
829     }
830 
831     /* Zero all sectors if reading beyond the end of the backing file */
832     if (pos >= backing_length ||
833         pos + qiov->size > backing_length) {
834         qemu_iovec_memset(qiov, 0, 0, qiov->size);
835     }
836 
837     /* Complete now if there are no backing file sectors to read */
838     if (pos >= backing_length) {
839         cb(opaque, 0);
840         return;
841     }
842 
843     /* If the read straddles the end of the backing file, shorten it */
844     size = MIN((uint64_t)backing_length - pos, qiov->size);
845 
846     assert(*backing_qiov == NULL);
847     *backing_qiov = g_new(QEMUIOVector, 1);
848     qemu_iovec_init(*backing_qiov, qiov->niov);
849     qemu_iovec_concat(*backing_qiov, qiov, 0, size);
850 
851     BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);
852     bdrv_aio_readv(s->bs->backing, pos / BDRV_SECTOR_SIZE,
853                    *backing_qiov, size / BDRV_SECTOR_SIZE, cb, opaque);
854 }
855 
856 typedef struct {
857     GenericCB gencb;
858     BDRVQEDState *s;
859     QEMUIOVector qiov;
860     QEMUIOVector *backing_qiov;
861     struct iovec iov;
862     uint64_t offset;
863 } CopyFromBackingFileCB;
864 
865 static void qed_copy_from_backing_file_cb(void *opaque, int ret)
866 {
867     CopyFromBackingFileCB *copy_cb = opaque;
868     qemu_vfree(copy_cb->iov.iov_base);
869     gencb_complete(&copy_cb->gencb, ret);
870 }
871 
872 static void qed_copy_from_backing_file_write(void *opaque, int ret)
873 {
874     CopyFromBackingFileCB *copy_cb = opaque;
875     BDRVQEDState *s = copy_cb->s;
876 
877     if (copy_cb->backing_qiov) {
878         qemu_iovec_destroy(copy_cb->backing_qiov);
879         g_free(copy_cb->backing_qiov);
880         copy_cb->backing_qiov = NULL;
881     }
882 
883     if (ret) {
884         qed_copy_from_backing_file_cb(copy_cb, ret);
885         return;
886     }
887 
888     BLKDBG_EVENT(s->bs->file, BLKDBG_COW_WRITE);
889     bdrv_aio_writev(s->bs->file, copy_cb->offset / BDRV_SECTOR_SIZE,
890                     &copy_cb->qiov, copy_cb->qiov.size / BDRV_SECTOR_SIZE,
891                     qed_copy_from_backing_file_cb, copy_cb);
892 }
893 
894 /**
895  * Copy data from backing file into the image
896  *
897  * @s:          QED state
898  * @pos:        Byte position in device
899  * @len:        Number of bytes
900  * @offset:     Byte offset in image file
901  * @cb:         Completion function
902  * @opaque:     User data for completion function
903  */
904 static void qed_copy_from_backing_file(BDRVQEDState *s, uint64_t pos,
905                                        uint64_t len, uint64_t offset,
906                                        BlockCompletionFunc *cb,
907                                        void *opaque)
908 {
909     CopyFromBackingFileCB *copy_cb;
910 
911     /* Skip copy entirely if there is no work to do */
912     if (len == 0) {
913         cb(opaque, 0);
914         return;
915     }
916 
917     copy_cb = gencb_alloc(sizeof(*copy_cb), cb, opaque);
918     copy_cb->s = s;
919     copy_cb->offset = offset;
920     copy_cb->backing_qiov = NULL;
921     copy_cb->iov.iov_base = qemu_blockalign(s->bs, len);
922     copy_cb->iov.iov_len = len;
923     qemu_iovec_init_external(&copy_cb->qiov, &copy_cb->iov, 1);
924 
925     qed_read_backing_file(s, pos, &copy_cb->qiov, &copy_cb->backing_qiov,
926                           qed_copy_from_backing_file_write, copy_cb);
927 }
928 
929 /**
930  * Link one or more contiguous clusters into a table
931  *
932  * @s:              QED state
933  * @table:          L2 table
934  * @index:          First cluster index
935  * @n:              Number of contiguous clusters
936  * @cluster:        First cluster offset
937  *
938  * The cluster offset may be an allocated byte offset in the image file, the
939  * zero cluster marker, or the unallocated cluster marker.
940  */
941 static void qed_update_l2_table(BDRVQEDState *s, QEDTable *table, int index,
942                                 unsigned int n, uint64_t cluster)
943 {
944     int i;
945     for (i = index; i < index + n; i++) {
946         table->offsets[i] = cluster;
947         if (!qed_offset_is_unalloc_cluster(cluster) &&
948             !qed_offset_is_zero_cluster(cluster)) {
949             cluster += s->header.cluster_size;
950         }
951     }
952 }
953 
954 static void qed_aio_complete_bh(void *opaque)
955 {
956     QEDAIOCB *acb = opaque;
957     BDRVQEDState *s = acb_to_s(acb);
958     BlockCompletionFunc *cb = acb->common.cb;
959     void *user_opaque = acb->common.opaque;
960     int ret = acb->bh_ret;
961 
962     qemu_aio_unref(acb);
963 
964     /* Invoke callback */
965     qed_acquire(s);
966     cb(user_opaque, ret);
967     qed_release(s);
968 }
969 
970 static void qed_aio_complete(QEDAIOCB *acb, int ret)
971 {
972     BDRVQEDState *s = acb_to_s(acb);
973 
974     trace_qed_aio_complete(s, acb, ret);
975 
976     /* Free resources */
977     qemu_iovec_destroy(&acb->cur_qiov);
978     qed_unref_l2_cache_entry(acb->request.l2_table);
979 
980     /* Free the buffer we may have allocated for zero writes */
981     if (acb->flags & QED_AIOCB_ZERO) {
982         qemu_vfree(acb->qiov->iov[0].iov_base);
983         acb->qiov->iov[0].iov_base = NULL;
984     }
985 
986     /* Arrange for a bh to invoke the completion function */
987     acb->bh_ret = ret;
988     aio_bh_schedule_oneshot(bdrv_get_aio_context(acb->common.bs),
989                             qed_aio_complete_bh, acb);
990 
991     /* Start next allocating write request waiting behind this one.  Note that
992      * requests enqueue themselves when they first hit an unallocated cluster
993      * but they wait until the entire request is finished before waking up the
994      * next request in the queue.  This ensures that we don't cycle through
995      * requests multiple times but rather finish one at a time completely.
996      */
997     if (acb == QSIMPLEQ_FIRST(&s->allocating_write_reqs)) {
998         QSIMPLEQ_REMOVE_HEAD(&s->allocating_write_reqs, next);
999         acb = QSIMPLEQ_FIRST(&s->allocating_write_reqs);
1000         if (acb) {
1001             qed_aio_start_io(acb);
1002         } else if (s->header.features & QED_F_NEED_CHECK) {
1003             qed_start_need_check_timer(s);
1004         }
1005     }
1006 }
1007 
1008 /**
1009  * Commit the current L2 table to the cache
1010  */
1011 static void qed_commit_l2_update(void *opaque, int ret)
1012 {
1013     QEDAIOCB *acb = opaque;
1014     BDRVQEDState *s = acb_to_s(acb);
1015     CachedL2Table *l2_table = acb->request.l2_table;
1016     uint64_t l2_offset = l2_table->offset;
1017 
1018     qed_commit_l2_cache_entry(&s->l2_cache, l2_table);
1019 
1020     /* This is guaranteed to succeed because we just committed the entry to the
1021      * cache.
1022      */
1023     acb->request.l2_table = qed_find_l2_cache_entry(&s->l2_cache, l2_offset);
1024     assert(acb->request.l2_table != NULL);
1025 
1026     qed_aio_next_io(acb, ret);
1027 }
1028 
1029 /**
1030  * Update L1 table with new L2 table offset and write it out
1031  */
1032 static void qed_aio_write_l1_update(void *opaque, int ret)
1033 {
1034     QEDAIOCB *acb = opaque;
1035     BDRVQEDState *s = acb_to_s(acb);
1036     int index;
1037 
1038     if (ret) {
1039         qed_aio_complete(acb, ret);
1040         return;
1041     }
1042 
1043     index = qed_l1_index(s, acb->cur_pos);
1044     s->l1_table->offsets[index] = acb->request.l2_table->offset;
1045 
1046     qed_write_l1_table(s, index, 1, qed_commit_l2_update, acb);
1047 }
1048 
1049 /**
1050  * Update L2 table with new cluster offsets and write them out
1051  */
1052 static void qed_aio_write_l2_update(QEDAIOCB *acb, int ret, uint64_t offset)
1053 {
1054     BDRVQEDState *s = acb_to_s(acb);
1055     bool need_alloc = acb->find_cluster_ret == QED_CLUSTER_L1;
1056     int index;
1057 
1058     if (ret) {
1059         goto err;
1060     }
1061 
1062     if (need_alloc) {
1063         qed_unref_l2_cache_entry(acb->request.l2_table);
1064         acb->request.l2_table = qed_new_l2_table(s);
1065     }
1066 
1067     index = qed_l2_index(s, acb->cur_pos);
1068     qed_update_l2_table(s, acb->request.l2_table->table, index, acb->cur_nclusters,
1069                          offset);
1070 
1071     if (need_alloc) {
1072         /* Write out the whole new L2 table */
1073         qed_write_l2_table(s, &acb->request, 0, s->table_nelems, true,
1074                            qed_aio_write_l1_update, acb);
1075     } else {
1076         /* Write out only the updated part of the L2 table */
1077         qed_write_l2_table(s, &acb->request, index, acb->cur_nclusters, false,
1078                            qed_aio_next_io_cb, acb);
1079     }
1080     return;
1081 
1082 err:
1083     qed_aio_complete(acb, ret);
1084 }
1085 
1086 static void qed_aio_write_l2_update_cb(void *opaque, int ret)
1087 {
1088     QEDAIOCB *acb = opaque;
1089     qed_aio_write_l2_update(acb, ret, acb->cur_cluster);
1090 }
1091 
1092 /**
1093  * Flush new data clusters before updating the L2 table
1094  *
1095  * This flush is necessary when a backing file is in use.  A crash during an
1096  * allocating write could result in empty clusters in the image.  If the write
1097  * only touched a subregion of the cluster, then backing image sectors have
1098  * been lost in the untouched region.  The solution is to flush after writing a
1099  * new data cluster and before updating the L2 table.
1100  */
1101 static void qed_aio_write_flush_before_l2_update(void *opaque, int ret)
1102 {
1103     QEDAIOCB *acb = opaque;
1104     BDRVQEDState *s = acb_to_s(acb);
1105 
1106     if (!bdrv_aio_flush(s->bs->file->bs, qed_aio_write_l2_update_cb, opaque)) {
1107         qed_aio_complete(acb, -EIO);
1108     }
1109 }
1110 
1111 /**
1112  * Write data to the image file
1113  */
1114 static void qed_aio_write_main(void *opaque, int ret)
1115 {
1116     QEDAIOCB *acb = opaque;
1117     BDRVQEDState *s = acb_to_s(acb);
1118     uint64_t offset = acb->cur_cluster +
1119                       qed_offset_into_cluster(s, acb->cur_pos);
1120     BlockCompletionFunc *next_fn;
1121 
1122     trace_qed_aio_write_main(s, acb, ret, offset, acb->cur_qiov.size);
1123 
1124     if (ret) {
1125         qed_aio_complete(acb, ret);
1126         return;
1127     }
1128 
1129     if (acb->find_cluster_ret == QED_CLUSTER_FOUND) {
1130         next_fn = qed_aio_next_io_cb;
1131     } else {
1132         if (s->bs->backing) {
1133             next_fn = qed_aio_write_flush_before_l2_update;
1134         } else {
1135             next_fn = qed_aio_write_l2_update_cb;
1136         }
1137     }
1138 
1139     BLKDBG_EVENT(s->bs->file, BLKDBG_WRITE_AIO);
1140     bdrv_aio_writev(s->bs->file, offset / BDRV_SECTOR_SIZE,
1141                     &acb->cur_qiov, acb->cur_qiov.size / BDRV_SECTOR_SIZE,
1142                     next_fn, acb);
1143 }
1144 
1145 /**
1146  * Populate back untouched region of new data cluster
1147  */
1148 static void qed_aio_write_postfill(void *opaque, int ret)
1149 {
1150     QEDAIOCB *acb = opaque;
1151     BDRVQEDState *s = acb_to_s(acb);
1152     uint64_t start = acb->cur_pos + acb->cur_qiov.size;
1153     uint64_t len =
1154         qed_start_of_cluster(s, start + s->header.cluster_size - 1) - start;
1155     uint64_t offset = acb->cur_cluster +
1156                       qed_offset_into_cluster(s, acb->cur_pos) +
1157                       acb->cur_qiov.size;
1158 
1159     if (ret) {
1160         qed_aio_complete(acb, ret);
1161         return;
1162     }
1163 
1164     trace_qed_aio_write_postfill(s, acb, start, len, offset);
1165     qed_copy_from_backing_file(s, start, len, offset,
1166                                 qed_aio_write_main, acb);
1167 }
1168 
1169 /**
1170  * Populate front untouched region of new data cluster
1171  */
1172 static void qed_aio_write_prefill(void *opaque, int ret)
1173 {
1174     QEDAIOCB *acb = opaque;
1175     BDRVQEDState *s = acb_to_s(acb);
1176     uint64_t start = qed_start_of_cluster(s, acb->cur_pos);
1177     uint64_t len = qed_offset_into_cluster(s, acb->cur_pos);
1178 
1179     trace_qed_aio_write_prefill(s, acb, start, len, acb->cur_cluster);
1180     qed_copy_from_backing_file(s, start, len, acb->cur_cluster,
1181                                 qed_aio_write_postfill, acb);
1182 }
1183 
1184 /**
1185  * Check if the QED_F_NEED_CHECK bit should be set during allocating write
1186  */
1187 static bool qed_should_set_need_check(BDRVQEDState *s)
1188 {
1189     /* The flush before L2 update path ensures consistency */
1190     if (s->bs->backing) {
1191         return false;
1192     }
1193 
1194     return !(s->header.features & QED_F_NEED_CHECK);
1195 }
1196 
1197 static void qed_aio_write_zero_cluster(void *opaque, int ret)
1198 {
1199     QEDAIOCB *acb = opaque;
1200 
1201     if (ret) {
1202         qed_aio_complete(acb, ret);
1203         return;
1204     }
1205 
1206     qed_aio_write_l2_update(acb, 0, 1);
1207 }
1208 
1209 /**
1210  * Write new data cluster
1211  *
1212  * @acb:        Write request
1213  * @len:        Length in bytes
1214  *
1215  * This path is taken when writing to previously unallocated clusters.
1216  */
1217 static void qed_aio_write_alloc(QEDAIOCB *acb, size_t len)
1218 {
1219     BDRVQEDState *s = acb_to_s(acb);
1220     BlockCompletionFunc *cb;
1221 
1222     /* Cancel timer when the first allocating request comes in */
1223     if (QSIMPLEQ_EMPTY(&s->allocating_write_reqs)) {
1224         qed_cancel_need_check_timer(s);
1225     }
1226 
1227     /* Freeze this request if another allocating write is in progress */
1228     if (acb != QSIMPLEQ_FIRST(&s->allocating_write_reqs)) {
1229         QSIMPLEQ_INSERT_TAIL(&s->allocating_write_reqs, acb, next);
1230     }
1231     if (acb != QSIMPLEQ_FIRST(&s->allocating_write_reqs) ||
1232         s->allocating_write_reqs_plugged) {
1233         return; /* wait for existing request to finish */
1234     }
1235 
1236     acb->cur_nclusters = qed_bytes_to_clusters(s,
1237             qed_offset_into_cluster(s, acb->cur_pos) + len);
1238     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1239 
1240     if (acb->flags & QED_AIOCB_ZERO) {
1241         /* Skip ahead if the clusters are already zero */
1242         if (acb->find_cluster_ret == QED_CLUSTER_ZERO) {
1243             qed_aio_start_io(acb);
1244             return;
1245         }
1246 
1247         cb = qed_aio_write_zero_cluster;
1248     } else {
1249         cb = qed_aio_write_prefill;
1250         acb->cur_cluster = qed_alloc_clusters(s, acb->cur_nclusters);
1251     }
1252 
1253     if (qed_should_set_need_check(s)) {
1254         s->header.features |= QED_F_NEED_CHECK;
1255         qed_write_header(s, cb, acb);
1256     } else {
1257         cb(acb, 0);
1258     }
1259 }
1260 
1261 /**
1262  * Write data cluster in place
1263  *
1264  * @acb:        Write request
1265  * @offset:     Cluster offset in bytes
1266  * @len:        Length in bytes
1267  *
1268  * This path is taken when writing to already allocated clusters.
1269  */
1270 static void qed_aio_write_inplace(QEDAIOCB *acb, uint64_t offset, size_t len)
1271 {
1272     /* Allocate buffer for zero writes */
1273     if (acb->flags & QED_AIOCB_ZERO) {
1274         struct iovec *iov = acb->qiov->iov;
1275 
1276         if (!iov->iov_base) {
1277             iov->iov_base = qemu_try_blockalign(acb->common.bs, iov->iov_len);
1278             if (iov->iov_base == NULL) {
1279                 qed_aio_complete(acb, -ENOMEM);
1280                 return;
1281             }
1282             memset(iov->iov_base, 0, iov->iov_len);
1283         }
1284     }
1285 
1286     /* Calculate the I/O vector */
1287     acb->cur_cluster = offset;
1288     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1289 
1290     /* Do the actual write */
1291     qed_aio_write_main(acb, 0);
1292 }
1293 
1294 /**
1295  * Write data cluster
1296  *
1297  * @opaque:     Write request
1298  * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2, QED_CLUSTER_L1,
1299  *              or -errno
1300  * @offset:     Cluster offset in bytes
1301  * @len:        Length in bytes
1302  *
1303  * Callback from qed_find_cluster().
1304  */
1305 static void qed_aio_write_data(void *opaque, int ret,
1306                                uint64_t offset, size_t len)
1307 {
1308     QEDAIOCB *acb = opaque;
1309 
1310     trace_qed_aio_write_data(acb_to_s(acb), acb, ret, offset, len);
1311 
1312     acb->find_cluster_ret = ret;
1313 
1314     switch (ret) {
1315     case QED_CLUSTER_FOUND:
1316         qed_aio_write_inplace(acb, offset, len);
1317         break;
1318 
1319     case QED_CLUSTER_L2:
1320     case QED_CLUSTER_L1:
1321     case QED_CLUSTER_ZERO:
1322         qed_aio_write_alloc(acb, len);
1323         break;
1324 
1325     default:
1326         qed_aio_complete(acb, ret);
1327         break;
1328     }
1329 }
1330 
1331 /**
1332  * Read data cluster
1333  *
1334  * @opaque:     Read request
1335  * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2, QED_CLUSTER_L1,
1336  *              or -errno
1337  * @offset:     Cluster offset in bytes
1338  * @len:        Length in bytes
1339  *
1340  * Callback from qed_find_cluster().
1341  */
1342 static void qed_aio_read_data(void *opaque, int ret,
1343                               uint64_t offset, size_t len)
1344 {
1345     QEDAIOCB *acb = opaque;
1346     BDRVQEDState *s = acb_to_s(acb);
1347     BlockDriverState *bs = acb->common.bs;
1348 
1349     /* Adjust offset into cluster */
1350     offset += qed_offset_into_cluster(s, acb->cur_pos);
1351 
1352     trace_qed_aio_read_data(s, acb, ret, offset, len);
1353 
1354     if (ret < 0) {
1355         goto err;
1356     }
1357 
1358     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1359 
1360     /* Handle zero cluster and backing file reads */
1361     if (ret == QED_CLUSTER_ZERO) {
1362         qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
1363         qed_aio_start_io(acb);
1364         return;
1365     } else if (ret != QED_CLUSTER_FOUND) {
1366         qed_read_backing_file(s, acb->cur_pos, &acb->cur_qiov,
1367                               &acb->backing_qiov, qed_aio_next_io_cb, acb);
1368         return;
1369     }
1370 
1371     BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1372     bdrv_aio_readv(bs->file, offset / BDRV_SECTOR_SIZE,
1373                    &acb->cur_qiov, acb->cur_qiov.size / BDRV_SECTOR_SIZE,
1374                    qed_aio_next_io_cb, acb);
1375     return;
1376 
1377 err:
1378     qed_aio_complete(acb, ret);
1379 }
1380 
1381 /**
1382  * Begin next I/O or complete the request
1383  */
1384 static void qed_aio_next_io(QEDAIOCB *acb, int ret)
1385 {
1386     BDRVQEDState *s = acb_to_s(acb);
1387     QEDFindClusterFunc *io_fn = (acb->flags & QED_AIOCB_WRITE) ?
1388                                 qed_aio_write_data : qed_aio_read_data;
1389 
1390     trace_qed_aio_next_io(s, acb, ret, acb->cur_pos + acb->cur_qiov.size);
1391 
1392     if (acb->backing_qiov) {
1393         qemu_iovec_destroy(acb->backing_qiov);
1394         g_free(acb->backing_qiov);
1395         acb->backing_qiov = NULL;
1396     }
1397 
1398     /* Handle I/O error */
1399     if (ret) {
1400         qed_aio_complete(acb, ret);
1401         return;
1402     }
1403 
1404     acb->qiov_offset += acb->cur_qiov.size;
1405     acb->cur_pos += acb->cur_qiov.size;
1406     qemu_iovec_reset(&acb->cur_qiov);
1407 
1408     /* Complete request */
1409     if (acb->cur_pos >= acb->end_pos) {
1410         qed_aio_complete(acb, 0);
1411         return;
1412     }
1413 
1414     /* Find next cluster and start I/O */
1415     qed_find_cluster(s, &acb->request,
1416                       acb->cur_pos, acb->end_pos - acb->cur_pos,
1417                       io_fn, acb);
1418 }
1419 
1420 static BlockAIOCB *qed_aio_setup(BlockDriverState *bs,
1421                                  int64_t sector_num,
1422                                  QEMUIOVector *qiov, int nb_sectors,
1423                                  BlockCompletionFunc *cb,
1424                                  void *opaque, int flags)
1425 {
1426     QEDAIOCB *acb = qemu_aio_get(&qed_aiocb_info, bs, cb, opaque);
1427 
1428     trace_qed_aio_setup(bs->opaque, acb, sector_num, nb_sectors,
1429                         opaque, flags);
1430 
1431     acb->flags = flags;
1432     acb->qiov = qiov;
1433     acb->qiov_offset = 0;
1434     acb->cur_pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE;
1435     acb->end_pos = acb->cur_pos + nb_sectors * BDRV_SECTOR_SIZE;
1436     acb->backing_qiov = NULL;
1437     acb->request.l2_table = NULL;
1438     qemu_iovec_init(&acb->cur_qiov, qiov->niov);
1439 
1440     /* Start request */
1441     qed_aio_start_io(acb);
1442     return &acb->common;
1443 }
1444 
1445 static BlockAIOCB *bdrv_qed_aio_readv(BlockDriverState *bs,
1446                                       int64_t sector_num,
1447                                       QEMUIOVector *qiov, int nb_sectors,
1448                                       BlockCompletionFunc *cb,
1449                                       void *opaque)
1450 {
1451     return qed_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1452 }
1453 
1454 static BlockAIOCB *bdrv_qed_aio_writev(BlockDriverState *bs,
1455                                        int64_t sector_num,
1456                                        QEMUIOVector *qiov, int nb_sectors,
1457                                        BlockCompletionFunc *cb,
1458                                        void *opaque)
1459 {
1460     return qed_aio_setup(bs, sector_num, qiov, nb_sectors, cb,
1461                          opaque, QED_AIOCB_WRITE);
1462 }
1463 
1464 typedef struct {
1465     Coroutine *co;
1466     int ret;
1467     bool done;
1468 } QEDWriteZeroesCB;
1469 
1470 static void coroutine_fn qed_co_pwrite_zeroes_cb(void *opaque, int ret)
1471 {
1472     QEDWriteZeroesCB *cb = opaque;
1473 
1474     cb->done = true;
1475     cb->ret = ret;
1476     if (cb->co) {
1477         aio_co_wake(cb->co);
1478     }
1479 }
1480 
1481 static int coroutine_fn bdrv_qed_co_pwrite_zeroes(BlockDriverState *bs,
1482                                                   int64_t offset,
1483                                                   int count,
1484                                                   BdrvRequestFlags flags)
1485 {
1486     BlockAIOCB *blockacb;
1487     BDRVQEDState *s = bs->opaque;
1488     QEDWriteZeroesCB cb = { .done = false };
1489     QEMUIOVector qiov;
1490     struct iovec iov;
1491 
1492     /* Fall back if the request is not aligned */
1493     if (qed_offset_into_cluster(s, offset) ||
1494         qed_offset_into_cluster(s, count)) {
1495         return -ENOTSUP;
1496     }
1497 
1498     /* Zero writes start without an I/O buffer.  If a buffer becomes necessary
1499      * then it will be allocated during request processing.
1500      */
1501     iov.iov_base = NULL;
1502     iov.iov_len = count;
1503 
1504     qemu_iovec_init_external(&qiov, &iov, 1);
1505     blockacb = qed_aio_setup(bs, offset >> BDRV_SECTOR_BITS, &qiov,
1506                              count >> BDRV_SECTOR_BITS,
1507                              qed_co_pwrite_zeroes_cb, &cb,
1508                              QED_AIOCB_WRITE | QED_AIOCB_ZERO);
1509     if (!blockacb) {
1510         return -EIO;
1511     }
1512     if (!cb.done) {
1513         cb.co = qemu_coroutine_self();
1514         qemu_coroutine_yield();
1515     }
1516     assert(cb.done);
1517     return cb.ret;
1518 }
1519 
1520 static int bdrv_qed_truncate(BlockDriverState *bs, int64_t offset)
1521 {
1522     BDRVQEDState *s = bs->opaque;
1523     uint64_t old_image_size;
1524     int ret;
1525 
1526     if (!qed_is_image_size_valid(offset, s->header.cluster_size,
1527                                  s->header.table_size)) {
1528         return -EINVAL;
1529     }
1530 
1531     /* Shrinking is currently not supported */
1532     if ((uint64_t)offset < s->header.image_size) {
1533         return -ENOTSUP;
1534     }
1535 
1536     old_image_size = s->header.image_size;
1537     s->header.image_size = offset;
1538     ret = qed_write_header_sync(s);
1539     if (ret < 0) {
1540         s->header.image_size = old_image_size;
1541     }
1542     return ret;
1543 }
1544 
1545 static int64_t bdrv_qed_getlength(BlockDriverState *bs)
1546 {
1547     BDRVQEDState *s = bs->opaque;
1548     return s->header.image_size;
1549 }
1550 
1551 static int bdrv_qed_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1552 {
1553     BDRVQEDState *s = bs->opaque;
1554 
1555     memset(bdi, 0, sizeof(*bdi));
1556     bdi->cluster_size = s->header.cluster_size;
1557     bdi->is_dirty = s->header.features & QED_F_NEED_CHECK;
1558     bdi->unallocated_blocks_are_zero = true;
1559     bdi->can_write_zeroes_with_unmap = true;
1560     return 0;
1561 }
1562 
1563 static int bdrv_qed_change_backing_file(BlockDriverState *bs,
1564                                         const char *backing_file,
1565                                         const char *backing_fmt)
1566 {
1567     BDRVQEDState *s = bs->opaque;
1568     QEDHeader new_header, le_header;
1569     void *buffer;
1570     size_t buffer_len, backing_file_len;
1571     int ret;
1572 
1573     /* Refuse to set backing filename if unknown compat feature bits are
1574      * active.  If the image uses an unknown compat feature then we may not
1575      * know the layout of data following the header structure and cannot safely
1576      * add a new string.
1577      */
1578     if (backing_file && (s->header.compat_features &
1579                          ~QED_COMPAT_FEATURE_MASK)) {
1580         return -ENOTSUP;
1581     }
1582 
1583     memcpy(&new_header, &s->header, sizeof(new_header));
1584 
1585     new_header.features &= ~(QED_F_BACKING_FILE |
1586                              QED_F_BACKING_FORMAT_NO_PROBE);
1587 
1588     /* Adjust feature flags */
1589     if (backing_file) {
1590         new_header.features |= QED_F_BACKING_FILE;
1591 
1592         if (qed_fmt_is_raw(backing_fmt)) {
1593             new_header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
1594         }
1595     }
1596 
1597     /* Calculate new header size */
1598     backing_file_len = 0;
1599 
1600     if (backing_file) {
1601         backing_file_len = strlen(backing_file);
1602     }
1603 
1604     buffer_len = sizeof(new_header);
1605     new_header.backing_filename_offset = buffer_len;
1606     new_header.backing_filename_size = backing_file_len;
1607     buffer_len += backing_file_len;
1608 
1609     /* Make sure we can rewrite header without failing */
1610     if (buffer_len > new_header.header_size * new_header.cluster_size) {
1611         return -ENOSPC;
1612     }
1613 
1614     /* Prepare new header */
1615     buffer = g_malloc(buffer_len);
1616 
1617     qed_header_cpu_to_le(&new_header, &le_header);
1618     memcpy(buffer, &le_header, sizeof(le_header));
1619     buffer_len = sizeof(le_header);
1620 
1621     if (backing_file) {
1622         memcpy(buffer + buffer_len, backing_file, backing_file_len);
1623         buffer_len += backing_file_len;
1624     }
1625 
1626     /* Write new header */
1627     ret = bdrv_pwrite_sync(bs->file, 0, buffer, buffer_len);
1628     g_free(buffer);
1629     if (ret == 0) {
1630         memcpy(&s->header, &new_header, sizeof(new_header));
1631     }
1632     return ret;
1633 }
1634 
1635 static void bdrv_qed_invalidate_cache(BlockDriverState *bs, Error **errp)
1636 {
1637     BDRVQEDState *s = bs->opaque;
1638     Error *local_err = NULL;
1639     int ret;
1640 
1641     bdrv_qed_close(bs);
1642 
1643     memset(s, 0, sizeof(BDRVQEDState));
1644     ret = bdrv_qed_do_open(bs, NULL, bs->open_flags, &local_err);
1645     if (local_err) {
1646         error_propagate(errp, local_err);
1647         error_prepend(errp, "Could not reopen qed layer: ");
1648         return;
1649     } else if (ret < 0) {
1650         error_setg_errno(errp, -ret, "Could not reopen qed layer");
1651         return;
1652     }
1653 }
1654 
1655 static int bdrv_qed_check(BlockDriverState *bs, BdrvCheckResult *result,
1656                           BdrvCheckMode fix)
1657 {
1658     BDRVQEDState *s = bs->opaque;
1659 
1660     return qed_check(s, result, !!fix);
1661 }
1662 
1663 static QemuOptsList qed_create_opts = {
1664     .name = "qed-create-opts",
1665     .head = QTAILQ_HEAD_INITIALIZER(qed_create_opts.head),
1666     .desc = {
1667         {
1668             .name = BLOCK_OPT_SIZE,
1669             .type = QEMU_OPT_SIZE,
1670             .help = "Virtual disk size"
1671         },
1672         {
1673             .name = BLOCK_OPT_BACKING_FILE,
1674             .type = QEMU_OPT_STRING,
1675             .help = "File name of a base image"
1676         },
1677         {
1678             .name = BLOCK_OPT_BACKING_FMT,
1679             .type = QEMU_OPT_STRING,
1680             .help = "Image format of the base image"
1681         },
1682         {
1683             .name = BLOCK_OPT_CLUSTER_SIZE,
1684             .type = QEMU_OPT_SIZE,
1685             .help = "Cluster size (in bytes)",
1686             .def_value_str = stringify(QED_DEFAULT_CLUSTER_SIZE)
1687         },
1688         {
1689             .name = BLOCK_OPT_TABLE_SIZE,
1690             .type = QEMU_OPT_SIZE,
1691             .help = "L1/L2 table size (in clusters)"
1692         },
1693         { /* end of list */ }
1694     }
1695 };
1696 
1697 static BlockDriver bdrv_qed = {
1698     .format_name              = "qed",
1699     .instance_size            = sizeof(BDRVQEDState),
1700     .create_opts              = &qed_create_opts,
1701     .supports_backing         = true,
1702 
1703     .bdrv_probe               = bdrv_qed_probe,
1704     .bdrv_open                = bdrv_qed_open,
1705     .bdrv_close               = bdrv_qed_close,
1706     .bdrv_reopen_prepare      = bdrv_qed_reopen_prepare,
1707     .bdrv_create              = bdrv_qed_create,
1708     .bdrv_has_zero_init       = bdrv_has_zero_init_1,
1709     .bdrv_co_get_block_status = bdrv_qed_co_get_block_status,
1710     .bdrv_aio_readv           = bdrv_qed_aio_readv,
1711     .bdrv_aio_writev          = bdrv_qed_aio_writev,
1712     .bdrv_co_pwrite_zeroes    = bdrv_qed_co_pwrite_zeroes,
1713     .bdrv_truncate            = bdrv_qed_truncate,
1714     .bdrv_getlength           = bdrv_qed_getlength,
1715     .bdrv_get_info            = bdrv_qed_get_info,
1716     .bdrv_refresh_limits      = bdrv_qed_refresh_limits,
1717     .bdrv_change_backing_file = bdrv_qed_change_backing_file,
1718     .bdrv_invalidate_cache    = bdrv_qed_invalidate_cache,
1719     .bdrv_check               = bdrv_qed_check,
1720     .bdrv_detach_aio_context  = bdrv_qed_detach_aio_context,
1721     .bdrv_attach_aio_context  = bdrv_qed_attach_aio_context,
1722     .bdrv_drain               = bdrv_qed_drain,
1723 };
1724 
1725 static void bdrv_qed_init(void)
1726 {
1727     bdrv_register(&bdrv_qed);
1728 }
1729 
1730 block_init(bdrv_qed_init);
1731