]> Git Repo - qemu.git/blob - block/qcow2-cluster.c
qcow2: count_contiguous_clusters and compression
[qemu.git] / block / qcow2-cluster.c
1 /*
2  * Block driver for the QCOW version 2 format
3  *
4  * Copyright (c) 2004-2006 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24
25 #include <zlib.h>
26
27 #include "qemu-common.h"
28 #include "block/block_int.h"
29 #include "block/qcow2.h"
30 #include "trace.h"
31
32 int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
33                         bool exact_size)
34 {
35     BDRVQcowState *s = bs->opaque;
36     int new_l1_size2, ret, i;
37     uint64_t *new_l1_table;
38     int64_t new_l1_table_offset, new_l1_size;
39     uint8_t data[12];
40
41     if (min_size <= s->l1_size)
42         return 0;
43
44     if (exact_size) {
45         new_l1_size = min_size;
46     } else {
47         /* Bump size up to reduce the number of times we have to grow */
48         new_l1_size = s->l1_size;
49         if (new_l1_size == 0) {
50             new_l1_size = 1;
51         }
52         while (min_size > new_l1_size) {
53             new_l1_size = (new_l1_size * 3 + 1) / 2;
54         }
55     }
56
57     if (new_l1_size > INT_MAX) {
58         return -EFBIG;
59     }
60
61 #ifdef DEBUG_ALLOC2
62     fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
63             s->l1_size, new_l1_size);
64 #endif
65
66     new_l1_size2 = sizeof(uint64_t) * new_l1_size;
67     new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));
68     memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
69
70     /* write new table (align to cluster) */
71     BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
72     new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
73     if (new_l1_table_offset < 0) {
74         g_free(new_l1_table);
75         return new_l1_table_offset;
76     }
77
78     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
79     if (ret < 0) {
80         goto fail;
81     }
82
83     /* the L1 position has not yet been updated, so these clusters must
84      * indeed be completely free */
85     ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
86                                         new_l1_table_offset, new_l1_size2);
87     if (ret < 0) {
88         goto fail;
89     }
90
91     BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
92     for(i = 0; i < s->l1_size; i++)
93         new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
94     ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
95     if (ret < 0)
96         goto fail;
97     for(i = 0; i < s->l1_size; i++)
98         new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
99
100     /* set new table */
101     BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
102     cpu_to_be32w((uint32_t*)data, new_l1_size);
103     cpu_to_be64wu((uint64_t*)(data + 4), new_l1_table_offset);
104     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
105     if (ret < 0) {
106         goto fail;
107     }
108     g_free(s->l1_table);
109     qcow2_free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t),
110                         QCOW2_DISCARD_OTHER);
111     s->l1_table_offset = new_l1_table_offset;
112     s->l1_table = new_l1_table;
113     s->l1_size = new_l1_size;
114     return 0;
115  fail:
116     g_free(new_l1_table);
117     qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
118                         QCOW2_DISCARD_OTHER);
119     return ret;
120 }
121
122 /*
123  * l2_load
124  *
125  * Loads a L2 table into memory. If the table is in the cache, the cache
126  * is used; otherwise the L2 table is loaded from the image file.
127  *
128  * Returns a pointer to the L2 table on success, or NULL if the read from
129  * the image file failed.
130  */
131
132 static int l2_load(BlockDriverState *bs, uint64_t l2_offset,
133     uint64_t **l2_table)
134 {
135     BDRVQcowState *s = bs->opaque;
136     int ret;
137
138     ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset, (void**) l2_table);
139
140     return ret;
141 }
142
143 /*
144  * Writes one sector of the L1 table to the disk (can't update single entries
145  * and we really don't want bdrv_pread to perform a read-modify-write)
146  */
147 #define L1_ENTRIES_PER_SECTOR (512 / 8)
148 int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index)
149 {
150     BDRVQcowState *s = bs->opaque;
151     uint64_t buf[L1_ENTRIES_PER_SECTOR];
152     int l1_start_index;
153     int i, ret;
154
155     l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);
156     for (i = 0; i < L1_ENTRIES_PER_SECTOR; i++) {
157         buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
158     }
159
160     ret = qcow2_pre_write_overlap_check(bs,
161             QCOW2_OL_DEFAULT & ~QCOW2_OL_ACTIVE_L1,
162             s->l1_table_offset + 8 * l1_start_index, sizeof(buf));
163     if (ret < 0) {
164         return ret;
165     }
166
167     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
168     ret = bdrv_pwrite_sync(bs->file, s->l1_table_offset + 8 * l1_start_index,
169         buf, sizeof(buf));
170     if (ret < 0) {
171         return ret;
172     }
173
174     return 0;
175 }
176
177 /*
178  * l2_allocate
179  *
180  * Allocate a new l2 entry in the file. If l1_index points to an already
181  * used entry in the L2 table (i.e. we are doing a copy on write for the L2
182  * table) copy the contents of the old L2 table into the newly allocated one.
183  * Otherwise the new table is initialized with zeros.
184  *
185  */
186
187 static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
188 {
189     BDRVQcowState *s = bs->opaque;
190     uint64_t old_l2_offset;
191     uint64_t *l2_table = NULL;
192     int64_t l2_offset;
193     int ret;
194
195     old_l2_offset = s->l1_table[l1_index];
196
197     trace_qcow2_l2_allocate(bs, l1_index);
198
199     /* allocate a new l2 entry */
200
201     l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
202     if (l2_offset < 0) {
203         ret = l2_offset;
204         goto fail;
205     }
206
207     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
208     if (ret < 0) {
209         goto fail;
210     }
211
212     /* allocate a new entry in the l2 cache */
213
214     trace_qcow2_l2_allocate_get_empty(bs, l1_index);
215     ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);
216     if (ret < 0) {
217         goto fail;
218     }
219
220     l2_table = *table;
221
222     if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
223         /* if there was no old l2 table, clear the new table */
224         memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
225     } else {
226         uint64_t* old_table;
227
228         /* if there was an old l2 table, read it from the disk */
229         BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
230         ret = qcow2_cache_get(bs, s->l2_table_cache,
231             old_l2_offset & L1E_OFFSET_MASK,
232             (void**) &old_table);
233         if (ret < 0) {
234             goto fail;
235         }
236
237         memcpy(l2_table, old_table, s->cluster_size);
238
239         ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &old_table);
240         if (ret < 0) {
241             goto fail;
242         }
243     }
244
245     /* write the l2 table to the file */
246     BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
247
248     trace_qcow2_l2_allocate_write_l2(bs, l1_index);
249     qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
250     ret = qcow2_cache_flush(bs, s->l2_table_cache);
251     if (ret < 0) {
252         goto fail;
253     }
254
255     /* update the L1 entry */
256     trace_qcow2_l2_allocate_write_l1(bs, l1_index);
257     s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
258     ret = qcow2_write_l1_entry(bs, l1_index);
259     if (ret < 0) {
260         goto fail;
261     }
262
263     *table = l2_table;
264     trace_qcow2_l2_allocate_done(bs, l1_index, 0);
265     return 0;
266
267 fail:
268     trace_qcow2_l2_allocate_done(bs, l1_index, ret);
269     if (l2_table != NULL) {
270         qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
271     }
272     s->l1_table[l1_index] = old_l2_offset;
273     return ret;
274 }
275
276 /*
277  * Checks how many clusters in a given L2 table are contiguous in the image
278  * file. As soon as one of the flags in the bitmask stop_flags changes compared
279  * to the first cluster, the search is stopped and the cluster is not counted
280  * as contiguous. (This allows it, for example, to stop at the first compressed
281  * cluster which may require a different handling)
282  */
283 static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
284         uint64_t *l2_table, uint64_t start, uint64_t stop_flags)
285 {
286     int i;
287     uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW2_CLUSTER_COMPRESSED;
288     uint64_t first_entry = be64_to_cpu(l2_table[0]);
289     uint64_t offset = first_entry & mask;
290
291     if (!offset)
292         return 0;
293
294     assert(qcow2_get_cluster_type(first_entry) != QCOW2_CLUSTER_COMPRESSED);
295
296     for (i = start; i < start + nb_clusters; i++) {
297         uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;
298         if (offset + (uint64_t) i * cluster_size != l2_entry) {
299             break;
300         }
301     }
302
303         return (i - start);
304 }
305
306 static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
307 {
308     int i;
309
310     for (i = 0; i < nb_clusters; i++) {
311         int type = qcow2_get_cluster_type(be64_to_cpu(l2_table[i]));
312
313         if (type != QCOW2_CLUSTER_UNALLOCATED) {
314             break;
315         }
316     }
317
318     return i;
319 }
320
321 /* The crypt function is compatible with the linux cryptoloop
322    algorithm for < 4 GB images. NOTE: out_buf == in_buf is
323    supported */
324 void qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
325                            uint8_t *out_buf, const uint8_t *in_buf,
326                            int nb_sectors, int enc,
327                            const AES_KEY *key)
328 {
329     union {
330         uint64_t ll[2];
331         uint8_t b[16];
332     } ivec;
333     int i;
334
335     for(i = 0; i < nb_sectors; i++) {
336         ivec.ll[0] = cpu_to_le64(sector_num);
337         ivec.ll[1] = 0;
338         AES_cbc_encrypt(in_buf, out_buf, 512, key,
339                         ivec.b, enc);
340         sector_num++;
341         in_buf += 512;
342         out_buf += 512;
343     }
344 }
345
346 static int coroutine_fn copy_sectors(BlockDriverState *bs,
347                                      uint64_t start_sect,
348                                      uint64_t cluster_offset,
349                                      int n_start, int n_end)
350 {
351     BDRVQcowState *s = bs->opaque;
352     QEMUIOVector qiov;
353     struct iovec iov;
354     int n, ret;
355
356     /*
357      * If this is the last cluster and it is only partially used, we must only
358      * copy until the end of the image, or bdrv_check_request will fail for the
359      * bdrv_read/write calls below.
360      */
361     if (start_sect + n_end > bs->total_sectors) {
362         n_end = bs->total_sectors - start_sect;
363     }
364
365     n = n_end - n_start;
366     if (n <= 0) {
367         return 0;
368     }
369
370     iov.iov_len = n * BDRV_SECTOR_SIZE;
371     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
372
373     qemu_iovec_init_external(&qiov, &iov, 1);
374
375     BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
376
377     /* Call .bdrv_co_readv() directly instead of using the public block-layer
378      * interface.  This avoids double I/O throttling and request tracking,
379      * which can lead to deadlock when block layer copy-on-read is enabled.
380      */
381     ret = bs->drv->bdrv_co_readv(bs, start_sect + n_start, n, &qiov);
382     if (ret < 0) {
383         goto out;
384     }
385
386     if (s->crypt_method) {
387         qcow2_encrypt_sectors(s, start_sect + n_start,
388                         iov.iov_base, iov.iov_base, n, 1,
389                         &s->aes_encrypt_key);
390     }
391
392     ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
393             cluster_offset + n_start * BDRV_SECTOR_SIZE, n * BDRV_SECTOR_SIZE);
394     if (ret < 0) {
395         goto out;
396     }
397
398     BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
399     ret = bdrv_co_writev(bs->file, (cluster_offset >> 9) + n_start, n, &qiov);
400     if (ret < 0) {
401         goto out;
402     }
403
404     ret = 0;
405 out:
406     qemu_vfree(iov.iov_base);
407     return ret;
408 }
409
410
411 /*
412  * get_cluster_offset
413  *
414  * For a given offset of the disk image, find the cluster offset in
415  * qcow2 file. The offset is stored in *cluster_offset.
416  *
417  * on entry, *num is the number of contiguous sectors we'd like to
418  * access following offset.
419  *
420  * on exit, *num is the number of contiguous sectors we can read.
421  *
422  * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
423  * cases.
424  */
425 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
426     int *num, uint64_t *cluster_offset)
427 {
428     BDRVQcowState *s = bs->opaque;
429     unsigned int l2_index;
430     uint64_t l1_index, l2_offset, *l2_table;
431     int l1_bits, c;
432     unsigned int index_in_cluster, nb_clusters;
433     uint64_t nb_available, nb_needed;
434     int ret;
435
436     index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
437     nb_needed = *num + index_in_cluster;
438
439     l1_bits = s->l2_bits + s->cluster_bits;
440
441     /* compute how many bytes there are between the offset and
442      * the end of the l1 entry
443      */
444
445     nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));
446
447     /* compute the number of available sectors */
448
449     nb_available = (nb_available >> 9) + index_in_cluster;
450
451     if (nb_needed > nb_available) {
452         nb_needed = nb_available;
453     }
454
455     *cluster_offset = 0;
456
457     /* seek the the l2 offset in the l1 table */
458
459     l1_index = offset >> l1_bits;
460     if (l1_index >= s->l1_size) {
461         ret = QCOW2_CLUSTER_UNALLOCATED;
462         goto out;
463     }
464
465     l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
466     if (!l2_offset) {
467         ret = QCOW2_CLUSTER_UNALLOCATED;
468         goto out;
469     }
470
471     /* load the l2 table in memory */
472
473     ret = l2_load(bs, l2_offset, &l2_table);
474     if (ret < 0) {
475         return ret;
476     }
477
478     /* find the cluster offset for the given disk offset */
479
480     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
481     *cluster_offset = be64_to_cpu(l2_table[l2_index]);
482     nb_clusters = size_to_clusters(s, nb_needed << 9);
483
484     ret = qcow2_get_cluster_type(*cluster_offset);
485     switch (ret) {
486     case QCOW2_CLUSTER_COMPRESSED:
487         /* Compressed clusters can only be processed one by one */
488         c = 1;
489         *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;
490         break;
491     case QCOW2_CLUSTER_ZERO:
492         if (s->qcow_version < 3) {
493             return -EIO;
494         }
495         c = count_contiguous_clusters(nb_clusters, s->cluster_size,
496                 &l2_table[l2_index], 0,
497                 QCOW_OFLAG_COMPRESSED | QCOW_OFLAG_ZERO);
498         *cluster_offset = 0;
499         break;
500     case QCOW2_CLUSTER_UNALLOCATED:
501         /* how many empty clusters ? */
502         c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
503         *cluster_offset = 0;
504         break;
505     case QCOW2_CLUSTER_NORMAL:
506         /* how many allocated clusters ? */
507         c = count_contiguous_clusters(nb_clusters, s->cluster_size,
508                 &l2_table[l2_index], 0,
509                 QCOW_OFLAG_COMPRESSED | QCOW_OFLAG_ZERO);
510         *cluster_offset &= L2E_OFFSET_MASK;
511         break;
512     default:
513         abort();
514     }
515
516     qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
517
518     nb_available = (c * s->cluster_sectors);
519
520 out:
521     if (nb_available > nb_needed)
522         nb_available = nb_needed;
523
524     *num = nb_available - index_in_cluster;
525
526     return ret;
527 }
528
529 /*
530  * get_cluster_table
531  *
532  * for a given disk offset, load (and allocate if needed)
533  * the l2 table.
534  *
535  * the l2 table offset in the qcow2 file and the cluster index
536  * in the l2 table are given to the caller.
537  *
538  * Returns 0 on success, -errno in failure case
539  */
540 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
541                              uint64_t **new_l2_table,
542                              int *new_l2_index)
543 {
544     BDRVQcowState *s = bs->opaque;
545     unsigned int l2_index;
546     uint64_t l1_index, l2_offset;
547     uint64_t *l2_table = NULL;
548     int ret;
549
550     /* seek the the l2 offset in the l1 table */
551
552     l1_index = offset >> (s->l2_bits + s->cluster_bits);
553     if (l1_index >= s->l1_size) {
554         ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
555         if (ret < 0) {
556             return ret;
557         }
558     }
559
560     assert(l1_index < s->l1_size);
561     l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
562
563     /* seek the l2 table of the given l2 offset */
564
565     if (s->l1_table[l1_index] & QCOW_OFLAG_COPIED) {
566         /* load the l2 table in memory */
567         ret = l2_load(bs, l2_offset, &l2_table);
568         if (ret < 0) {
569             return ret;
570         }
571     } else {
572         /* First allocate a new L2 table (and do COW if needed) */
573         ret = l2_allocate(bs, l1_index, &l2_table);
574         if (ret < 0) {
575             return ret;
576         }
577
578         /* Then decrease the refcount of the old table */
579         if (l2_offset) {
580             qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
581                                 QCOW2_DISCARD_OTHER);
582         }
583     }
584
585     /* find the cluster offset for the given disk offset */
586
587     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
588
589     *new_l2_table = l2_table;
590     *new_l2_index = l2_index;
591
592     return 0;
593 }
594
595 /*
596  * alloc_compressed_cluster_offset
597  *
598  * For a given offset of the disk image, return cluster offset in
599  * qcow2 file.
600  *
601  * If the offset is not found, allocate a new compressed cluster.
602  *
603  * Return the cluster offset if successful,
604  * Return 0, otherwise.
605  *
606  */
607
608 uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
609                                                uint64_t offset,
610                                                int compressed_size)
611 {
612     BDRVQcowState *s = bs->opaque;
613     int l2_index, ret;
614     uint64_t *l2_table;
615     int64_t cluster_offset;
616     int nb_csectors;
617
618     ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
619     if (ret < 0) {
620         return 0;
621     }
622
623     /* Compression can't overwrite anything. Fail if the cluster was already
624      * allocated. */
625     cluster_offset = be64_to_cpu(l2_table[l2_index]);
626     if (cluster_offset & L2E_OFFSET_MASK) {
627         qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
628         return 0;
629     }
630
631     cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
632     if (cluster_offset < 0) {
633         qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
634         return 0;
635     }
636
637     nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
638                   (cluster_offset >> 9);
639
640     cluster_offset |= QCOW_OFLAG_COMPRESSED |
641                       ((uint64_t)nb_csectors << s->csize_shift);
642
643     /* update L2 table */
644
645     /* compressed clusters never have the copied flag */
646
647     BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
648     qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
649     l2_table[l2_index] = cpu_to_be64(cluster_offset);
650     ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
651     if (ret < 0) {
652         return 0;
653     }
654
655     return cluster_offset;
656 }
657
658 static int perform_cow(BlockDriverState *bs, QCowL2Meta *m, Qcow2COWRegion *r)
659 {
660     BDRVQcowState *s = bs->opaque;
661     int ret;
662
663     if (r->nb_sectors == 0) {
664         return 0;
665     }
666
667     qemu_co_mutex_unlock(&s->lock);
668     ret = copy_sectors(bs, m->offset / BDRV_SECTOR_SIZE, m->alloc_offset,
669                        r->offset / BDRV_SECTOR_SIZE,
670                        r->offset / BDRV_SECTOR_SIZE + r->nb_sectors);
671     qemu_co_mutex_lock(&s->lock);
672
673     if (ret < 0) {
674         return ret;
675     }
676
677     /*
678      * Before we update the L2 table to actually point to the new cluster, we
679      * need to be sure that the refcounts have been increased and COW was
680      * handled.
681      */
682     qcow2_cache_depends_on_flush(s->l2_table_cache);
683
684     return 0;
685 }
686
687 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
688 {
689     BDRVQcowState *s = bs->opaque;
690     int i, j = 0, l2_index, ret;
691     uint64_t *old_cluster, *l2_table;
692     uint64_t cluster_offset = m->alloc_offset;
693
694     trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
695     assert(m->nb_clusters > 0);
696
697     old_cluster = g_malloc(m->nb_clusters * sizeof(uint64_t));
698
699     /* copy content of unmodified sectors */
700     ret = perform_cow(bs, m, &m->cow_start);
701     if (ret < 0) {
702         goto err;
703     }
704
705     ret = perform_cow(bs, m, &m->cow_end);
706     if (ret < 0) {
707         goto err;
708     }
709
710     /* Update L2 table. */
711     if (s->use_lazy_refcounts) {
712         qcow2_mark_dirty(bs);
713     }
714     if (qcow2_need_accurate_refcounts(s)) {
715         qcow2_cache_set_dependency(bs, s->l2_table_cache,
716                                    s->refcount_block_cache);
717     }
718
719     ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
720     if (ret < 0) {
721         goto err;
722     }
723     qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
724
725     assert(l2_index + m->nb_clusters <= s->l2_size);
726     for (i = 0; i < m->nb_clusters; i++) {
727         /* if two concurrent writes happen to the same unallocated cluster
728          * each write allocates separate cluster and writes data concurrently.
729          * The first one to complete updates l2 table with pointer to its
730          * cluster the second one has to do RMW (which is done above by
731          * copy_sectors()), update l2 table with its cluster pointer and free
732          * old cluster. This is what this loop does */
733         if(l2_table[l2_index + i] != 0)
734             old_cluster[j++] = l2_table[l2_index + i];
735
736         l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
737                     (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
738      }
739
740
741     ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
742     if (ret < 0) {
743         goto err;
744     }
745
746     /*
747      * If this was a COW, we need to decrease the refcount of the old cluster.
748      * Also flush bs->file to get the right order for L2 and refcount update.
749      *
750      * Don't discard clusters that reach a refcount of 0 (e.g. compressed
751      * clusters), the next write will reuse them anyway.
752      */
753     if (j != 0) {
754         for (i = 0; i < j; i++) {
755             qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,
756                                     QCOW2_DISCARD_NEVER);
757         }
758     }
759
760     ret = 0;
761 err:
762     g_free(old_cluster);
763     return ret;
764  }
765
766 /*
767  * Returns the number of contiguous clusters that can be used for an allocating
768  * write, but require COW to be performed (this includes yet unallocated space,
769  * which must copy from the backing file)
770  */
771 static int count_cow_clusters(BDRVQcowState *s, int nb_clusters,
772     uint64_t *l2_table, int l2_index)
773 {
774     int i;
775
776     for (i = 0; i < nb_clusters; i++) {
777         uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);
778         int cluster_type = qcow2_get_cluster_type(l2_entry);
779
780         switch(cluster_type) {
781         case QCOW2_CLUSTER_NORMAL:
782             if (l2_entry & QCOW_OFLAG_COPIED) {
783                 goto out;
784             }
785             break;
786         case QCOW2_CLUSTER_UNALLOCATED:
787         case QCOW2_CLUSTER_COMPRESSED:
788         case QCOW2_CLUSTER_ZERO:
789             break;
790         default:
791             abort();
792         }
793     }
794
795 out:
796     assert(i <= nb_clusters);
797     return i;
798 }
799
800 /*
801  * Check if there already is an AIO write request in flight which allocates
802  * the same cluster. In this case we need to wait until the previous
803  * request has completed and updated the L2 table accordingly.
804  *
805  * Returns:
806  *   0       if there was no dependency. *cur_bytes indicates the number of
807  *           bytes from guest_offset that can be read before the next
808  *           dependency must be processed (or the request is complete)
809  *
810  *   -EAGAIN if we had to wait for another request, previously gathered
811  *           information on cluster allocation may be invalid now. The caller
812  *           must start over anyway, so consider *cur_bytes undefined.
813  */
814 static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
815     uint64_t *cur_bytes, QCowL2Meta **m)
816 {
817     BDRVQcowState *s = bs->opaque;
818     QCowL2Meta *old_alloc;
819     uint64_t bytes = *cur_bytes;
820
821     QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
822
823         uint64_t start = guest_offset;
824         uint64_t end = start + bytes;
825         uint64_t old_start = l2meta_cow_start(old_alloc);
826         uint64_t old_end = l2meta_cow_end(old_alloc);
827
828         if (end <= old_start || start >= old_end) {
829             /* No intersection */
830         } else {
831             if (start < old_start) {
832                 /* Stop at the start of a running allocation */
833                 bytes = old_start - start;
834             } else {
835                 bytes = 0;
836             }
837
838             /* Stop if already an l2meta exists. After yielding, it wouldn't
839              * be valid any more, so we'd have to clean up the old L2Metas
840              * and deal with requests depending on them before starting to
841              * gather new ones. Not worth the trouble. */
842             if (bytes == 0 && *m) {
843                 *cur_bytes = 0;
844                 return 0;
845             }
846
847             if (bytes == 0) {
848                 /* Wait for the dependency to complete. We need to recheck
849                  * the free/allocated clusters when we continue. */
850                 qemu_co_mutex_unlock(&s->lock);
851                 qemu_co_queue_wait(&old_alloc->dependent_requests);
852                 qemu_co_mutex_lock(&s->lock);
853                 return -EAGAIN;
854             }
855         }
856     }
857
858     /* Make sure that existing clusters and new allocations are only used up to
859      * the next dependency if we shortened the request above */
860     *cur_bytes = bytes;
861
862     return 0;
863 }
864
865 /*
866  * Checks how many already allocated clusters that don't require a copy on
867  * write there are at the given guest_offset (up to *bytes). If
868  * *host_offset is not zero, only physically contiguous clusters beginning at
869  * this host offset are counted.
870  *
871  * Note that guest_offset may not be cluster aligned. In this case, the
872  * returned *host_offset points to exact byte referenced by guest_offset and
873  * therefore isn't cluster aligned as well.
874  *
875  * Returns:
876  *   0:     if no allocated clusters are available at the given offset.
877  *          *bytes is normally unchanged. It is set to 0 if the cluster
878  *          is allocated and doesn't need COW, but doesn't have the right
879  *          physical offset.
880  *
881  *   1:     if allocated clusters that don't require a COW are available at
882  *          the requested offset. *bytes may have decreased and describes
883  *          the length of the area that can be written to.
884  *
885  *  -errno: in error cases
886  */
887 static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
888     uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
889 {
890     BDRVQcowState *s = bs->opaque;
891     int l2_index;
892     uint64_t cluster_offset;
893     uint64_t *l2_table;
894     unsigned int nb_clusters;
895     unsigned int keep_clusters;
896     int ret, pret;
897
898     trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
899                               *bytes);
900
901     assert(*host_offset == 0 ||    offset_into_cluster(s, guest_offset)
902                                 == offset_into_cluster(s, *host_offset));
903
904     /*
905      * Calculate the number of clusters to look for. We stop at L2 table
906      * boundaries to keep things simple.
907      */
908     nb_clusters =
909         size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
910
911     l2_index = offset_to_l2_index(s, guest_offset);
912     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
913
914     /* Find L2 entry for the first involved cluster */
915     ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
916     if (ret < 0) {
917         return ret;
918     }
919
920     cluster_offset = be64_to_cpu(l2_table[l2_index]);
921
922     /* Check how many clusters are already allocated and don't need COW */
923     if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL
924         && (cluster_offset & QCOW_OFLAG_COPIED))
925     {
926         /* If a specific host_offset is required, check it */
927         bool offset_matches =
928             (cluster_offset & L2E_OFFSET_MASK) == *host_offset;
929
930         if (*host_offset != 0 && !offset_matches) {
931             *bytes = 0;
932             ret = 0;
933             goto out;
934         }
935
936         /* We keep all QCOW_OFLAG_COPIED clusters */
937         keep_clusters =
938             count_contiguous_clusters(nb_clusters, s->cluster_size,
939                                       &l2_table[l2_index], 0,
940                                       QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);
941         assert(keep_clusters <= nb_clusters);
942
943         *bytes = MIN(*bytes,
944                  keep_clusters * s->cluster_size
945                  - offset_into_cluster(s, guest_offset));
946
947         ret = 1;
948     } else {
949         ret = 0;
950     }
951
952     /* Cleanup */
953 out:
954     pret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
955     if (pret < 0) {
956         return pret;
957     }
958
959     /* Only return a host offset if we actually made progress. Otherwise we
960      * would make requirements for handle_alloc() that it can't fulfill */
961     if (ret) {
962         *host_offset = (cluster_offset & L2E_OFFSET_MASK)
963                      + offset_into_cluster(s, guest_offset);
964     }
965
966     return ret;
967 }
968
969 /*
970  * Allocates new clusters for the given guest_offset.
971  *
972  * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
973  * contain the number of clusters that have been allocated and are contiguous
974  * in the image file.
975  *
976  * If *host_offset is non-zero, it specifies the offset in the image file at
977  * which the new clusters must start. *nb_clusters can be 0 on return in this
978  * case if the cluster at host_offset is already in use. If *host_offset is
979  * zero, the clusters can be allocated anywhere in the image file.
980  *
981  * *host_offset is updated to contain the offset into the image file at which
982  * the first allocated cluster starts.
983  *
984  * Return 0 on success and -errno in error cases. -EAGAIN means that the
985  * function has been waiting for another request and the allocation must be
986  * restarted, but the whole request should not be failed.
987  */
988 static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
989     uint64_t *host_offset, unsigned int *nb_clusters)
990 {
991     BDRVQcowState *s = bs->opaque;
992
993     trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
994                                          *host_offset, *nb_clusters);
995
996     /* Allocate new clusters */
997     trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
998     if (*host_offset == 0) {
999         int64_t cluster_offset =
1000             qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1001         if (cluster_offset < 0) {
1002             return cluster_offset;
1003         }
1004         *host_offset = cluster_offset;
1005         return 0;
1006     } else {
1007         int ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
1008         if (ret < 0) {
1009             return ret;
1010         }
1011         *nb_clusters = ret;
1012         return 0;
1013     }
1014 }
1015
1016 /*
1017  * Allocates new clusters for an area that either is yet unallocated or needs a
1018  * copy on write. If *host_offset is non-zero, clusters are only allocated if
1019  * the new allocation can match the specified host offset.
1020  *
1021  * Note that guest_offset may not be cluster aligned. In this case, the
1022  * returned *host_offset points to exact byte referenced by guest_offset and
1023  * therefore isn't cluster aligned as well.
1024  *
1025  * Returns:
1026  *   0:     if no clusters could be allocated. *bytes is set to 0,
1027  *          *host_offset is left unchanged.
1028  *
1029  *   1:     if new clusters were allocated. *bytes may be decreased if the
1030  *          new allocation doesn't cover all of the requested area.
1031  *          *host_offset is updated to contain the host offset of the first
1032  *          newly allocated cluster.
1033  *
1034  *  -errno: in error cases
1035  */
1036 static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
1037     uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1038 {
1039     BDRVQcowState *s = bs->opaque;
1040     int l2_index;
1041     uint64_t *l2_table;
1042     uint64_t entry;
1043     unsigned int nb_clusters;
1044     int ret;
1045
1046     uint64_t alloc_cluster_offset;
1047
1048     trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1049                              *bytes);
1050     assert(*bytes > 0);
1051
1052     /*
1053      * Calculate the number of clusters to look for. We stop at L2 table
1054      * boundaries to keep things simple.
1055      */
1056     nb_clusters =
1057         size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1058
1059     l2_index = offset_to_l2_index(s, guest_offset);
1060     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1061
1062     /* Find L2 entry for the first involved cluster */
1063     ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1064     if (ret < 0) {
1065         return ret;
1066     }
1067
1068     entry = be64_to_cpu(l2_table[l2_index]);
1069
1070     /* For the moment, overwrite compressed clusters one by one */
1071     if (entry & QCOW_OFLAG_COMPRESSED) {
1072         nb_clusters = 1;
1073     } else {
1074         nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);
1075     }
1076
1077     /* This function is only called when there were no non-COW clusters, so if
1078      * we can't find any unallocated or COW clusters either, something is
1079      * wrong with our code. */
1080     assert(nb_clusters > 0);
1081
1082     ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1083     if (ret < 0) {
1084         return ret;
1085     }
1086
1087     /* Allocate, if necessary at a given offset in the image file */
1088     alloc_cluster_offset = start_of_cluster(s, *host_offset);
1089     ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1090                                   &nb_clusters);
1091     if (ret < 0) {
1092         goto fail;
1093     }
1094
1095     /* Can't extend contiguous allocation */
1096     if (nb_clusters == 0) {
1097         *bytes = 0;
1098         return 0;
1099     }
1100
1101     /*
1102      * Save info needed for meta data update.
1103      *
1104      * requested_sectors: Number of sectors from the start of the first
1105      * newly allocated cluster to the end of the (possibly shortened
1106      * before) write request.
1107      *
1108      * avail_sectors: Number of sectors from the start of the first
1109      * newly allocated to the end of the last newly allocated cluster.
1110      *
1111      * nb_sectors: The number of sectors from the start of the first
1112      * newly allocated cluster to the end of the area that the write
1113      * request actually writes to (excluding COW at the end)
1114      */
1115     int requested_sectors =
1116         (*bytes + offset_into_cluster(s, guest_offset))
1117         >> BDRV_SECTOR_BITS;
1118     int avail_sectors = nb_clusters
1119                         << (s->cluster_bits - BDRV_SECTOR_BITS);
1120     int alloc_n_start = offset_into_cluster(s, guest_offset)
1121                         >> BDRV_SECTOR_BITS;
1122     int nb_sectors = MIN(requested_sectors, avail_sectors);
1123     QCowL2Meta *old_m = *m;
1124
1125     *m = g_malloc0(sizeof(**m));
1126
1127     **m = (QCowL2Meta) {
1128         .next           = old_m,
1129
1130         .alloc_offset   = alloc_cluster_offset,
1131         .offset         = start_of_cluster(s, guest_offset),
1132         .nb_clusters    = nb_clusters,
1133         .nb_available   = nb_sectors,
1134
1135         .cow_start = {
1136             .offset     = 0,
1137             .nb_sectors = alloc_n_start,
1138         },
1139         .cow_end = {
1140             .offset     = nb_sectors * BDRV_SECTOR_SIZE,
1141             .nb_sectors = avail_sectors - nb_sectors,
1142         },
1143     };
1144     qemu_co_queue_init(&(*m)->dependent_requests);
1145     QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1146
1147     *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
1148     *bytes = MIN(*bytes, (nb_sectors * BDRV_SECTOR_SIZE)
1149                          - offset_into_cluster(s, guest_offset));
1150     assert(*bytes != 0);
1151
1152     return 1;
1153
1154 fail:
1155     if (*m && (*m)->nb_clusters > 0) {
1156         QLIST_REMOVE(*m, next_in_flight);
1157     }
1158     return ret;
1159 }
1160
1161 /*
1162  * alloc_cluster_offset
1163  *
1164  * For a given offset on the virtual disk, find the cluster offset in qcow2
1165  * file. If the offset is not found, allocate a new cluster.
1166  *
1167  * If the cluster was already allocated, m->nb_clusters is set to 0 and
1168  * other fields in m are meaningless.
1169  *
1170  * If the cluster is newly allocated, m->nb_clusters is set to the number of
1171  * contiguous clusters that have been allocated. In this case, the other
1172  * fields of m are valid and contain information about the first allocated
1173  * cluster.
1174  *
1175  * If the request conflicts with another write request in flight, the coroutine
1176  * is queued and will be reentered when the dependency has completed.
1177  *
1178  * Return 0 on success and -errno in error cases
1179  */
1180 int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
1181     int n_start, int n_end, int *num, uint64_t *host_offset, QCowL2Meta **m)
1182 {
1183     BDRVQcowState *s = bs->opaque;
1184     uint64_t start, remaining;
1185     uint64_t cluster_offset;
1186     uint64_t cur_bytes;
1187     int ret;
1188
1189     trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset,
1190                                       n_start, n_end);
1191
1192     assert(n_start * BDRV_SECTOR_SIZE == offset_into_cluster(s, offset));
1193     offset = start_of_cluster(s, offset);
1194
1195 again:
1196     start = offset + (n_start << BDRV_SECTOR_BITS);
1197     remaining = (n_end - n_start) << BDRV_SECTOR_BITS;
1198     cluster_offset = 0;
1199     *host_offset = 0;
1200     cur_bytes = 0;
1201     *m = NULL;
1202
1203     while (true) {
1204
1205         if (!*host_offset) {
1206             *host_offset = start_of_cluster(s, cluster_offset);
1207         }
1208
1209         assert(remaining >= cur_bytes);
1210
1211         start           += cur_bytes;
1212         remaining       -= cur_bytes;
1213         cluster_offset  += cur_bytes;
1214
1215         if (remaining == 0) {
1216             break;
1217         }
1218
1219         cur_bytes = remaining;
1220
1221         /*
1222          * Now start gathering as many contiguous clusters as possible:
1223          *
1224          * 1. Check for overlaps with in-flight allocations
1225          *
1226          *      a) Overlap not in the first cluster -> shorten this request and
1227          *         let the caller handle the rest in its next loop iteration.
1228          *
1229          *      b) Real overlaps of two requests. Yield and restart the search
1230          *         for contiguous clusters (the situation could have changed
1231          *         while we were sleeping)
1232          *
1233          *      c) TODO: Request starts in the same cluster as the in-flight
1234          *         allocation ends. Shorten the COW of the in-fight allocation,
1235          *         set cluster_offset to write to the same cluster and set up
1236          *         the right synchronisation between the in-flight request and
1237          *         the new one.
1238          */
1239         ret = handle_dependencies(bs, start, &cur_bytes, m);
1240         if (ret == -EAGAIN) {
1241             /* Currently handle_dependencies() doesn't yield if we already had
1242              * an allocation. If it did, we would have to clean up the L2Meta
1243              * structs before starting over. */
1244             assert(*m == NULL);
1245             goto again;
1246         } else if (ret < 0) {
1247             return ret;
1248         } else if (cur_bytes == 0) {
1249             break;
1250         } else {
1251             /* handle_dependencies() may have decreased cur_bytes (shortened
1252              * the allocations below) so that the next dependency is processed
1253              * correctly during the next loop iteration. */
1254         }
1255
1256         /*
1257          * 2. Count contiguous COPIED clusters.
1258          */
1259         ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1260         if (ret < 0) {
1261             return ret;
1262         } else if (ret) {
1263             continue;
1264         } else if (cur_bytes == 0) {
1265             break;
1266         }
1267
1268         /*
1269          * 3. If the request still hasn't completed, allocate new clusters,
1270          *    considering any cluster_offset of steps 1c or 2.
1271          */
1272         ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1273         if (ret < 0) {
1274             return ret;
1275         } else if (ret) {
1276             continue;
1277         } else {
1278             assert(cur_bytes == 0);
1279             break;
1280         }
1281     }
1282
1283     *num = (n_end - n_start) - (remaining >> BDRV_SECTOR_BITS);
1284     assert(*num > 0);
1285     assert(*host_offset != 0);
1286
1287     return 0;
1288 }
1289
1290 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1291                              const uint8_t *buf, int buf_size)
1292 {
1293     z_stream strm1, *strm = &strm1;
1294     int ret, out_len;
1295
1296     memset(strm, 0, sizeof(*strm));
1297
1298     strm->next_in = (uint8_t *)buf;
1299     strm->avail_in = buf_size;
1300     strm->next_out = out_buf;
1301     strm->avail_out = out_buf_size;
1302
1303     ret = inflateInit2(strm, -12);
1304     if (ret != Z_OK)
1305         return -1;
1306     ret = inflate(strm, Z_FINISH);
1307     out_len = strm->next_out - out_buf;
1308     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1309         out_len != out_buf_size) {
1310         inflateEnd(strm);
1311         return -1;
1312     }
1313     inflateEnd(strm);
1314     return 0;
1315 }
1316
1317 int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
1318 {
1319     BDRVQcowState *s = bs->opaque;
1320     int ret, csize, nb_csectors, sector_offset;
1321     uint64_t coffset;
1322
1323     coffset = cluster_offset & s->cluster_offset_mask;
1324     if (s->cluster_cache_offset != coffset) {
1325         nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1326         sector_offset = coffset & 511;
1327         csize = nb_csectors * 512 - sector_offset;
1328         BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
1329         ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data, nb_csectors);
1330         if (ret < 0) {
1331             return ret;
1332         }
1333         if (decompress_buffer(s->cluster_cache, s->cluster_size,
1334                               s->cluster_data + sector_offset, csize) < 0) {
1335             return -EIO;
1336         }
1337         s->cluster_cache_offset = coffset;
1338     }
1339     return 0;
1340 }
1341
1342 /*
1343  * This discards as many clusters of nb_clusters as possible at once (i.e.
1344  * all clusters in the same L2 table) and returns the number of discarded
1345  * clusters.
1346  */
1347 static int discard_single_l2(BlockDriverState *bs, uint64_t offset,
1348     unsigned int nb_clusters, enum qcow2_discard_type type)
1349 {
1350     BDRVQcowState *s = bs->opaque;
1351     uint64_t *l2_table;
1352     int l2_index;
1353     int ret;
1354     int i;
1355
1356     ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1357     if (ret < 0) {
1358         return ret;
1359     }
1360
1361     /* Limit nb_clusters to one L2 table */
1362     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1363
1364     for (i = 0; i < nb_clusters; i++) {
1365         uint64_t old_offset;
1366
1367         old_offset = be64_to_cpu(l2_table[l2_index + i]);
1368         if ((old_offset & L2E_OFFSET_MASK) == 0) {
1369             continue;
1370         }
1371
1372         /* First remove L2 entries */
1373         qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1374         l2_table[l2_index + i] = cpu_to_be64(0);
1375
1376         /* Then decrease the refcount */
1377         qcow2_free_any_clusters(bs, old_offset, 1, type);
1378     }
1379
1380     ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1381     if (ret < 0) {
1382         return ret;
1383     }
1384
1385     return nb_clusters;
1386 }
1387
1388 int qcow2_discard_clusters(BlockDriverState *bs, uint64_t offset,
1389     int nb_sectors, enum qcow2_discard_type type)
1390 {
1391     BDRVQcowState *s = bs->opaque;
1392     uint64_t end_offset;
1393     unsigned int nb_clusters;
1394     int ret;
1395
1396     end_offset = offset + (nb_sectors << BDRV_SECTOR_BITS);
1397
1398     /* Round start up and end down */
1399     offset = align_offset(offset, s->cluster_size);
1400     end_offset &= ~(s->cluster_size - 1);
1401
1402     if (offset > end_offset) {
1403         return 0;
1404     }
1405
1406     nb_clusters = size_to_clusters(s, end_offset - offset);
1407
1408     s->cache_discards = true;
1409
1410     /* Each L2 table is handled by its own loop iteration */
1411     while (nb_clusters > 0) {
1412         ret = discard_single_l2(bs, offset, nb_clusters, type);
1413         if (ret < 0) {
1414             goto fail;
1415         }
1416
1417         nb_clusters -= ret;
1418         offset += (ret * s->cluster_size);
1419     }
1420
1421     ret = 0;
1422 fail:
1423     s->cache_discards = false;
1424     qcow2_process_discards(bs, ret);
1425
1426     return ret;
1427 }
1428
1429 /*
1430  * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1431  * all clusters in the same L2 table) and returns the number of zeroed
1432  * clusters.
1433  */
1434 static int zero_single_l2(BlockDriverState *bs, uint64_t offset,
1435     unsigned int nb_clusters)
1436 {
1437     BDRVQcowState *s = bs->opaque;
1438     uint64_t *l2_table;
1439     int l2_index;
1440     int ret;
1441     int i;
1442
1443     ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1444     if (ret < 0) {
1445         return ret;
1446     }
1447
1448     /* Limit nb_clusters to one L2 table */
1449     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1450
1451     for (i = 0; i < nb_clusters; i++) {
1452         uint64_t old_offset;
1453
1454         old_offset = be64_to_cpu(l2_table[l2_index + i]);
1455
1456         /* Update L2 entries */
1457         qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1458         if (old_offset & QCOW_OFLAG_COMPRESSED) {
1459             l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1460             qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
1461         } else {
1462             l2_table[l2_index + i] |= cpu_to_be64(QCOW_OFLAG_ZERO);
1463         }
1464     }
1465
1466     ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1467     if (ret < 0) {
1468         return ret;
1469     }
1470
1471     return nb_clusters;
1472 }
1473
1474 int qcow2_zero_clusters(BlockDriverState *bs, uint64_t offset, int nb_sectors)
1475 {
1476     BDRVQcowState *s = bs->opaque;
1477     unsigned int nb_clusters;
1478     int ret;
1479
1480     /* The zero flag is only supported by version 3 and newer */
1481     if (s->qcow_version < 3) {
1482         return -ENOTSUP;
1483     }
1484
1485     /* Each L2 table is handled by its own loop iteration */
1486     nb_clusters = size_to_clusters(s, nb_sectors << BDRV_SECTOR_BITS);
1487
1488     s->cache_discards = true;
1489
1490     while (nb_clusters > 0) {
1491         ret = zero_single_l2(bs, offset, nb_clusters);
1492         if (ret < 0) {
1493             goto fail;
1494         }
1495
1496         nb_clusters -= ret;
1497         offset += (ret * s->cluster_size);
1498     }
1499
1500     ret = 0;
1501 fail:
1502     s->cache_discards = false;
1503     qcow2_process_discards(bs, ret);
1504
1505     return ret;
1506 }
1507
1508 /*
1509  * Expands all zero clusters in a specific L1 table (or deallocates them, for
1510  * non-backed non-pre-allocated zero clusters).
1511  *
1512  * expanded_clusters is a bitmap where every bit corresponds to one cluster in
1513  * the image file; a bit gets set if the corresponding cluster has been used for
1514  * zero expansion (i.e., has been filled with zeroes and is referenced from an
1515  * L2 table). nb_clusters contains the total cluster count of the image file,
1516  * i.e., the number of bits in expanded_clusters.
1517  */
1518 static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
1519                                       int l1_size, uint8_t **expanded_clusters,
1520                                       uint64_t *nb_clusters)
1521 {
1522     BDRVQcowState *s = bs->opaque;
1523     bool is_active_l1 = (l1_table == s->l1_table);
1524     uint64_t *l2_table = NULL;
1525     int ret;
1526     int i, j;
1527
1528     if (!is_active_l1) {
1529         /* inactive L2 tables require a buffer to be stored in when loading
1530          * them from disk */
1531         l2_table = qemu_blockalign(bs, s->cluster_size);
1532     }
1533
1534     for (i = 0; i < l1_size; i++) {
1535         uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1536         bool l2_dirty = false;
1537
1538         if (!l2_offset) {
1539             /* unallocated */
1540             continue;
1541         }
1542
1543         if (is_active_l1) {
1544             /* get active L2 tables from cache */
1545             ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1546                     (void **)&l2_table);
1547         } else {
1548             /* load inactive L2 tables from disk */
1549             ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1550                     (void *)l2_table, s->cluster_sectors);
1551         }
1552         if (ret < 0) {
1553             goto fail;
1554         }
1555
1556         for (j = 0; j < s->l2_size; j++) {
1557             uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1558             int64_t offset = l2_entry & L2E_OFFSET_MASK, cluster_index;
1559             int cluster_type = qcow2_get_cluster_type(l2_entry);
1560             bool preallocated = offset != 0;
1561
1562             if (cluster_type == QCOW2_CLUSTER_NORMAL) {
1563                 cluster_index = offset >> s->cluster_bits;
1564                 assert((cluster_index >= 0) && (cluster_index < *nb_clusters));
1565                 if ((*expanded_clusters)[cluster_index / 8] &
1566                     (1 << (cluster_index % 8))) {
1567                     /* Probably a shared L2 table; this cluster was a zero
1568                      * cluster which has been expanded, its refcount
1569                      * therefore most likely requires an update. */
1570                     ret = qcow2_update_cluster_refcount(bs, cluster_index, 1,
1571                                                         QCOW2_DISCARD_NEVER);
1572                     if (ret < 0) {
1573                         goto fail;
1574                     }
1575                     /* Since we just increased the refcount, the COPIED flag may
1576                      * no longer be set. */
1577                     l2_table[j] = cpu_to_be64(l2_entry & ~QCOW_OFLAG_COPIED);
1578                     l2_dirty = true;
1579                 }
1580                 continue;
1581             }
1582             else if (qcow2_get_cluster_type(l2_entry) != QCOW2_CLUSTER_ZERO) {
1583                 continue;
1584             }
1585
1586             if (!preallocated) {
1587                 if (!bs->backing_hd) {
1588                     /* not backed; therefore we can simply deallocate the
1589                      * cluster */
1590                     l2_table[j] = 0;
1591                     l2_dirty = true;
1592                     continue;
1593                 }
1594
1595                 offset = qcow2_alloc_clusters(bs, s->cluster_size);
1596                 if (offset < 0) {
1597                     ret = offset;
1598                     goto fail;
1599                 }
1600             }
1601
1602             ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
1603                                                 offset, s->cluster_size);
1604             if (ret < 0) {
1605                 if (!preallocated) {
1606                     qcow2_free_clusters(bs, offset, s->cluster_size,
1607                                         QCOW2_DISCARD_ALWAYS);
1608                 }
1609                 goto fail;
1610             }
1611
1612             ret = bdrv_write_zeroes(bs->file, offset / BDRV_SECTOR_SIZE,
1613                                     s->cluster_sectors);
1614             if (ret < 0) {
1615                 if (!preallocated) {
1616                     qcow2_free_clusters(bs, offset, s->cluster_size,
1617                                         QCOW2_DISCARD_ALWAYS);
1618                 }
1619                 goto fail;
1620             }
1621
1622             l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
1623             l2_dirty = true;
1624
1625             cluster_index = offset >> s->cluster_bits;
1626
1627             if (cluster_index >= *nb_clusters) {
1628                 uint64_t old_bitmap_size = (*nb_clusters + 7) / 8;
1629                 uint64_t new_bitmap_size;
1630                 /* The offset may lie beyond the old end of the underlying image
1631                  * file for growable files only */
1632                 assert(bs->file->growable);
1633                 *nb_clusters = size_to_clusters(s, bs->file->total_sectors *
1634                                                 BDRV_SECTOR_SIZE);
1635                 new_bitmap_size = (*nb_clusters + 7) / 8;
1636                 *expanded_clusters = g_realloc(*expanded_clusters,
1637                                                new_bitmap_size);
1638                 /* clear the newly allocated space */
1639                 memset(&(*expanded_clusters)[old_bitmap_size], 0,
1640                        new_bitmap_size - old_bitmap_size);
1641             }
1642
1643             assert((cluster_index >= 0) && (cluster_index < *nb_clusters));
1644             (*expanded_clusters)[cluster_index / 8] |= 1 << (cluster_index % 8);
1645         }
1646
1647         if (is_active_l1) {
1648             if (l2_dirty) {
1649                 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1650                 qcow2_cache_depends_on_flush(s->l2_table_cache);
1651             }
1652             ret = qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
1653             if (ret < 0) {
1654                 l2_table = NULL;
1655                 goto fail;
1656             }
1657         } else {
1658             if (l2_dirty) {
1659                 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT &
1660                         ~(QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2), l2_offset,
1661                         s->cluster_size);
1662                 if (ret < 0) {
1663                     goto fail;
1664                 }
1665
1666                 ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1667                         (void *)l2_table, s->cluster_sectors);
1668                 if (ret < 0) {
1669                     goto fail;
1670                 }
1671             }
1672         }
1673     }
1674
1675     ret = 0;
1676
1677 fail:
1678     if (l2_table) {
1679         if (!is_active_l1) {
1680             qemu_vfree(l2_table);
1681         } else {
1682             if (ret < 0) {
1683                 qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
1684             } else {
1685                 ret = qcow2_cache_put(bs, s->l2_table_cache,
1686                         (void **)&l2_table);
1687             }
1688         }
1689     }
1690     return ret;
1691 }
1692
1693 /*
1694  * For backed images, expands all zero clusters on the image. For non-backed
1695  * images, deallocates all non-pre-allocated zero clusters (and claims the
1696  * allocation for pre-allocated ones). This is important for downgrading to a
1697  * qcow2 version which doesn't yet support metadata zero clusters.
1698  */
1699 int qcow2_expand_zero_clusters(BlockDriverState *bs)
1700 {
1701     BDRVQcowState *s = bs->opaque;
1702     uint64_t *l1_table = NULL;
1703     uint64_t nb_clusters;
1704     uint8_t *expanded_clusters;
1705     int ret;
1706     int i, j;
1707
1708     nb_clusters = size_to_clusters(s, bs->file->total_sectors *
1709                                    BDRV_SECTOR_SIZE);
1710     expanded_clusters = g_malloc0((nb_clusters + 7) / 8);
1711
1712     ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
1713                                      &expanded_clusters, &nb_clusters);
1714     if (ret < 0) {
1715         goto fail;
1716     }
1717
1718     /* Inactive L1 tables may point to active L2 tables - therefore it is
1719      * necessary to flush the L2 table cache before trying to access the L2
1720      * tables pointed to by inactive L1 entries (else we might try to expand
1721      * zero clusters that have already been expanded); furthermore, it is also
1722      * necessary to empty the L2 table cache, since it may contain tables which
1723      * are now going to be modified directly on disk, bypassing the cache.
1724      * qcow2_cache_empty() does both for us. */
1725     ret = qcow2_cache_empty(bs, s->l2_table_cache);
1726     if (ret < 0) {
1727         goto fail;
1728     }
1729
1730     for (i = 0; i < s->nb_snapshots; i++) {
1731         int l1_sectors = (s->snapshots[i].l1_size * sizeof(uint64_t) +
1732                 BDRV_SECTOR_SIZE - 1) / BDRV_SECTOR_SIZE;
1733
1734         l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);
1735
1736         ret = bdrv_read(bs->file, s->snapshots[i].l1_table_offset /
1737                 BDRV_SECTOR_SIZE, (void *)l1_table, l1_sectors);
1738         if (ret < 0) {
1739             goto fail;
1740         }
1741
1742         for (j = 0; j < s->snapshots[i].l1_size; j++) {
1743             be64_to_cpus(&l1_table[j]);
1744         }
1745
1746         ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
1747                                          &expanded_clusters, &nb_clusters);
1748         if (ret < 0) {
1749             goto fail;
1750         }
1751     }
1752
1753     ret = 0;
1754
1755 fail:
1756     g_free(expanded_clusters);
1757     g_free(l1_table);
1758     return ret;
1759 }
This page took 0.123102 seconds and 4 git commands to generate.