Statistics
| Branch: | Revision:

root / block / qcow2-cluster.c @ 1b7c801b

History | View | Annotate | Download (26.5 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(bs->file, 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(bs->file, 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(bs->file, 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(bs->file, 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(bs->file, 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(bs->file, BLKDBG_L2_LOAD);
178
    if (bdrv_pread(bs->file, 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(BlockDriverState *bs, int l1_index)
193
{
194
    BDRVQcowState *s = bs->opaque;
195
    uint64_t buf[L1_ENTRIES_PER_SECTOR];
196
    int l1_start_index;
197
    int i, ret;
198

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

    
204
    BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
205
    ret = bdrv_pwrite(bs->file, s->l1_table_offset + 8 * l1_start_index,
206
        buf, sizeof(buf));
207
    if (ret < 0) {
208
        return ret;
209
    }
210

    
211
    return 0;
212
}
213

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

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

    
233
    old_l2_offset = s->l1_table[l1_index];
234

    
235
    /* allocate a new l2 entry */
236

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

    
242
    /* update the L1 entry */
243

    
244
    s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
245
    ret = write_l1_entry(bs, l1_index);
246
    if (ret < 0) {
247
        return ret;
248
    }
249

    
250
    /* allocate a new entry in the l2 cache */
251

    
252
    min_index = l2_cache_new_entry(bs);
253
    l2_table = s->l2_cache + (min_index << s->l2_bits);
254

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

    
275
    /* update the l2 cache entry */
276

    
277
    s->l2_cache_offsets[min_index] = l2_offset;
278
    s->l2_cache_counts[min_index] = 1;
279

    
280
    *table = l2_table;
281
    return 0;
282
}
283

    
284
static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
285
        uint64_t *l2_table, uint64_t start, uint64_t mask)
286
{
287
    int i;
288
    uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask;
289

    
290
    if (!offset)
291
        return 0;
292

    
293
    for (i = start; i < start + nb_clusters; i++)
294
        if (offset + (uint64_t) i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask))
295
            break;
296

    
297
        return (i - start);
298
}
299

    
300
static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
301
{
302
    int i = 0;
303

    
304
    while(nb_clusters-- && l2_table[i] == 0)
305
        i++;
306

    
307
    return i;
308
}
309

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

    
324
    for(i = 0; i < nb_sectors; i++) {
325
        ivec.ll[0] = cpu_to_le64(sector_num);
326
        ivec.ll[1] = 0;
327
        AES_cbc_encrypt(in_buf, out_buf, 512, key,
328
                        ivec.b, enc);
329
        sector_num++;
330
        in_buf += 512;
331
        out_buf += 512;
332
    }
333
}
334

    
335

    
336
static int qcow_read(BlockDriverState *bs, int64_t sector_num,
337
                     uint8_t *buf, int nb_sectors)
338
{
339
    BDRVQcowState *s = bs->opaque;
340
    int ret, index_in_cluster, n, n1;
341
    uint64_t cluster_offset;
342

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

    
381
static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,
382
                        uint64_t cluster_offset, int n_start, int n_end)
383
{
384
    BDRVQcowState *s = bs->opaque;
385
    int n, ret;
386

    
387
    n = n_end - n_start;
388
    if (n <= 0)
389
        return 0;
390
    BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
391
    ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);
392
    if (ret < 0)
393
        return ret;
394
    if (s->crypt_method) {
395
        qcow2_encrypt_sectors(s, start_sect + n_start,
396
                        s->cluster_data,
397
                        s->cluster_data, n, 1,
398
                        &s->aes_encrypt_key);
399
    }
400
    BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
401
    ret = bdrv_write(bs->file, (cluster_offset >> 9) + n_start,
402
                     s->cluster_data, n);
403
    if (ret < 0)
404
        return ret;
405
    return 0;
406
}
407

    
408

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

    
425
uint64_t qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
426
    int *num)
427
{
428
    BDRVQcowState *s = bs->opaque;
429
    unsigned int l1_index, l2_index;
430
    uint64_t l2_offset, *l2_table, cluster_offset;
431
    int l1_bits, c;
432
    unsigned int index_in_cluster, nb_clusters;
433
    uint64_t nb_available, nb_needed;
434

    
435
    index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
436
    nb_needed = *num + index_in_cluster;
437

    
438
    l1_bits = s->l2_bits + s->cluster_bits;
439

    
440
    /* compute how many bytes there are between the offset and
441
     * the end of the l1 entry
442
     */
443

    
444
    nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));
445

    
446
    /* compute the number of available sectors */
447

    
448
    nb_available = (nb_available >> 9) + index_in_cluster;
449

    
450
    if (nb_needed > nb_available) {
451
        nb_needed = nb_available;
452
    }
453

    
454
    cluster_offset = 0;
455

    
456
    /* seek the the l2 offset in the l1 table */
457

    
458
    l1_index = offset >> l1_bits;
459
    if (l1_index >= s->l1_size)
460
        goto out;
461

    
462
    l2_offset = s->l1_table[l1_index];
463

    
464
    /* seek the l2 table of the given l2 offset */
465

    
466
    if (!l2_offset)
467
        goto out;
468

    
469
    /* load the l2 table in memory */
470

    
471
    l2_offset &= ~QCOW_OFLAG_COPIED;
472
    l2_table = l2_load(bs, l2_offset);
473
    if (l2_table == NULL)
474
        return 0;
475

    
476
    /* find the cluster offset for the given disk offset */
477

    
478
    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
479
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
480
    nb_clusters = size_to_clusters(s, nb_needed << 9);
481

    
482
    if (!cluster_offset) {
483
        /* how many empty clusters ? */
484
        c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
485
    } else {
486
        /* how many allocated clusters ? */
487
        c = count_contiguous_clusters(nb_clusters, s->cluster_size,
488
                &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);
489
    }
490

    
491
   nb_available = (c * s->cluster_sectors);
492
out:
493
    if (nb_available > nb_needed)
494
        nb_available = nb_needed;
495

    
496
    *num = nb_available - index_in_cluster;
497

    
498
    return cluster_offset & ~QCOW_OFLAG_COPIED;
499
}
500

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

    
523
    /* seek the the l2 offset in the l1 table */
