xref: /openbmc/qemu/block/qed.c (revision b3dd1b8c)
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 void bdrv_qed_refresh_limits(BlockDriverState *bs, Error **errp)
532 {
533     BDRVQEDState *s = bs->opaque;
534 
535     bs->bl.write_zeroes_alignment = s->header.cluster_size >> BDRV_SECTOR_BITS;
536 }
537 
538 /* We have nothing to do for QED reopen, stubs just return
539  * success */
540 static int bdrv_qed_reopen_prepare(BDRVReopenState *state,
541                                    BlockReopenQueue *queue, Error **errp)
542 {
543     return 0;
544 }
545 
546 static void bdrv_qed_close(BlockDriverState *bs)
547 {
548     BDRVQEDState *s = bs->opaque;
549 
550     bdrv_qed_detach_aio_context(bs);
551 
552     /* Ensure writes reach stable storage */
553     bdrv_flush(bs->file);
554 
555     /* Clean shutdown, no check required on next open */
556     if (s->header.features & QED_F_NEED_CHECK) {
557         s->header.features &= ~QED_F_NEED_CHECK;
558         qed_write_header_sync(s);
559     }
560 
561     qed_free_l2_cache(&s->l2_cache);
562     qemu_vfree(s->l1_table);
563 }
564 
565 static int qed_create(const char *filename, uint32_t cluster_size,
566                       uint64_t image_size, uint32_t table_size,
567                       const char *backing_file, const char *backing_fmt,
568                       QemuOpts *opts, Error **errp)
569 {
570     QEDHeader header = {
571         .magic = QED_MAGIC,
572         .cluster_size = cluster_size,
573         .table_size = table_size,
574         .header_size = 1,
575         .features = 0,
576         .compat_features = 0,
577         .l1_table_offset = cluster_size,
578         .image_size = image_size,
579     };
580     QEDHeader le_header;
581     uint8_t *l1_table = NULL;
582     size_t l1_size = header.cluster_size * header.table_size;
583     Error *local_err = NULL;
584     int ret = 0;
585     BlockDriverState *bs;
586 
587     ret = bdrv_create_file(filename, opts, &local_err);
588     if (ret < 0) {
589         error_propagate(errp, local_err);
590         return ret;
591     }
592 
593     bs = NULL;
594     ret = bdrv_open(&bs, filename, NULL, NULL,
595                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_PROTOCOL, NULL,
596                     &local_err);
597     if (ret < 0) {
598         error_propagate(errp, local_err);
599         return ret;
600     }
601 
602     /* File must start empty and grow, check truncate is supported */
603     ret = bdrv_truncate(bs, 0);
604     if (ret < 0) {
605         goto out;
606     }
607 
608     if (backing_file) {
609         header.features |= QED_F_BACKING_FILE;
610         header.backing_filename_offset = sizeof(le_header);
611         header.backing_filename_size = strlen(backing_file);
612 
613         if (qed_fmt_is_raw(backing_fmt)) {
614             header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
615         }
616     }
617 
618     qed_header_cpu_to_le(&header, &le_header);
619     ret = bdrv_pwrite(bs, 0, &le_header, sizeof(le_header));
620     if (ret < 0) {
621         goto out;
622     }
623     ret = bdrv_pwrite(bs, sizeof(le_header), backing_file,
624                       header.backing_filename_size);
625     if (ret < 0) {
626         goto out;
627     }
628 
629     l1_table = g_malloc0(l1_size);
630     ret = bdrv_pwrite(bs, header.l1_table_offset, l1_table, l1_size);
631     if (ret < 0) {
632         goto out;
633     }
634 
635     ret = 0; /* success */
636 out:
637     g_free(l1_table);
638     bdrv_unref(bs);
639     return ret;
640 }
641 
642 static int bdrv_qed_create(const char *filename, QemuOpts *opts, Error **errp)
643 {
644     uint64_t image_size = 0;
645     uint32_t cluster_size = QED_DEFAULT_CLUSTER_SIZE;
646     uint32_t table_size = QED_DEFAULT_TABLE_SIZE;
647     char *backing_file = NULL;
648     char *backing_fmt = NULL;
649     int ret;
650 
651     image_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
652     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
653     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
654     cluster_size = qemu_opt_get_size_del(opts,
655                                          BLOCK_OPT_CLUSTER_SIZE,
656                                          QED_DEFAULT_CLUSTER_SIZE);
657     table_size = qemu_opt_get_size_del(opts, BLOCK_OPT_TABLE_SIZE,
658                                        QED_DEFAULT_TABLE_SIZE);
659 
660     if (!qed_is_cluster_size_valid(cluster_size)) {
661         error_setg(errp, "QED cluster size must be within range [%u, %u] "
662                          "and power of 2",
663                    QED_MIN_CLUSTER_SIZE, QED_MAX_CLUSTER_SIZE);
664         ret = -EINVAL;
665         goto finish;
666     }
667     if (!qed_is_table_size_valid(table_size)) {
668         error_setg(errp, "QED table size must be within range [%u, %u] "
669                          "and power of 2",
670                    QED_MIN_TABLE_SIZE, QED_MAX_TABLE_SIZE);
671         ret = -EINVAL;
672         goto finish;
673     }
674     if (!qed_is_image_size_valid(image_size, cluster_size, table_size)) {
675         error_setg(errp, "QED image size must be a non-zero multiple of "
676                          "cluster size and less than %" PRIu64 " bytes",
677                    qed_max_image_size(cluster_size, table_size));
678         ret = -EINVAL;
679         goto finish;
680     }
681 
682     ret = qed_create(filename, cluster_size, image_size, table_size,
683                      backing_file, backing_fmt, opts, errp);
684 
685 finish:
686     g_free(backing_file);
687     g_free(backing_fmt);
688     return ret;
689 }
690 
691 typedef struct {
692     BlockDriverState *bs;
693     Coroutine *co;
694     uint64_t pos;
695     int64_t status;
696     int *pnum;
697 } QEDIsAllocatedCB;
698 
699 static void qed_is_allocated_cb(void *opaque, int ret, uint64_t offset, size_t len)
700 {
701     QEDIsAllocatedCB *cb = opaque;
702     BDRVQEDState *s = cb->bs->opaque;
703     *cb->pnum = len / BDRV_SECTOR_SIZE;
704     switch (ret) {
705     case QED_CLUSTER_FOUND:
706         offset |= qed_offset_into_cluster(s, cb->pos);
707         cb->status = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
708         break;
709     case QED_CLUSTER_ZERO:
710         cb->status = BDRV_BLOCK_ZERO;
711         break;
712     case QED_CLUSTER_L2:
713     case QED_CLUSTER_L1:
714         cb->status = 0;
715         break;
716     default:
717         assert(ret < 0);
718         cb->status = ret;
719         break;
720     }
721 
722     if (cb->co) {
723         qemu_coroutine_enter(cb->co, NULL);
724     }
725 }
726 
727 static int64_t coroutine_fn bdrv_qed_co_get_block_status(BlockDriverState *bs,
728                                                  int64_t sector_num,
729                                                  int nb_sectors, int *pnum)
730 {
731     BDRVQEDState *s = bs->opaque;
732     size_t len = (size_t)nb_sectors * BDRV_SECTOR_SIZE;
733     QEDIsAllocatedCB cb = {
734         .bs = bs,
735         .pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE,
736         .status = BDRV_BLOCK_OFFSET_MASK,
737         .pnum = pnum,
738     };
739     QEDRequest request = { .l2_table = NULL };
740 
741     qed_find_cluster(s, &request, cb.pos, len, qed_is_allocated_cb, &cb);
742 
743     /* Now sleep if the callback wasn't invoked immediately */
744     while (cb.status == BDRV_BLOCK_OFFSET_MASK) {
745         cb.co = qemu_coroutine_self();
746         qemu_coroutine_yield();
747     }
748 
749     qed_unref_l2_cache_entry(request.l2_table);
750 
751     return cb.status;
752 }
753 
754 static BDRVQEDState *acb_to_s(QEDAIOCB *acb)
755 {
756     return acb->common.bs->opaque;
757 }
758 
759 /**
760  * Read from the backing file or zero-fill if no backing file
761  *
762  * @s:              QED state
763  * @pos:            Byte position in device
764  * @qiov:           Destination I/O vector
765  * @backing_qiov:   Possibly shortened copy of qiov, to be allocated here
766  * @cb:             Completion function
767  * @opaque:         User data for completion function
768  *
769  * This function reads qiov->size bytes starting at pos from the backing file.
770  * If there is no backing file then zeroes are read.
771  */
772 static void qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
773                                   QEMUIOVector *qiov,
774                                   QEMUIOVector **backing_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     assert(*backing_qiov == NULL);
808     *backing_qiov = g_new(QEMUIOVector, 1);
809     qemu_iovec_init(*backing_qiov, qiov->niov);
810     qemu_iovec_concat(*backing_qiov, qiov, 0, size);
811 
812     BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);
813     bdrv_aio_readv(s->bs->backing_hd, pos / BDRV_SECTOR_SIZE,
814                    *backing_qiov, size / BDRV_SECTOR_SIZE, cb, opaque);
815 }
816 
817 typedef struct {
818     GenericCB gencb;
819     BDRVQEDState *s;
820     QEMUIOVector qiov;
821     QEMUIOVector *backing_qiov;
822     struct iovec iov;
823     uint64_t offset;
824 } CopyFromBackingFileCB;
825 
826 static void qed_copy_from_backing_file_cb(void *opaque, int ret)
827 {
828     CopyFromBackingFileCB *copy_cb = opaque;
829     qemu_vfree(copy_cb->iov.iov_base);
830     gencb_complete(&copy_cb->gencb, ret);
831 }
832 
833 static void qed_copy_from_backing_file_write(void *opaque, int ret)
834 {
835     CopyFromBackingFileCB *copy_cb = opaque;
836     BDRVQEDState *s = copy_cb->s;
837 
838     if (copy_cb->backing_qiov) {
839         qemu_iovec_destroy(copy_cb->backing_qiov);
840         g_free(copy_cb->backing_qiov);
841         copy_cb->backing_qiov = NULL;
842     }
843 
844     if (ret) {
845         qed_copy_from_backing_file_cb(copy_cb, ret);
846         return;
847     }
848 
849     BLKDBG_EVENT(s->bs->file, BLKDBG_COW_WRITE);
850     bdrv_aio_writev(s->bs->file, copy_cb->offset / BDRV_SECTOR_SIZE,
851                     &copy_cb->qiov, copy_cb->qiov.size / BDRV_SECTOR_SIZE,
852                     qed_copy_from_backing_file_cb, copy_cb);
853 }
854 
855 /**
856  * Copy data from backing file into the image
857  *
858  * @s:          QED state
859  * @pos:        Byte position in device
860  * @len:        Number of bytes
861  * @offset:     Byte offset in image file
862  * @cb:         Completion function
863  * @opaque:     User data for completion function
864  */
865 static void qed_copy_from_backing_file(BDRVQEDState *s, uint64_t pos,
866                                        uint64_t len, uint64_t offset,
867                                        BlockDriverCompletionFunc *cb,
868                                        void *opaque)
869 {
870     CopyFromBackingFileCB *copy_cb;
871 
872     /* Skip copy entirely if there is no work to do */
873     if (len == 0) {
874         cb(opaque, 0);
875         return;
876     }
877 
878     copy_cb = gencb_alloc(sizeof(*copy_cb), cb, opaque);
879     copy_cb->s = s;
880     copy_cb->offset = offset;
881     copy_cb->backing_qiov = NULL;
882     copy_cb->iov.iov_base = qemu_blockalign(s->bs, len);
883     copy_cb->iov.iov_len = len;
884     qemu_iovec_init_external(&copy_cb->qiov, &copy_cb->iov, 1);
885 
886     qed_read_backing_file(s, pos, &copy_cb->qiov, &copy_cb->backing_qiov,
887                           qed_copy_from_backing_file_write, copy_cb);
888 }
889 
890 /**
891  * Link one or more contiguous clusters into a table
892  *
893  * @s:              QED state
894  * @table:          L2 table
895  * @index:          First cluster index
896  * @n:              Number of contiguous clusters
897  * @cluster:        First cluster offset
898  *
899  * The cluster offset may be an allocated byte offset in the image file, the
900  * zero cluster marker, or the unallocated cluster marker.
901  */
902 static void qed_update_l2_table(BDRVQEDState *s, QEDTable *table, int index,
903                                 unsigned int n, uint64_t cluster)
904 {
905     int i;
906     for (i = index; i < index + n; i++) {
907         table->offsets[i] = cluster;
908         if (!qed_offset_is_unalloc_cluster(cluster) &&
909             !qed_offset_is_zero_cluster(cluster)) {
910             cluster += s->header.cluster_size;
911         }
912     }
913 }
914 
915 static void qed_aio_complete_bh(void *opaque)
916 {
917     QEDAIOCB *acb = opaque;
918     BlockDriverCompletionFunc *cb = acb->common.cb;
919     void *user_opaque = acb->common.opaque;
920     int ret = acb->bh_ret;
921     bool *finished = acb->finished;
922 
923     qemu_bh_delete(acb->bh);
924     qemu_aio_release(acb);
925 
926     /* Invoke callback */
927     cb(user_opaque, ret);
928 
929     /* Signal cancel completion */
930     if (finished) {
931         *finished = true;
932     }
933 }
934 
935 static void qed_aio_complete(QEDAIOCB *acb, int ret)
936 {
937     BDRVQEDState *s = acb_to_s(acb);
938 
939     trace_qed_aio_complete(s, acb, ret);
940 
941     /* Free resources */
942     qemu_iovec_destroy(&acb->cur_qiov);
943     qed_unref_l2_cache_entry(acb->request.l2_table);
944 
945     /* Free the buffer we may have allocated for zero writes */
946     if (acb->flags & QED_AIOCB_ZERO) {
947         qemu_vfree(acb->qiov->iov[0].iov_base);
948         acb->qiov->iov[0].iov_base = NULL;
949     }
950 
951     /* Arrange for a bh to invoke the completion function */
952     acb->bh_ret = ret;
953     acb->bh = aio_bh_new(bdrv_get_aio_context(acb->common.bs),
954                          qed_aio_complete_bh, acb);
955     qemu_bh_schedule(acb->bh);
956 
957     /* Start next allocating write request waiting behind this one.  Note that
958      * requests enqueue themselves when they first hit an unallocated cluster
959      * but they wait until the entire request is finished before waking up the
960      * next request in the queue.  This ensures that we don't cycle through
961      * requests multiple times but rather finish one at a time completely.
962      */
963     if (acb == QSIMPLEQ_FIRST(&s->allocating_write_reqs)) {
964         QSIMPLEQ_REMOVE_HEAD(&s->allocating_write_reqs, next);
965         acb = QSIMPLEQ_FIRST(&s->allocating_write_reqs);
966         if (acb) {
967             qed_aio_next_io(acb, 0);
968         } else if (s->header.features & QED_F_NEED_CHECK) {
969             qed_start_need_check_timer(s);
970         }
971     }
972 }
973 
974 /**
975  * Commit the current L2 table to the cache
976  */
977 static void qed_commit_l2_update(void *opaque, int ret)
978 {
979     QEDAIOCB *acb = opaque;
980     BDRVQEDState *s = acb_to_s(acb);
981     CachedL2Table *l2_table = acb->request.l2_table;
982     uint64_t l2_offset = l2_table->offset;
983 
984     qed_commit_l2_cache_entry(&s->l2_cache, l2_table);
985 
986     /* This is guaranteed to succeed because we just committed the entry to the
987      * cache.
988      */
989     acb->request.l2_table = qed_find_l2_cache_entry(&s->l2_cache, l2_offset);
990     assert(acb->request.l2_table != NULL);
991 
992     qed_aio_next_io(opaque, ret);
993 }
994 
995 /**
996  * Update L1 table with new L2 table offset and write it out
997  */
998 static void qed_aio_write_l1_update(void *opaque, int ret)
999 {
1000     QEDAIOCB *acb = opaque;
1001     BDRVQEDState *s = acb_to_s(acb);
1002     int index;
1003 
1004     if (ret) {
1005         qed_aio_complete(acb, ret);
1006         return;
1007     }
1008 
1009     index = qed_l1_index(s, acb->cur_pos);
1010     s->l1_table->offsets[index] = acb->request.l2_table->offset;
1011 
1012     qed_write_l1_table(s, index, 1, qed_commit_l2_update, acb);
1013 }
1014 
1015 /**
1016  * Update L2 table with new cluster offsets and write them out
1017  */
1018 static void qed_aio_write_l2_update(QEDAIOCB *acb, int ret, uint64_t offset)
1019 {
1020     BDRVQEDState *s = acb_to_s(acb);
1021     bool need_alloc = acb->find_cluster_ret == QED_CLUSTER_L1;
1022     int index;
1023 
1024     if (ret) {
1025         goto err;
1026     }
1027 
1028     if (need_alloc) {
1029         qed_unref_l2_cache_entry(acb->request.l2_table);
1030         acb->request.l2_table = qed_new_l2_table(s);
1031     }
1032 
1033     index = qed_l2_index(s, acb->cur_pos);
1034     qed_update_l2_table(s, acb->request.l2_table->table, index, acb->cur_nclusters,
1035                          offset);
1036 
1037     if (need_alloc) {
1038         /* Write out the whole new L2 table */
1039         qed_write_l2_table(s, &acb->request, 0, s->table_nelems, true,
1040                             qed_aio_write_l1_update, acb);
1041     } else {
1042         /* Write out only the updated part of the L2 table */
1043         qed_write_l2_table(s, &acb->request, index, acb->cur_nclusters, false,
1044                             qed_aio_next_io, acb);
1045     }
1046     return;
1047 
1048 err:
1049     qed_aio_complete(acb, ret);
1050 }
1051 
1052 static void qed_aio_write_l2_update_cb(void *opaque, int ret)
1053 {
1054     QEDAIOCB *acb = opaque;
1055     qed_aio_write_l2_update(acb, ret, acb->cur_cluster);
1056 }
1057 
1058 /**
1059  * Flush new data clusters before updating the L2 table
1060  *
1061  * This flush is necessary when a backing file is in use.  A crash during an
1062  * allocating write could result in empty clusters in the image.  If the write
1063  * only touched a subregion of the cluster, then backing image sectors have
1064  * been lost in the untouched region.  The solution is to flush after writing a
1065  * new data cluster and before updating the L2 table.
1066  */
1067 static void qed_aio_write_flush_before_l2_update(void *opaque, int ret)
1068 {
1069     QEDAIOCB *acb = opaque;
1070     BDRVQEDState *s = acb_to_s(acb);
1071 
1072     if (!bdrv_aio_flush(s->bs->file, qed_aio_write_l2_update_cb, opaque)) {
1073         qed_aio_complete(acb, -EIO);
1074     }
1075 }
1076 
1077 /**
1078  * Write data to the image file
1079  */
1080 static void qed_aio_write_main(void *opaque, int ret)
1081 {
1082     QEDAIOCB *acb = opaque;
1083     BDRVQEDState *s = acb_to_s(acb);
1084     uint64_t offset = acb->cur_cluster +
1085                       qed_offset_into_cluster(s, acb->cur_pos);
1086     BlockDriverCompletionFunc *next_fn;
1087 
1088     trace_qed_aio_write_main(s, acb, ret, offset, acb->cur_qiov.size);
1089 
1090     if (ret) {
1091         qed_aio_complete(acb, ret);
1092         return;
1093     }
1094 
1095     if (acb->find_cluster_ret == QED_CLUSTER_FOUND) {
1096         next_fn = qed_aio_next_io;
1097     } else {
1098         if (s->bs->backing_hd) {
1099             next_fn = qed_aio_write_flush_before_l2_update;
1100         } else {
1101             next_fn = qed_aio_write_l2_update_cb;
1102         }
1103     }
1104 
1105     BLKDBG_EVENT(s->bs->file, BLKDBG_WRITE_AIO);
1106     bdrv_aio_writev(s->bs->file, offset / BDRV_SECTOR_SIZE,
1107                     &acb->cur_qiov, acb->cur_qiov.size / BDRV_SECTOR_SIZE,
1108                     next_fn, acb);
1109 }
1110 
1111 /**
1112  * Populate back untouched region of new data cluster
1113  */
1114 static void qed_aio_write_postfill(void *opaque, int ret)
1115 {
1116     QEDAIOCB *acb = opaque;
1117     BDRVQEDState *s = acb_to_s(acb);
1118     uint64_t start = acb->cur_pos + acb->cur_qiov.size;
1119     uint64_t len =
1120         qed_start_of_cluster(s, start + s->header.cluster_size - 1) - start;
1121     uint64_t offset = acb->cur_cluster +
1122                       qed_offset_into_cluster(s, acb->cur_pos) +
1123                       acb->cur_qiov.size;
1124 
1125     if (ret) {
1126         qed_aio_complete(acb, ret);
1127         return;
1128     }
1129 
1130     trace_qed_aio_write_postfill(s, acb, start, len, offset);
1131     qed_copy_from_backing_file(s, start, len, offset,
1132                                 qed_aio_write_main, acb);
1133 }
1134 
1135 /**
1136  * Populate front untouched region of new data cluster
1137  */
1138 static void qed_aio_write_prefill(void *opaque, int ret)
1139 {
1140     QEDAIOCB *acb = opaque;
1141     BDRVQEDState *s = acb_to_s(acb);
1142     uint64_t start = qed_start_of_cluster(s, acb->cur_pos);
1143     uint64_t len = qed_offset_into_cluster(s, acb->cur_pos);
1144 
1145     trace_qed_aio_write_prefill(s, acb, start, len, acb->cur_cluster);
1146     qed_copy_from_backing_file(s, start, len, acb->cur_cluster,
1147                                 qed_aio_write_postfill, acb);
1148 }
1149 
1150 /**
1151  * Check if the QED_F_NEED_CHECK bit should be set during allocating write
1152  */
1153 static bool qed_should_set_need_check(BDRVQEDState *s)
1154 {
1155     /* The flush before L2 update path ensures consistency */
1156     if (s->bs->backing_hd) {
1157         return false;
1158     }
1159 
1160     return !(s->header.features & QED_F_NEED_CHECK);
1161 }
1162 
1163 static void qed_aio_write_zero_cluster(void *opaque, int ret)
1164 {
1165     QEDAIOCB *acb = opaque;
1166 
1167     if (ret) {
1168         qed_aio_complete(acb, ret);
1169         return;
1170     }
1171 
1172     qed_aio_write_l2_update(acb, 0, 1);
1173 }
1174 
1175 /**
1176  * Write new data cluster
1177  *
1178  * @acb:        Write request
1179  * @len:        Length in bytes
1180  *
1181  * This path is taken when writing to previously unallocated clusters.
1182  */
1183 static void qed_aio_write_alloc(QEDAIOCB *acb, size_t len)
1184 {
1185     BDRVQEDState *s = acb_to_s(acb);
1186     BlockDriverCompletionFunc *cb;
1187 
1188     /* Cancel timer when the first allocating request comes in */
1189     if (QSIMPLEQ_EMPTY(&s->allocating_write_reqs)) {
1190         qed_cancel_need_check_timer(s);
1191     }
1192 
1193     /* Freeze this request if another allocating write is in progress */
1194     if (acb != QSIMPLEQ_FIRST(&s->allocating_write_reqs)) {
1195         QSIMPLEQ_INSERT_TAIL(&s->allocating_write_reqs, acb, next);
1196     }
1197     if (acb != QSIMPLEQ_FIRST(&s->allocating_write_reqs) ||
1198         s->allocating_write_reqs_plugged) {
1199         return; /* wait for existing request to finish */
1200     }
1201 
1202     acb->cur_nclusters = qed_bytes_to_clusters(s,
1203             qed_offset_into_cluster(s, acb->cur_pos) + len);
1204     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1205 
1206     if (acb->flags & QED_AIOCB_ZERO) {
1207         /* Skip ahead if the clusters are already zero */
1208         if (acb->find_cluster_ret == QED_CLUSTER_ZERO) {
1209             qed_aio_next_io(acb, 0);
1210             return;
1211         }
1212 
1213         cb = qed_aio_write_zero_cluster;
1214     } else {
1215         cb = qed_aio_write_prefill;
1216         acb->cur_cluster = qed_alloc_clusters(s, acb->cur_nclusters);
1217     }
1218 
1219     if (qed_should_set_need_check(s)) {
1220         s->header.features |= QED_F_NEED_CHECK;
1221         qed_write_header(s, cb, acb);
1222     } else {
1223         cb(acb, 0);
1224     }
1225 }
1226 
1227 /**
1228  * Write data cluster in place
1229  *
1230  * @acb:        Write request
1231  * @offset:     Cluster offset in bytes
1232  * @len:        Length in bytes
1233  *
1234  * This path is taken when writing to already allocated clusters.
1235  */
1236 static void qed_aio_write_inplace(QEDAIOCB *acb, uint64_t offset, size_t len)
1237 {
1238     /* Allocate buffer for zero writes */
1239     if (acb->flags & QED_AIOCB_ZERO) {
1240         struct iovec *iov = acb->qiov->iov;
1241 
1242         if (!iov->iov_base) {
1243             iov->iov_base = qemu_try_blockalign(acb->common.bs, iov->iov_len);
1244             if (iov->iov_base == NULL) {
1245                 qed_aio_complete(acb, -ENOMEM);
1246                 return;
1247             }
1248             memset(iov->iov_base, 0, iov->iov_len);
1249         }
1250     }
1251 
1252     /* Calculate the I/O vector */
1253     acb->cur_cluster = offset;
1254     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1255 
1256     /* Do the actual write */
1257     qed_aio_write_main(acb, 0);
1258 }
1259 
1260 /**
1261  * Write data cluster
1262  *
1263  * @opaque:     Write request
1264  * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2, QED_CLUSTER_L1,
1265  *              or -errno
1266  * @offset:     Cluster offset in bytes
1267  * @len:        Length in bytes
1268  *
1269  * Callback from qed_find_cluster().
1270  */
1271 static void qed_aio_write_data(void *opaque, int ret,
1272                                uint64_t offset, size_t len)
1273 {
1274     QEDAIOCB *acb = opaque;
1275 
1276     trace_qed_aio_write_data(acb_to_s(acb), acb, ret, offset, len);
1277 
1278     acb->find_cluster_ret = ret;
1279 
1280     switch (ret) {
1281     case QED_CLUSTER_FOUND:
1282         qed_aio_write_inplace(acb, offset, len);
1283         break;
1284 
1285     case QED_CLUSTER_L2:
1286     case QED_CLUSTER_L1:
1287     case QED_CLUSTER_ZERO:
1288         qed_aio_write_alloc(acb, len);
1289         break;
1290 
1291     default:
1292         qed_aio_complete(acb, ret);
1293         break;
1294     }
1295 }
1296 
1297 /**
1298  * Read data cluster
1299  *
1300  * @opaque:     Read request
1301  * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2, QED_CLUSTER_L1,
1302  *              or -errno
1303  * @offset:     Cluster offset in bytes
1304  * @len:        Length in bytes
1305  *
1306  * Callback from qed_find_cluster().
1307  */
1308 static void qed_aio_read_data(void *opaque, int ret,
1309                               uint64_t offset, size_t len)
1310 {
1311     QEDAIOCB *acb = opaque;
1312     BDRVQEDState *s = acb_to_s(acb);
1313     BlockDriverState *bs = acb->common.bs;
1314 
1315     /* Adjust offset into cluster */
1316     offset += qed_offset_into_cluster(s, acb->cur_pos);
1317 
1318     trace_qed_aio_read_data(s, acb, ret, offset, len);
1319 
1320     if (ret < 0) {
1321         goto err;
1322     }
1323 
1324     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1325 
1326     /* Handle zero cluster and backing file reads */
1327     if (ret == QED_CLUSTER_ZERO) {
1328         qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
1329         qed_aio_next_io(acb, 0);
1330         return;
1331     } else if (ret != QED_CLUSTER_FOUND) {
1332         qed_read_backing_file(s, acb->cur_pos, &acb->cur_qiov,
1333                               &acb->backing_qiov, qed_aio_next_io, acb);
1334         return;
1335     }
1336 
1337     BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1338     bdrv_aio_readv(bs->file, offset / BDRV_SECTOR_SIZE,
1339                    &acb->cur_qiov, acb->cur_qiov.size / BDRV_SECTOR_SIZE,
1340                    qed_aio_next_io, acb);
1341     return;
1342 
1343 err:
1344     qed_aio_complete(acb, ret);
1345 }
1346 
1347 /**
1348  * Begin next I/O or complete the request
1349  */
1350 static void qed_aio_next_io(void *opaque, int ret)
1351 {
1352     QEDAIOCB *acb = opaque;
1353     BDRVQEDState *s = acb_to_s(acb);
1354     QEDFindClusterFunc *io_fn = (acb->flags & QED_AIOCB_WRITE) ?
1355                                 qed_aio_write_data : qed_aio_read_data;
1356 
1357     trace_qed_aio_next_io(s, acb, ret, acb->cur_pos + acb->cur_qiov.size);
1358 
1359     if (acb->backing_qiov) {
1360         qemu_iovec_destroy(acb->backing_qiov);
1361         g_free(acb->backing_qiov);
1362         acb->backing_qiov = NULL;
1363     }
1364 
1365     /* Handle I/O error */
1366     if (ret) {
1367         qed_aio_complete(acb, ret);
1368         return;
1369     }
1370 
1371     acb->qiov_offset += acb->cur_qiov.size;
1372     acb->cur_pos += acb->cur_qiov.size;
1373     qemu_iovec_reset(&acb->cur_qiov);
1374 
1375     /* Complete request */
1376     if (acb->cur_pos >= acb->end_pos) {
1377         qed_aio_complete(acb, 0);
1378         return;
1379     }
1380 
1381     /* Find next cluster and start I/O */
1382     qed_find_cluster(s, &acb->request,
1383                       acb->cur_pos, acb->end_pos - acb->cur_pos,
1384                       io_fn, acb);
1385 }
1386 
1387 static BlockDriverAIOCB *qed_aio_setup(BlockDriverState *bs,
1388                                        int64_t sector_num,
1389                                        QEMUIOVector *qiov, int nb_sectors,
1390                                        BlockDriverCompletionFunc *cb,
1391                                        void *opaque, int flags)
1392 {
1393     QEDAIOCB *acb = qemu_aio_get(&qed_aiocb_info, bs, cb, opaque);
1394 
1395     trace_qed_aio_setup(bs->opaque, acb, sector_num, nb_sectors,
1396                         opaque, flags);
1397 
1398     acb->flags = flags;
1399     acb->finished = NULL;
1400     acb->qiov = qiov;
1401     acb->qiov_offset = 0;
1402     acb->cur_pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE;
1403     acb->end_pos = acb->cur_pos + nb_sectors * BDRV_SECTOR_SIZE;
1404     acb->backing_qiov = NULL;
1405     acb->request.l2_table = NULL;
1406     qemu_iovec_init(&acb->cur_qiov, qiov->niov);
1407 
1408     /* Start request */
1409     qed_aio_next_io(acb, 0);
1410     return &acb->common;
1411 }
1412 
1413 static BlockDriverAIOCB *bdrv_qed_aio_readv(BlockDriverState *bs,
1414                                             int64_t sector_num,
1415                                             QEMUIOVector *qiov, int nb_sectors,
1416                                             BlockDriverCompletionFunc *cb,
1417                                             void *opaque)
1418 {
1419     return qed_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1420 }
1421 
1422 static BlockDriverAIOCB *bdrv_qed_aio_writev(BlockDriverState *bs,
1423                                              int64_t sector_num,
1424                                              QEMUIOVector *qiov, int nb_sectors,
1425                                              BlockDriverCompletionFunc *cb,
1426                                              void *opaque)
1427 {
1428     return qed_aio_setup(bs, sector_num, qiov, nb_sectors, cb,
1429                          opaque, QED_AIOCB_WRITE);
1430 }
1431 
1432 typedef struct {
1433     Coroutine *co;
1434     int ret;
1435     bool done;
1436 } QEDWriteZeroesCB;
1437 
1438 static void coroutine_fn qed_co_write_zeroes_cb(void *opaque, int ret)
1439 {
1440     QEDWriteZeroesCB *cb = opaque;
1441 
1442     cb->done = true;
1443     cb->ret = ret;
1444     if (cb->co) {
1445         qemu_coroutine_enter(cb->co, NULL);
1446     }
1447 }
1448 
1449 static int coroutine_fn bdrv_qed_co_write_zeroes(BlockDriverState *bs,
1450                                                  int64_t sector_num,
1451                                                  int nb_sectors,
1452                                                  BdrvRequestFlags flags)
1453 {
1454     BlockDriverAIOCB *blockacb;
1455     BDRVQEDState *s = bs->opaque;
1456     QEDWriteZeroesCB cb = { .done = false };
1457     QEMUIOVector qiov;
1458     struct iovec iov;
1459 
1460     /* Refuse if there are untouched backing file sectors */
1461     if (bs->backing_hd) {
1462         if (qed_offset_into_cluster(s, sector_num * BDRV_SECTOR_SIZE) != 0) {
1463             return -ENOTSUP;
1464         }
1465         if (qed_offset_into_cluster(s, nb_sectors * BDRV_SECTOR_SIZE) != 0) {
1466             return -ENOTSUP;
1467         }
1468     }
1469 
1470     /* Zero writes start without an I/O buffer.  If a buffer becomes necessary
1471      * then it will be allocated during request processing.
1472      */
1473     iov.iov_base = NULL,
1474     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE,
1475 
1476     qemu_iovec_init_external(&qiov, &iov, 1);
1477     blockacb = qed_aio_setup(bs, sector_num, &qiov, nb_sectors,
1478                              qed_co_write_zeroes_cb, &cb,
1479                              QED_AIOCB_WRITE | QED_AIOCB_ZERO);
1480     if (!blockacb) {
1481         return -EIO;
1482     }
1483     if (!cb.done) {
1484         cb.co = qemu_coroutine_self();
1485         qemu_coroutine_yield();
1486     }
1487     assert(cb.done);
1488     return cb.ret;
1489 }
1490 
1491 static int bdrv_qed_truncate(BlockDriverState *bs, int64_t offset)
1492 {
1493     BDRVQEDState *s = bs->opaque;
1494     uint64_t old_image_size;
1495     int ret;
1496 
1497     if (!qed_is_image_size_valid(offset, s->header.cluster_size,
1498                                  s->header.table_size)) {
1499         return -EINVAL;
1500     }
1501 
1502     /* Shrinking is currently not supported */
1503     if ((uint64_t)offset < s->header.image_size) {
1504         return -ENOTSUP;
1505     }
1506 
1507     old_image_size = s->header.image_size;
1508     s->header.image_size = offset;
1509     ret = qed_write_header_sync(s);
1510     if (ret < 0) {
1511         s->header.image_size = old_image_size;
1512     }
1513     return ret;
1514 }
1515 
1516 static int64_t bdrv_qed_getlength(BlockDriverState *bs)
1517 {
1518     BDRVQEDState *s = bs->opaque;
1519     return s->header.image_size;
1520 }
1521 
1522 static int bdrv_qed_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1523 {
1524     BDRVQEDState *s = bs->opaque;
1525 
1526     memset(bdi, 0, sizeof(*bdi));
1527     bdi->cluster_size = s->header.cluster_size;
1528     bdi->is_dirty = s->header.features & QED_F_NEED_CHECK;
1529     bdi->unallocated_blocks_are_zero = true;
1530     bdi->can_write_zeroes_with_unmap = true;
1531     return 0;
1532 }
1533 
1534 static int bdrv_qed_change_backing_file(BlockDriverState *bs,
1535                                         const char *backing_file,
1536                                         const char *backing_fmt)
1537 {
1538     BDRVQEDState *s = bs->opaque;
1539     QEDHeader new_header, le_header;
1540     void *buffer;
1541     size_t buffer_len, backing_file_len;
1542     int ret;
1543 
1544     /* Refuse to set backing filename if unknown compat feature bits are
1545      * active.  If the image uses an unknown compat feature then we may not
1546      * know the layout of data following the header structure and cannot safely
1547      * add a new string.
1548      */
1549     if (backing_file && (s->header.compat_features &
1550                          ~QED_COMPAT_FEATURE_MASK)) {
1551         return -ENOTSUP;
1552     }
1553 
1554     memcpy(&new_header, &s->header, sizeof(new_header));
1555 
1556     new_header.features &= ~(QED_F_BACKING_FILE |
1557                              QED_F_BACKING_FORMAT_NO_PROBE);
1558 
1559     /* Adjust feature flags */
1560     if (backing_file) {
1561         new_header.features |= QED_F_BACKING_FILE;
1562 
1563         if (qed_fmt_is_raw(backing_fmt)) {
1564             new_header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
1565         }
1566     }
1567 
1568     /* Calculate new header size */
1569     backing_file_len = 0;
1570 
1571     if (backing_file) {
1572         backing_file_len = strlen(backing_file);
1573     }
1574 
1575     buffer_len = sizeof(new_header);
1576     new_header.backing_filename_offset = buffer_len;
1577     new_header.backing_filename_size = backing_file_len;
1578     buffer_len += backing_file_len;
1579 
1580     /* Make sure we can rewrite header without failing */
1581     if (buffer_len > new_header.header_size * new_header.cluster_size) {
1582         return -ENOSPC;
1583     }
1584 
1585     /* Prepare new header */
1586     buffer = g_malloc(buffer_len);
1587 
1588     qed_header_cpu_to_le(&new_header, &le_header);
1589     memcpy(buffer, &le_header, sizeof(le_header));
1590     buffer_len = sizeof(le_header);
1591 
1592     if (backing_file) {
1593         memcpy(buffer + buffer_len, backing_file, backing_file_len);
1594         buffer_len += backing_file_len;
1595     }
1596 
1597     /* Write new header */
1598     ret = bdrv_pwrite_sync(bs->file, 0, buffer, buffer_len);
1599     g_free(buffer);
1600     if (ret == 0) {
1601         memcpy(&s->header, &new_header, sizeof(new_header));
1602     }
1603     return ret;
1604 }
1605 
1606 static void bdrv_qed_invalidate_cache(BlockDriverState *bs, Error **errp)
1607 {
1608     BDRVQEDState *s = bs->opaque;
1609     Error *local_err = NULL;
1610     int ret;
1611 
1612     bdrv_qed_close(bs);
1613 
1614     bdrv_invalidate_cache(bs->file, &local_err);
1615     if (local_err) {
1616         error_propagate(errp, local_err);
1617         return;
1618     }
1619 
1620     memset(s, 0, sizeof(BDRVQEDState));
1621     ret = bdrv_qed_open(bs, NULL, bs->open_flags, &local_err);
1622     if (local_err) {
1623         error_setg(errp, "Could not reopen qed layer: %s",
1624                    error_get_pretty(local_err));
1625         error_free(local_err);
1626         return;
1627     } else if (ret < 0) {
1628         error_setg_errno(errp, -ret, "Could not reopen qed layer");
1629         return;
1630     }
1631 }
1632 
1633 static int bdrv_qed_check(BlockDriverState *bs, BdrvCheckResult *result,
1634                           BdrvCheckMode fix)
1635 {
1636     BDRVQEDState *s = bs->opaque;
1637 
1638     return qed_check(s, result, !!fix);
1639 }
1640 
1641 static QemuOptsList qed_create_opts = {
1642     .name = "qed-create-opts",
1643     .head = QTAILQ_HEAD_INITIALIZER(qed_create_opts.head),
1644     .desc = {
1645         {
1646             .name = BLOCK_OPT_SIZE,
1647             .type = QEMU_OPT_SIZE,
1648             .help = "Virtual disk size"
1649         },
1650         {
1651             .name = BLOCK_OPT_BACKING_FILE,
1652             .type = QEMU_OPT_STRING,
1653             .help = "File name of a base image"
1654         },
1655         {
1656             .name = BLOCK_OPT_BACKING_FMT,
1657             .type = QEMU_OPT_STRING,
1658             .help = "Image format of the base image"
1659         },
1660         {
1661             .name = BLOCK_OPT_CLUSTER_SIZE,
1662             .type = QEMU_OPT_SIZE,
1663             .help = "Cluster size (in bytes)",
1664             .def_value_str = stringify(QED_DEFAULT_CLUSTER_SIZE)
1665         },
1666         {
1667             .name = BLOCK_OPT_TABLE_SIZE,
1668             .type = QEMU_OPT_SIZE,
1669             .help = "L1/L2 table size (in clusters)"
1670         },
1671         { /* end of list */ }
1672     }
1673 };
1674 
1675 static BlockDriver bdrv_qed = {
1676     .format_name              = "qed",
1677     .instance_size            = sizeof(BDRVQEDState),
1678     .create_opts              = &qed_create_opts,
1679     .supports_backing         = true,
1680 
1681     .bdrv_probe               = bdrv_qed_probe,
1682     .bdrv_rebind              = bdrv_qed_rebind,
1683     .bdrv_open                = bdrv_qed_open,
1684     .bdrv_close               = bdrv_qed_close,
1685     .bdrv_reopen_prepare      = bdrv_qed_reopen_prepare,
1686     .bdrv_create              = bdrv_qed_create,
1687     .bdrv_has_zero_init       = bdrv_has_zero_init_1,
1688     .bdrv_co_get_block_status = bdrv_qed_co_get_block_status,
1689     .bdrv_aio_readv           = bdrv_qed_aio_readv,
1690     .bdrv_aio_writev          = bdrv_qed_aio_writev,
1691     .bdrv_co_write_zeroes     = bdrv_qed_co_write_zeroes,
1692     .bdrv_truncate            = bdrv_qed_truncate,
1693     .bdrv_getlength           = bdrv_qed_getlength,
1694     .bdrv_get_info            = bdrv_qed_get_info,
1695     .bdrv_refresh_limits      = bdrv_qed_refresh_limits,
1696     .bdrv_change_backing_file = bdrv_qed_change_backing_file,
1697     .bdrv_invalidate_cache    = bdrv_qed_invalidate_cache,
1698     .bdrv_check               = bdrv_qed_check,
1699     .bdrv_detach_aio_context  = bdrv_qed_detach_aio_context,
1700     .bdrv_attach_aio_context  = bdrv_qed_attach_aio_context,
1701 };
1702 
1703 static void bdrv_qed_init(void)
1704 {
1705     bdrv_register(&bdrv_qed);
1706 }
1707 
1708 block_init(bdrv_qed_init);
1709