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