524

    
525
    l1_index = offset >> (s->l2_bits + s->cluster_bits);
526
    if (l1_index >= s->l1_size) {
527
        ret = qcow2_grow_l1_table(bs, l1_index + 1);
528
        if (ret < 0) {
529
            return ret;
530
        }
531
    }
532
    l2_offset = s->l1_table[l1_index];
533

    
534
    /* seek the l2 table of the given l2 offset */
535

    
536
    if (l2_offset & QCOW_OFLAG_COPIED) {
537
        /* load the l2 table in memory */
538
        l2_offset &= ~QCOW_OFLAG_COPIED;
539
        l2_table = l2_load(bs, l2_offset);
540
        if (l2_table == NULL) {
541
            return -EIO;
542
        }
543
    } else {
544
        if (l2_offset)
545
            qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
546
        ret = l2_allocate(bs, l1_index, &l2_table);
547
        if (ret < 0) {
548
            return ret;
549
        }
550
        l2_offset = s->l1_table[l1_index] & ~QCOW_OFLAG_COPIED;
551
    }
552

    
553
    /* find the cluster offset for the given disk offset */
554

    
555
    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
556

    
557
    *new_l2_table = l2_table;
558
    *new_l2_offset = l2_offset;
559
    *new_l2_index = l2_index;
560

    
561
    return 0;
562
}
563

    
564
/*
565
 * alloc_compressed_cluster_offset
566
 *
567
 * For a given offset of the disk image, return cluster offset in
568
 * qcow2 file.
569
 *
570
 * If the offset is not found, allocate a new compressed cluster.
571
 *
572
 * Return the cluster offset if successful,
573
 * Return 0, otherwise.
574
 *
575
 */
576

    
577
uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
578
                                               uint64_t offset,
579
                                               int compressed_size)
580
{
581
    BDRVQcowState *s = bs->opaque;
582
    int l2_index, ret;
583
    uint64_t l2_offset, *l2_table;
584
    int64_t cluster_offset;
585
    int nb_csectors;
586

    
587
    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
588
    if (ret < 0) {
589
        return 0;
590
    }
591

    
592
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
593
    if (cluster_offset & QCOW_OFLAG_COPIED)
594
        return cluster_offset & ~QCOW_OFLAG_COPIED;
595

    
596
    if (cluster_offset)
597
        qcow2_free_any_clusters(bs, cluster_offset, 1);
598

    
599
    cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
600
    if (cluster_offset < 0) {
601
        return 0;
602
    }
603

    
604
    nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
605
                  (cluster_offset >> 9);
606

    
607
    cluster_offset |= QCOW_OFLAG_COMPRESSED |
608
                      ((uint64_t)nb_csectors << s->csize_shift);
609

    
610
    /* update L2 table */
611

    
612
    /* compressed clusters never have the copied flag */
613

    
614
    BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
615
    l2_table[l2_index] = cpu_to_be64(cluster_offset);
616
    if (bdrv_pwrite(bs->file,
617
                    l2_offset + l2_index * sizeof(uint64_t),
618
                    l2_table + l2_index,
619
                    sizeof(uint64_t)) != sizeof(uint64_t))
620
        return 0;
621

    
622
    return cluster_offset;
623
}
624

    
625
/*
626
 * Write L2 table updates to disk, writing whole sectors to avoid a
627
 * read-modify-write in bdrv_pwrite
628
 */
