Statistics
| Branch: | Revision:

root / block / qcow2-cluster.c @ 50779cc2

History | View | Annotate | Download (26.2 kB)

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_int.h"
29
#include "block/qcow2.h"
30

    
31
int qcow2_grow_l1_table(BlockDriverState *bs, int min_size)
32
{
33
    BDRVQcowState *s = bs->opaque;
34
    int new_l1_size, new_l1_size2, ret, i;
35
    uint64_t *new_l1_table;
36
    int64_t new_l1_table_offset;
37
    uint8_t data[12];
38

    
39
    new_l1_size = s->l1_size;
40
    if (min_size <= new_l1_size)
41
        return 0;
42
    if (new_l1_size == 0) {
43
        new_l1_size = 1;
44
    }
45
    while (min_size > new_l1_size) {
46
        new_l1_size = (new_l1_size * 3 + 1) / 2;
47
    }
48
#ifdef DEBUG_ALLOC2
49
    printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
50
#endif
51

    
52
    new_l1_size2 = sizeof(uint64_t) * new_l1_size;
53
    new_l1_table = qemu_mallocz(align_offset(new_l1_size2, 512));
54
    memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
55

    
56
    /* write new table (align to cluster) */
57
    BLKDBG_EVENT(s->hd, BLKDBG_L1_GROW_ALLOC_TABLE);
58
    new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
59
    if (new_l1_table_offset < 0) {
60
        qemu_free(new_l1_table);
61
        return new_l1_table_offset;
62
    }
63

    
64
    BLKDBG_EVENT(s->hd, BLKDBG_L1_GROW_WRITE_TABLE);
65
    for(i = 0; i < s->l1_size; i++)
66
        new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
67
    ret = bdrv_pwrite(s->hd, new_l1_table_offset, new_l1_table, new_l1_size2);
68
    if (ret != new_l1_size2)
69
        goto fail;
70
    for(i = 0; i < s->l1_size; i++)
71
        new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
72

    
73
    /* set new table */
74
    BLKDBG_EVENT(s->hd, BLKDBG_L1_GROW_ACTIVATE_TABLE);
75
    cpu_to_be32w((uint32_t*)data, new_l1_size);
76
    cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);
77
    ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, l1_size), data,sizeof(data));
78
    if (ret != sizeof(data)) {
79
        goto fail;
80
    }
81
    qemu_free(s->l1_table);
82
    qcow2_free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
83
    s->l1_table_offset = new_l1_table_offset;
84
    s->l1_table = new_l1_table;
85
    s->l1_size = new_l1_size;
86
    return 0;
87
 fail:
88
    qemu_free(new_l1_table);
89
    qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2);
90
    return ret < 0 ? ret : -EIO;
91
}
92

    
93
void qcow2_l2_cache_reset(BlockDriverState *bs)
94
{
95
    BDRVQcowState *s = bs->opaque;
96

    
97
    memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
98
    memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
99
    memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
100
}
101

    
102
static inline int l2_cache_new_entry(BlockDriverState *bs)
103
{
104
    BDRVQcowState *s = bs->opaque;
105
    uint32_t min_count;
106
    int min_index, i;
107

    
108
    /* find a new entry in the least used one */
109
    min_index = 0;
110
    min_count = 0xffffffff;
111
    for(i = 0; i < L2_CACHE_SIZE; i++) {
112
        if (s->l2_cache_counts[i] < min_count) {
113
            min_count = s->l2_cache_counts[i];
114
            min_index = i;
115
        }
116
    }
117
    return min_index;
118
}
119

    
120
/*
121
 * seek_l2_table
122
 *
123
 * seek l2_offset in the l2_cache table
124
 * if not found, return NULL,
125
 * if found,
126
 *   increments the l2 cache hit count of the entry,
127
 *   if counter overflow, divide by two all counters
128
 *   return the pointer to the l2 cache entry
129
 *
130
 */
