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