629
#define L2_ENTRIES_PER_SECTOR (512 / 8)
630
static int write_l2_entries(BlockDriverState *bs, uint64_t *l2_table,
631
    uint64_t l2_offset, int l2_index, int num)
632
{
633
    int l2_start_index = l2_index & ~(L1_ENTRIES_PER_SECTOR - 1);
634
    int start_offset = (8 * l2_index) & ~511;
635
    int end_offset = (8 * (l2_index + num) + 511) & ~511;
636
    size_t len = end_offset - start_offset;
637
    int ret;
638

    
639
    BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE);
640
    ret = bdrv_pwrite(bs->file, l2_offset + start_offset,
641
        &l2_table[l2_start_index], len);
642
    if (ret < 0) {
643
        return ret;
644
    }
645

    
646
    return 0;
647
}
648

    
649
int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
650
{
651
    BDRVQcowState *s = bs->opaque;
652
    int i, j = 0, l2_index, ret;
653
    uint64_t *old_cluster, start_sect, l2_offset, *l2_table;
654
    uint64_t cluster_offset = m->cluster_offset;
655

    
656
    if (m->nb_clusters == 0)
657
        return 0;
658

    
659
    old_cluster = qemu_malloc(m->nb_clusters * sizeof(uint64_t));
660

    
661
    /* copy content of unmodified sectors */
662
    start_sect = (m->offset & ~(s->cluster_size - 1)) >> 9;
663
    if (m->n_start) {
664
        ret = copy_sectors(bs, start_sect, cluster_offset, 0, m->n_start);
665
        if (ret < 0)
666
            goto err;
667
    }
668

    
669
    if (m->nb_available & (s->cluster_sectors - 1)) {
670
        uint64_t end = m->nb_available & ~(uint64_t)(s->cluster_sectors - 1);
671
        ret = copy_sectors(bs, start_sect + end, cluster_offset + (end << 9),
672
                m->nb_available - end, s->cluster_sectors);
673
        if (ret < 0)
674
            goto err;
675
    }
676

    
677
    /* update L2 table */
678
    ret = get_cluster_table(bs, m->offset, &l2_table, &l2_offset, &l2_index);
679
    if (ret < 0) {
680
        goto err;
681
    }
682

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

    
693
        l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
694
                    (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
695
     }
696

    
697
    ret = write_l2_entries(bs, l2_table, l2_offset, l2_index, m->nb_clusters);
698
    if (ret < 0) {
699
        qcow2_l2_cache_reset(bs);
700
        goto err;
701
    }
702

    
703
    for (i = 0; i < j; i++)
704
        qcow2_free_any_clusters(bs,
705
            be64_to_cpu(old_cluster[i]) & ~QCOW_OFLAG_COPIED, 1);
706

    
707
    ret = 0;
708
err:
709
    qemu_free(old_cluster);
710
    return ret;
711
 }
712

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

    
742
    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
743
    if (ret < 0) {
744
        return ret;
745
    }
746

    
747
    nb_clusters = size_to_clusters(s, n_end << 9);
748

    
749
    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
750

    
751
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
752

    
753
    /* We keep all QCOW_OFLAG_COPIED clusters */
754

    
755
    if (cluster_offset & QCOW_OFLAG_COPIED) {
756
        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
757
                &l2_table[l2_index], 0, 0);
758

    
759
        cluster_offset &= ~QCOW_OFLAG_COPIED;
760
        m->nb_clusters = 0;
761
        m->depends_on = NULL;
762

    
763
        goto out;
764
    }
765

    
766
    /* for the moment, multiple compressed clusters are not managed */
767

    
768
    if (cluster_offset & QCOW_OFLAG_COMPRESSED)