131

    
132
static uint64_t *seek_l2_table(BDRVQcowState *s, uint64_t l2_offset)
133
{
134
    int i, j;
135

    
136
    for(i = 0; i < L2_CACHE_SIZE; i++) {
137
        if (l2_offset == s->l2_cache_offsets[i]) {
138
            /* increment the hit count */
139
            if (++s->l2_cache_counts[i] == 0xffffffff) {
140
                for(j = 0; j < L2_CACHE_SIZE; j++) {
141
                    s->l2_cache_counts[j] >>= 1;
142
                }
143
            }
144
            return s->l2_cache + (i << s->l2_bits);
145
        }
146
    }
147
    return NULL;
148
}
149

    
150
/*
151
 * l2_load
152
 *
153
 * Loads a L2 table into memory. If the table is in the cache, the cache
154
 * is used; otherwise the L2 table is loaded from the image file.
155
 *
156
 * Returns a pointer to the L2 table on success, or NULL if the read from
157
 * the image file failed.
158
 */
159

    
160
static uint64_t *l2_load(BlockDriverState *bs, uint64_t l2_offset)
161
{
162
    BDRVQcowState *s = bs->opaque;
163
    int min_index;
164
    uint64_t *l2_table;
165

    
166
    /* seek if the table for the given offset is in the cache */
167

    
168
    l2_table = seek_l2_table(s, l2_offset);
169
    if (l2_table != NULL)
170
        return l2_table;
171

    
172
    /* not found: load a new entry in the least used one */
173

    
174
    min_index = l2_cache_new_entry(bs);
175
    l2_table = s->l2_cache + (min_index << s->l2_bits);
176

    
177
    BLKDBG_EVENT(s->hd, BLKDBG_L2_LOAD);
178
    if (bdrv_pread(s->hd, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
179
        s->l2_size * sizeof(uint64_t))
180
        return NULL;
181
    s->l2_cache_offsets[min_index] = l2_offset;
182
    s->l2_cache_counts[min_index] = 1;
183

    
184
    return l2_table;
185
}
186

    
187
/*
188
 * Writes one sector of the L1 table to the disk (can't update single entries
189
 * and we really don't want bdrv_pread to perform a read-modify-write)
190
 */
191
#define L1_ENTRIES_PER_SECTOR (512 / 8)
192
static int write_l1_entry(BDRVQcowState *s, int l1_index)
193
{
194
    uint64_t buf[L1_ENTRIES_PER_SECTOR];
195
    int l1_start_index;
196
    int i;
197

    
198
    l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);
199
    for (i = 0; i < L1_ENTRIES_PER_SECTOR; i++) {
200
        buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
201
    }
202

    
203
    BLKDBG_EVENT(s->hd, BLKDBG_L1_UPDATE);
204
    if (bdrv_pwrite(s->hd, s->l1_table_offset + 8 * l1_start_index,
205
        buf, sizeof(buf)) != sizeof(buf))
206
    {
207
        return -1;
208
    }
209

    
210
    return 0;
211
}
212

    
213
/*
214
 * l2_allocate
215
 *
216
 * Allocate a new l2 entry in the file. If l1_index points to an already
217
 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
218
 * table) copy the contents of the old L2 table into the newly allocated one.
219
 * Otherwise the new table is initialized with zeros.
220
 *
221
 */
222

    
223
static uint64_t *l2_allocate(BlockDriverState *bs, int l1_index)
224
{
225
    BDRVQcowState *s = bs->opaque;
226
    int min_index;
227
    uint64_t old_l2_offset;
228
    uint64_t *l2_table;
229
    int64_t l2_offset;
230

    
231
    old_l2_offset = s->l1_table[l1_index];
232

    
233
    /* allocate a new l2 entry */
234

    
235
    l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
236
    if (l2_offset < 0) {
237
        return NULL;
238
    }
239

    
240
    /* update the L1 entry */
241

    
242
    s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
243
    if (write_l1_entry(s, l1_index) < 0) {
244
        return NULL;
245
    }
246

    
247
    /* allocate a new entry in the l2 cache */
248

    
249
    min_index = l2_cache_new_entry(bs);
250
    l2_table = s->l2_cache + (min_index << s->l2_bits);
251

    
252
    if (old_l2_offset == 0) {
253
        /* if there was no old l2 table, clear the new table */
254
        memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
255
    } else {
256
        /* if there was an old l2 table, read it from the disk */
257
        BLKDBG_EVENT(s->hd, BLKDBG_L2_ALLOC_COW_READ);
258
        if (bdrv_pread(s->hd, old_l2_offset,
259
                       l2_table, s->l2_size * sizeof(uint64_t)) !=
260
            s->l2_size * sizeof(uint64_t))
261
            return NULL;
262
    }
263
    /* write the l2 table to the file */
264
    BLKDBG_EVENT(s->hd, BLKDBG_L2_ALLOC_WRITE);
265
    if (bdrv_pwrite(s->hd, l2_offset,
266
                    l2_table, s->l2_size * sizeof(uint64_t)) !=
267
        s->l2_size * sizeof(uint64_t))
268
        return NULL;
269

    
270
    /* update the l2 cache entry */
271

    
272
    s->l2_cache_offsets[min_index] = l2_offset;
273
    s->l2_cache_counts[min_index] = 1;
274

    
275
    return l2_table;
276
}
277

    
278
static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
279
        uint64_t *l2_table, uint64_t start, uint64_t mask)
