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