769
        nb_clusters = 1;
770

    
771
    /* how many available clusters ? */
772

    
773
    while (i < nb_clusters) {
774
        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
775
                &l2_table[l2_index], i, 0);
776
        if ((i >= nb_clusters) || be64_to_cpu(l2_table[l2_index + i])) {
777
            break;
778
        }
779

    
780
        i += count_contiguous_free_clusters(nb_clusters - i,
781
                &l2_table[l2_index + i]);
782
        if (i >= nb_clusters) {
783
            break;
784
        }
785

    
786
        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
787

    
788
        if ((cluster_offset & QCOW_OFLAG_COPIED) ||
789
                (cluster_offset & QCOW_OFLAG_COMPRESSED))
790
            break;
791
    }
792
    assert(i <= nb_clusters);
793
    nb_clusters = i;
794

    
795
    /*
796
     * Check if there already is an AIO write request in flight which allocates
797
     * the same cluster. In this case we need to wait until the previous
798
     * request has completed and updated the L2 table accordingly.
799
     */
800
    QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
801

    
802
        uint64_t end_offset = offset + nb_clusters * s->cluster_size;
803
        uint64_t old_offset = old_alloc->offset;
804
        uint64_t old_end_offset = old_alloc->offset +
805
            old_alloc->nb_clusters * s->cluster_size;
806

    
807
        if (end_offset < old_offset || offset > old_end_offset) {
808
            /* No intersection */
809
        } else {
810
            if (offset < old_offset) {
811
                /* Stop at the start of a running allocation */
812
                nb_clusters = (old_offset - offset) >> s->cluster_bits;
813
            } else {
814
                nb_clusters = 0;
815
            }
816

    
817
            if (nb_clusters == 0) {
818
                /* Set dependency and wait for a callback */
819
                m->depends_on = old_alloc;
820
                m->nb_clusters = 0;
821
                *num = 0;
822
                return 0;
823
            }
824
        }
825
    }
826

    
827
    if (!nb_clusters) {
828
        abort();
829
    }
830

    
831
    QLIST_INSERT_HEAD(&s->cluster_allocs, m, next_in_flight);
832

    
833
    /* allocate a new cluster */
834

    
835
    cluster_offset = qcow2_alloc_clusters(bs, nb_clusters * s->cluster_size);
836
    if (cluster_offset < 0) {
837
        QLIST_REMOVE(m, next_in_flight);
838
        return cluster_offset;
839
    }
840

    
841
    /* save info needed for meta data update */
842
    m->offset = offset;
843
    m->n_start = n_start;
844
    m->nb_clusters = nb_clusters;
845

    
846
out:
847
    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
848
    m->cluster_offset = cluster_offset;
849

    
850
    *num = m->nb_available - n_start;
851

    
852
    return 0;
853
}
854

    
855
static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
856
                             const uint8_t *buf, int buf_size)
857
{
858
    z_stream strm1, *strm = &strm1;
859
    int ret, out_len;
860

    
861
    memset(strm, 0, sizeof(*strm));
862

    
863
    strm->next_in = (uint8_t *)buf;
864
    strm->avail_in = buf_size;
865
    strm->next_out = out_buf;
866
    strm->avail_out = out_buf_size;
867

    
868
    ret = inflateInit2(strm, -12);
869
    if (ret != Z_OK)
870
        return -1;
871
    ret = inflate(strm, Z_FINISH);
872
    out_len = strm->next_out - out_buf;
873
    if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
874
        out_len != out_buf_size) {
875
        inflateEnd(strm);
876
        return -1;
877
    }
878
    inflateEnd(strm);
879
    return 0;
880
}
881

    
882
int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
883
{
884
    BDRVQcowState *s = bs->opaque;
885
    int ret, csize, nb_csectors, sector_offset;
886
    uint64_t coffset;
887

    
888
    coffset = cluster_offset & s->cluster_offset_mask;
889
    if (s->cluster_cache_offset != coffset) {
890
        nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
891
        sector_offset = coffset & 511;
892
        csize = nb_csectors * 512 - sector_offset;
893
        BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
894
        ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data, nb_csectors);
895
        if (ret < 0) {
896
            return -1;
897
        }
898
        if (decompress_buffer(s->cluster_cache, s->cluster_size,
899
                              s->cluster_data + sector_offset, csize) < 0) {
900
            return -1;
901
        }
902
        s->cluster_cache_offset = coffset;
903
    }
904
    return 0;
905
}