280
{
281
    int i;
282
    uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask;
283

    
284
    if (!offset)
285
        return 0;
286

    
287
    for (i = start; i < start + nb_clusters; i++)
288
        if (offset + (uint64_t) i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask))
289
            break;
290

    
291
        return (i - start);
292
}
293

    
294
static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
295
{
296
    int i = 0;
297

    
298
    while(nb_clusters-- && l2_table[i] == 0)
299
        i++;
300

    
301
    return i;
302
}
303

    
304
/* The crypt function is compatible with the linux cryptoloop
305
   algorithm for < 4 GB images. NOTE: out_buf == in_buf is
306
   supported */
307
void qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
308
                           uint8_t *out_buf, const uint8_t *in_buf,
309
                           int nb_sectors, int enc,
310
                           const AES_KEY *key)
311
{
312
    union {
313
        uint64_t ll[2];
314
        uint8_t b[16];
315
    } ivec;
316
    int i;
317

    
318
    for(i = 0; i < nb_sectors; i++) {
319
        ivec.ll[0] = cpu_to_le64(sector_num);
320
        ivec.ll[1] = 0;
321
        AES_cbc_encrypt(in_buf, out_buf, 512, key,
322
                        ivec.b, enc);
323
        sector_num++;
324
        in_buf += 512;
325
        out_buf += 512;
326
    }
327
}
328

    
329

    
330
static int qcow_read(BlockDriverState *bs, int64_t sector_num,
331
                     uint8_t *buf, int nb_sectors)
332
{
333
    BDRVQcowState *s = bs->opaque;
334
    int ret, index_in_cluster, n, n1;
335
    uint64_t cluster_offset;
336

    
337
    while (nb_sectors > 0) {
338
        n = nb_sectors;
339
        cluster_offset = qcow2_get_cluster_offset(bs, sector_num << 9, &n);
340
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
341
        if (!cluster_offset) {
342
            if (bs->backing_hd) {
343
                /* read from the base image */
344
                n1 = qcow2_backing_read1(bs->backing_hd, sector_num, buf, n);
345
                if (n1 > 0) {
346
                    BLKDBG_EVENT(s->hd, BLKDBG_READ_BACKING);
347
                    ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
348
                    if (ret < 0)
349
                        return -1;
350
                }
351
            } else {
352
                memset(buf, 0, 512 * n);
353
            }
354
        } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
355
            if (qcow2_decompress_cluster(s, cluster_offset) < 0)
356
                return -1;
357
            memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
358
        } else {
359
            BLKDBG_EVENT(s->hd, BLKDBG_READ);
360
            ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
361
            if (ret != n * 512)
362
                return -1;
363
            if (s->crypt_method) {
364
                qcow2_encrypt_sectors(s, sector_num, buf, buf, n, 0,
365
                                &s->aes_decrypt_key);
366
            }
367
        }
368
        nb_sectors -= n;
369
        sector_num += n;
370
        buf += n * 512;
371
    }
372
    return 0;
373
}
374

    
375
static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,
376
                        uint64_t cluster_offset, int n_start, int n_end)
377
{
378
    BDRVQcowState *s = bs->opaque;
379
    int n, ret;
380

    
381
    n = n_end - n_start;
382
    if (n <= 0)
383
        return 0;
384
    BLKDBG_EVENT(s->hd, BLKDBG_COW_READ);
385
    ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);
386
    if (ret < 0)
387
        return ret;
388
    if (s->crypt_method) {
389
        qcow2_encrypt_sectors(s, start_sect + n_start,
390
                        s->cluster_data,
391
                        s->cluster_data, n, 1,
392
                        &s->aes_encrypt_key);
393
    }
