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