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