394
    BLKDBG_EVENT(s->hd, BLKDBG_COW_WRITE);
395
    ret = bdrv_write(s->hd, (cluster_offset >> 9) + n_start,
396
                     s->cluster_data, n);
397
    if (ret < 0)
398
        return ret;
399
    return 0;
400
}
401

    
402

    
403
/*
404
 * get_cluster_offset
405
 *
406
 * For a given offset of the disk image, return cluster offset in
407
 * qcow2 file.
408
 *
409
 * on entry, *num is the number of contiguous clusters we'd like to
410
 * access following offset.
411
 *
412
 * on exit, *num is the number of contiguous clusters we can read.
413
 *
414
 * Return 1, if the offset is found
415
 * Return 0, otherwise.
416
 *
417
 */
418

    
419
uint64_t qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
420
    int *num)
421
{
422
    BDRVQcowState *s = bs->opaque;
423
    unsigned int l1_index, l2_index;
424
    uint64_t l2_offset, *l2_table, cluster_offset;
425
    int l1_bits, c;
426
    unsigned int index_in_cluster, nb_clusters;
427
    uint64_t nb_available, nb_needed;
428

    
429
    index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
430
    nb_needed = *num + index_in_cluster;
431

    
432
    l1_bits = s->l2_bits + s->cluster_bits;
433

    
434
    /* compute how many bytes there are between the offset and
435
     * the end of the l1 entry
436
     */
437

    
438
    nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));
439

    
440
    /* compute the number of available sectors */
441

    
442
    nb_available = (nb_available >> 9) + index_in_cluster;
443

    
444
    if (nb_needed > nb_available) {
445
        nb_needed = nb_available;
446
    }
447

    
448
    cluster_offset = 0;
449

    
450
    /* seek the the l2 offset in the l1 table */
451

    
452
    l1_index = offset >> l1_bits;
453
    if (l1_index >= s->l1_size)
454
        goto out;
455

    
456
    l2_offset = s->l1_table[l1_index];
457

    
458
    /* seek the l2 table of the given l2 offset */
459

    
460
    if (!l2_offset)
461
        goto out;
462

    
463
    /* load the l2 table in memory */
464

    
465
    l2_offset &= ~QCOW_OFLAG_COPIED;
466
    l2_table = l2_load(bs, l2_offset);
467
    if (l2_table == NULL)
468
        return 0;
469

    
470
    /* find the cluster offset for the given disk offset */
471

    
472
    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
473
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
474
    nb_clusters = size_to_clusters(s, nb_needed << 9);
475

    
476
    if (!cluster_offset) {
477
        /* how many empty clusters ? */
478
        c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
479
    } else {
480
        /* how many allocated clusters ? */
481
        c = count_contiguous_clusters(nb_clusters, s->cluster_size,
482
                &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);
483
    }
484

    
485
   nb_available = (c * s->cluster_sectors);
486
out:
487
    if (nb_available > nb_needed)
488
        nb_available = nb_needed;
489

    
490
    *num = nb_available - index_in_cluster;
491

    
492
    return cluster_offset & ~QCOW_OFLAG_COPIED;
493
}
494

    
495
/*
496
 * get_cluster_table
497
 *
498
 * for a given disk offset, load (and allocate if needed)
499
 * the l2 table.
500
 *
501
 * the l2 table offset in the qcow2 file and the cluster index
502
 * in the l2 table are given to the caller.
503
 *
504
 * Returns 0 on success, -errno in failure case
505
 */
506
static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
507
                             uint64_t **new_l2_table,
508
                             uint64_t *new_l2_offset,
509
                             int *new_l2_index)
