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