510
{
511
    BDRVQcowState *s = bs->opaque;
512
    unsigned int l1_index, l2_index;
513
    uint64_t l2_offset, *l2_table;
514
    int ret;
515

    
516
    /* seek the the l2 offset in the l1 table */
517

    
518
    l1_index = offset >> (s->l2_bits + s->cluster_bits);
519
    if (l1_index >= s->l1_size) {
520
        ret = qcow2_grow_l1_table(bs, l1_index + 1);
521
        if (ret < 0) {
522
            return ret;
523
        }
524
    }
525
    l2_offset = s->l1_table[l1_index];
526

    
527
    /* seek the l2 table of the given l2 offset */
528

    
529
    if (l2_offset & QCOW_OFLAG_COPIED) {
530
        /* load the l2 table in memory */
531
        l2_offset &= ~QCOW_OFLAG_COPIED;
532
        l2_table = l2_load(bs, l2_offset);
533
        if (l2_table == NULL) {
534
            return -EIO;
535
        }
536
    } else {
537
        if (l2_offset)
538
            qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
539
        l2_table = l2_allocate(bs, l1_index);
540
        if (l2_table == NULL) {
541
            return -EIO;
542
        }
543
        l2_offset = s->l1_table[l1_index] & ~QCOW_OFLAG_COPIED;
544
    }
545

    
546
    /* find the cluster offset for the given disk offset */
547

    
548
    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
549

    
550
    *new_l2_table = l2_table;
551
    *new_l2_offset = l2_offset;
552
    *new_l2_index = l2_index;
553

    
554
    return 0;
555
}
556

    
557
/*
558
 * alloc_compressed_cluster_offset
559
 *
560
 * For a given offset of the disk image, return cluster offset in
561
 * qcow2 file.
562
 *
563
 * If the offset is not found, allocate a new compressed cluster.
564
 *
565
 * Return the cluster offset if successful,
566
 * Return 0, otherwise.
567
 *
568
 */
569

    
570
uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
571
                                               uint64_t offset,
572
                                               int compressed_size)
573
{
574
    BDRVQcowState *s = bs->opaque;
575
    int l2_index, ret;
576
    uint64_t l2_offset, *l2_table;
577
    int64_t cluster_offset;
578
    int nb_csectors;
579

    
580
    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
581
    if (ret < 0) {
582
        return 0;
583
    }
584

    
585
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
586
    if (cluster_offset & QCOW_OFLAG_COPIED)
587
        return cluster_offset & ~QCOW_OFLAG_COPIED;
588

    
589
    if (cluster_offset)
590
        qcow2_free_any_clusters(bs, cluster_offset, 1);
591

    
592
    cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
593
    if (cluster_offset < 0) {
594
        return 0;
595
    }
596

    
597
    nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
598
                  (cluster_offset >> 9);
599

    
600
    cluster_offset |= QCOW_OFLAG_COMPRESSED |
601
                      ((uint64_t)nb_csectors << s->csize_shift);
602

    
603
    /* update L2 table */
604

    
605
    /* compressed clusters never have the copied flag */
606

    
607
    BLKDBG_EVENT(s->hd, BLKDBG_L2_UPDATE_COMPRESSED);
608
    l2_table[l2_index] = cpu_to_be64(cluster_offset);
609
    if (bdrv_pwrite(s->hd,
610
                    l2_offset + l2_index * sizeof(uint64_t),
611
                    l2_table + l2_index,
612
                    sizeof(uint64_t)) != sizeof(uint64_t))
613
        return 0;
614

    
615
    return cluster_offset;
616
}
617

    
618
/*
619
 * Write L2 table updates to disk, writing whole sectors to avoid a
620
 * read-modify-write in bdrv_pwrite
621
 */
622
#define L2_ENTRIES_PER_SECTOR (512 / 8)
623
static int write_l2_entries(BDRVQcowState *s, uint64_t *l2_table,
624
    uint64_t l2_offset, int l2_index, int num)
625
{
626
    int l2_start_index = l2_index & ~(L1_ENTRIES_PER_SECTOR - 1);
627
    int start_offset = (8 * l2_index) & ~511;
628
    int end_offset = (8 * (l2_index + num) + 511) & ~511;
629
    size_t len = end_offset - start_offset;
630

    
631
    BLKDBG_EVENT(s->hd, BLKDBG_L2_UPDATE);
632
    if (bdrv_pwrite(s->hd, l2_offset + start_offset, &l2_table[l2_start_index],
633
        len) != len)
634
    {
635
        return -1;
636
    }
637

    
638
    return 0;
639
}
640

    
641
int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
642
{
643
    BDRVQcowState *s = bs->opaque;
644
    int i, j = 0, l2_index, ret;
645
    uint64_t *old_cluster, start_sect, l2_offset, *l2_table;
646
    uint64_t cluster_offset = m->cluster_offset;
647

    
648
    if (m->nb_clusters == 0)
649
        return 0;
650

    
651
    old_cluster = qemu_malloc(m->nb_clusters * sizeof(uint64_t));
652

    
653
    /* copy content of unmodified sectors */
654
    start_sect = (m->offset & ~(s->cluster_size - 1)) >> 9;
655
    if (m->n_start) {
656
        ret = copy_sectors(bs, start_sect, cluster_offset, 0, m->n_start);
657
        if (ret < 0)
658
            goto err;
659
    }
660

    
661
    if (m->nb_available & (s->cluster_sectors - 1)) {
662
        uint64_t end = m->nb_available & ~(uint64_t)(s->cluster_sectors - 1);
663
        ret = copy_sectors(bs, start_sect + end, cluster_offset + (end << 9),
664
                m->nb_available - end, s->cluster_sectors);
665
        if (ret < 0)
666
            goto err;
667
    }
668

    
669
    /* update L2 table */
670
    ret = get_cluster_table(bs, m->offset, &l2_table, &l2_offset, &l2_index);
671
    if (ret < 0) {
672
        goto err;
673
    }
674

    
675
    for (i = 0; i < m->nb_clusters; i++) {
676
        /* if two concurrent writes happen to the same unallocated cluster
677
         * each write allocates separate cluster and writes data concurrently.
678
         * The first one to complete updates l2 table with pointer to its
679
         * cluster the second one has to do RMW (which is done above by
680
         * copy_sectors()), update l2 table with its cluster pointer and free
681
         * old cluster. This is what this loop does */
682
        if(l2_table[l2_index + i] != 0)
683
            old_cluster[j++] = l2_table[l2_index + i];
684

    
685
        l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
686
                    (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
687
     }
688

    
689
    if (write_l2_entries(s, l2_table, l2_offset, l2_index, m->nb_clusters) < 0) {
690
        ret = -1;
691
        goto err;
692
    }
693

    
694
    for (i = 0; i < j; i++)
695
        qcow2_free_any_clusters(bs,
696
            be64_to_cpu(old_cluster[i]) & ~QCOW_OFLAG_COPIED, 1);
697

    
698
    ret = 0;
699
err:
700
    qemu_free(old_cluster);
701
    return ret;
702
 }
703

    
704
/*
705
 * alloc_cluster_offset
706
 *
707
 * For a given offset of the disk image, return cluster offset in qcow2 file.
708
 * If the offset is not found, allocate a new cluster.
709
 *
710
 * If the cluster was already allocated, m->nb_clusters is set to 0,
711
 * m->depends_on is set to NULL and the other fields in m are meaningless.
712
 *
713
 * If the cluster is newly allocated, m->nb_clusters is set to the number of
714
 * contiguous clusters that have been allocated. This may be 0 if the request
715
 * conflict with another write request in flight; in this case, m->depends_on
716
 * is set and the remaining fields of m are meaningless.
717
 *
718
 * If m->nb_clusters is non-zero, the other fields of m are valid and contain
719
 * information about the first allocated cluster.
720
 *
721
 * Return 0 on success and -errno in error cases
722
 */
723
int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
724
    int n_start, int n_end, int *num, QCowL2Meta *m)
725
{
726
    BDRVQcowState *s = bs->opaque;
727
    int l2_index, ret;
728
    uint64_t l2_offset, *l2_table;
729
    int64_t cluster_offset;
730
    unsigned int nb_clusters, i = 0;
731
    QCowL2Meta *old_alloc;
732

    
733
    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
734
    if (ret < 0) {
735
        return ret;
736
    }
737

    
738
    nb_clusters = size_to_clusters(s, n_end << 9);
739

    
740
    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
741

    
742
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
743

    
744
    /* We keep all QCOW_OFLAG_COPIED clusters */
745

    
746
    if (cluster_offset & QCOW_OFLAG_COPIED) {
747
        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
748
                &l2_table[l2_index], 0, 0);
749

    
750
        cluster_offset &= ~QCOW_OFLAG_COPIED;
751
        m->nb_clusters = 0;
752
        m->depends_on = NULL;
753

    
754
        goto out;
755
    }
756

    
757
    /* for the moment, multiple compressed clusters are not managed */
758

    
759
    if (cluster_offset & QCOW_OFLAG_COMPRESSED)
760
        nb_clusters = 1;
761

    
762
    /* how many available clusters ? */
763

    
764
    while (i < nb_clusters) {
765
        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
766
                &l2_table[l2_index], i, 0);
767
        if ((i >= nb_clusters) || be64_to_cpu(l2_table[l2_index + i])) {
768
            break;
769
        }
770

    
771
        i += count_contiguous_free_clusters(nb_clusters - i,
772
                &l2_table[l2_index + i]);
773
        if (i >= nb_clusters) {
774
            break;
775
        }
776

    
777
        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
778

    
779
        if ((cluster_offset & QCOW_OFLAG_COPIED) ||
780
                (cluster_offset & QCOW_OFLAG_COMPRESSED))
781
            break;
782
    }
783
    assert(i <= nb_clusters);
784
    nb_clusters = i;
785

    
786
    /*
787
     * Check if there already is an AIO write request in flight which allocates
788
     * the same cluster. In this case we need to wait until the previous
789
     * request has completed and updated the L2 table accordingly.
790
     */
791
    QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
792

    
793
        uint64_t end_offset = offset + nb_clusters * s->cluster_size;
794
        uint64_t old_offset = old_alloc->offset;
795
        uint64_t old_end_offset = old_alloc->offset +
796
            old_alloc->nb_clusters * s->cluster_size;
797

    
798
        if (end_offset < old_offset || offset > old_end_offset) {
799
            /* No intersection */
800
        } else {
801
            if (offset < old_offset) {
802
                /* Stop at the start of a running allocation */
803
                nb_clusters = (old_offset - offset) >> s->cluster_bits;
804
            } else {
805
                nb_clusters = 0;
806
            }
807

    
808
            if (nb_clusters == 0) {
809
                /* Set dependency and wait for a callback */
810
                m->depends_on = old_alloc;
811
                m->nb_clusters = 0;
812
                *num = 0;
813
                return 0;
814
            }
815
        }
816
    }
817

    
818
    if (!nb_clusters) {
819
        abort();
820
    }
821

    
822
    QLIST_INSERT_HEAD(&s->cluster_allocs, m, next_in_flight);
823

    
824
    /* allocate a new cluster */
825

    
826
    cluster_offset = qcow2_alloc_clusters(bs, nb_clusters * s->cluster_size);
827
    if (cluster_offset < 0) {
828
        QLIST_REMOVE(m, next_in_flight);
829
        return cluster_offset;
830
    }
831

    
832
    /* save info needed for meta data update */
833
    m->offset = offset;
834
    m->n_start = n_start;
835
    m->nb_clusters = nb_clusters;
836

    
837
out:
838
    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
839
    m->cluster_offset = cluster_offset;
840

    
841
    *num = m->nb_available - n_start;
842

    
843
    return 0;
844
}
845

    
846
static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
847
                             const uint8_t *buf, int buf_size)
848
{
849
    z_stream strm1, *strm = &strm1;
850
    int ret, out_len;
851

    
852
    memset(strm, 0, sizeof(*strm));
853

    
854
    strm->next_in = (uint8_t *)buf;
855
    strm->avail_in = buf_size;
856
    strm->next_out = out_buf;
857
    strm->avail_out = out_buf_size;
858

    
859
    ret = inflateInit2(strm, -12);
860
    if (ret != Z_OK)
861
        return -1;
862
    ret = inflate(strm, Z_FINISH);
863
    out_len = strm->next_out - out_buf;
864
    if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
865
        out_len != out_buf_size) {
866
        inflateEnd(strm);
867
        return -1;
868
    }
869
    inflateEnd(strm);
870
    return 0;
871
}
872

    
873
int qcow2_decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
874
{
875
    int ret, csize, nb_csectors, sector_offset;
876
    uint64_t coffset;
877

    
878
    coffset = cluster_offset & s->cluster_offset_mask;
879
    if (s->cluster_cache_offset != coffset) {
880
        nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
881
        sector_offset = coffset & 511;
882
        csize = nb_csectors * 512 - sector_offset;
883
        BLKDBG_EVENT(s->hd, BLKDBG_READ_COMPRESSED);
884
        ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
885
        if (ret < 0) {
886
            return -1;
887
        }
888
        if (decompress_buffer(s->cluster_cache, s->cluster_size,
889
                              s->cluster_data + sector_offset, csize) < 0) {
890
            return -1;
891
        }
892
        s->cluster_cache_offset = coffset;
893
    }
894
    return 0;
895
}