Add qemu 2.4.0
[kvmfornfv.git] / qemu / block / vhdx-log.c
1 /*
2  * Block driver for Hyper-V VHDX Images
3  *
4  * Copyright (c) 2013 Red Hat, Inc.,
5  *
6  * Authors:
7  *  Jeff Cody <jcody@redhat.com>
8  *
9  *  This is based on the "VHDX Format Specification v1.00", published 8/25/2012
10  *  by Microsoft:
11  *      https://www.microsoft.com/en-us/download/details.aspx?id=34750
12  *
13  * This file covers the functionality of the metadata log writing, parsing, and
14  * replay.
15  *
16  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
17  * See the COPYING.LIB file in the top-level directory.
18  *
19  */
20 #include "qemu-common.h"
21 #include "block/block_int.h"
22 #include "qemu/error-report.h"
23 #include "qemu/module.h"
24 #include "block/vhdx.h"
25
26
27 typedef struct VHDXLogSequence {
28     bool valid;
29     uint32_t count;
30     VHDXLogEntries log;
31     VHDXLogEntryHeader hdr;
32 } VHDXLogSequence;
33
34 typedef struct VHDXLogDescEntries {
35     VHDXLogEntryHeader hdr;
36     VHDXLogDescriptor desc[];
37 } VHDXLogDescEntries;
38
39 static const MSGUID zero_guid = { 0 };
40
41 /* The log located on the disk is circular buffer containing
42  * sectors of 4096 bytes each.
43  *
44  * It is assumed for the read/write functions below that the
45  * circular buffer scheme uses a 'one sector open' to indicate
46  * the buffer is full.  Given the validation methods used for each
47  * sector, this method should be compatible with other methods that
48  * do not waste a sector.
49  */
50
51
52 /* Allow peeking at the hdr entry at the beginning of the current
53  * read index, without advancing the read index */
54 static int vhdx_log_peek_hdr(BlockDriverState *bs, VHDXLogEntries *log,
55                              VHDXLogEntryHeader *hdr)
56 {
57     int ret = 0;
58     uint64_t offset;
59     uint32_t read;
60
61     assert(hdr != NULL);
62
63     /* peek is only supported on sector boundaries */
64     if (log->read % VHDX_LOG_SECTOR_SIZE) {
65         ret = -EFAULT;
66         goto exit;
67     }
68
69     read = log->read;
70     /* we are guaranteed that a) log sectors are 4096 bytes,
71      * and b) the log length is a multiple of 1MB. So, there
72      * is always a round number of sectors in the buffer */
73     if ((read + sizeof(VHDXLogEntryHeader)) > log->length) {
74         read = 0;
75     }
76
77     if (read == log->write) {
78         ret = -EINVAL;
79         goto exit;
80     }
81
82     offset = log->offset + read;
83
84     ret = bdrv_pread(bs->file, offset, hdr, sizeof(VHDXLogEntryHeader));
85     if (ret < 0) {
86         goto exit;
87     }
88     vhdx_log_entry_hdr_le_import(hdr);
89
90 exit:
91     return ret;
92 }
93
94 /* Index increment for log, based on sector boundaries */
95 static int vhdx_log_inc_idx(uint32_t idx, uint64_t length)
96 {
97     idx += VHDX_LOG_SECTOR_SIZE;
98     /* we are guaranteed that a) log sectors are 4096 bytes,
99      * and b) the log length is a multiple of 1MB. So, there
100      * is always a round number of sectors in the buffer */
101     return idx >= length ? 0 : idx;
102 }
103
104
105 /* Reset the log to empty */
106 static void vhdx_log_reset(BlockDriverState *bs, BDRVVHDXState *s)
107 {
108     MSGUID guid = { 0 };
109     s->log.read = s->log.write = 0;
110     /* a log guid of 0 indicates an empty log to any parser of v0
111      * VHDX logs */
112     vhdx_update_headers(bs, s, false, &guid);
113 }
114
115 /* Reads num_sectors from the log (all log sectors are 4096 bytes),
116  * into buffer 'buffer'.  Upon return, *sectors_read will contain
117  * the number of sectors successfully read.
118  *
119  * It is assumed that 'buffer' is already allocated, and of sufficient
120  * size (i.e. >= 4096*num_sectors).
121  *
122  * If 'peek' is true, then the tail (read) pointer for the circular buffer is
123  * not modified.
124  *
125  * 0 is returned on success, -errno otherwise.  */
126 static int vhdx_log_read_sectors(BlockDriverState *bs, VHDXLogEntries *log,
127                                  uint32_t *sectors_read, void *buffer,
128                                  uint32_t num_sectors, bool peek)
129 {
130     int ret = 0;
131     uint64_t offset;
132     uint32_t read;
133
134     read = log->read;
135
136     *sectors_read = 0;
137     while (num_sectors) {
138         if (read == log->write) {
139             /* empty */
140             break;
141         }
142         offset = log->offset + read;
143
144         ret = bdrv_pread(bs->file, offset, buffer, VHDX_LOG_SECTOR_SIZE);
145         if (ret < 0) {
146             goto exit;
147         }
148         read = vhdx_log_inc_idx(read, log->length);
149
150         *sectors_read = *sectors_read + 1;
151         num_sectors--;
152     }
153
154 exit:
155     if (!peek) {
156         log->read = read;
157     }
158     return ret;
159 }
160
161 /* Writes num_sectors to the log (all log sectors are 4096 bytes),
162  * from buffer 'buffer'.  Upon return, *sectors_written will contain
163  * the number of sectors successfully written.
164  *
165  * It is assumed that 'buffer' is at least 4096*num_sectors large.
166  *
167  * 0 is returned on success, -errno otherwise */
168 static int vhdx_log_write_sectors(BlockDriverState *bs, VHDXLogEntries *log,
169                                   uint32_t *sectors_written, void *buffer,
170                                   uint32_t num_sectors)
171 {
172     int ret = 0;
173     uint64_t offset;
174     uint32_t write;
175     void *buffer_tmp;
176     BDRVVHDXState *s = bs->opaque;
177
178     ret = vhdx_user_visible_write(bs, s);
179     if (ret < 0) {
180         goto exit;
181     }
182
183     write = log->write;
184
185     buffer_tmp = buffer;
186     while (num_sectors) {
187
188         offset = log->offset + write;
189         write = vhdx_log_inc_idx(write, log->length);
190         if (write == log->read) {
191             /* full */
192             break;
193         }
194         ret = bdrv_pwrite(bs->file, offset, buffer_tmp, VHDX_LOG_SECTOR_SIZE);
195         if (ret < 0) {
196             goto exit;
197         }
198         buffer_tmp += VHDX_LOG_SECTOR_SIZE;
199
200         log->write = write;
201         *sectors_written = *sectors_written + 1;
202         num_sectors--;
203     }
204
205 exit:
206     return ret;
207 }
208
209
210 /* Validates a log entry header */
211 static bool vhdx_log_hdr_is_valid(VHDXLogEntries *log, VHDXLogEntryHeader *hdr,
212                                   BDRVVHDXState *s)
213 {
214     int valid = false;
215
216     if (hdr->signature != VHDX_LOG_SIGNATURE) {
217         goto exit;
218     }
219
220     /* if the individual entry length is larger than the whole log
221      * buffer, that is obviously invalid */
222     if (log->length < hdr->entry_length) {
223         goto exit;
224     }
225
226     /* length of entire entry must be in units of 4KB (log sector size) */
227     if (hdr->entry_length % (VHDX_LOG_SECTOR_SIZE)) {
228         goto exit;
229     }
230
231     /* per spec, sequence # must be > 0 */
232     if (hdr->sequence_number == 0) {
233         goto exit;
234     }
235
236     /* log entries are only valid if they match the file-wide log guid
237      * found in the active header */
238     if (!guid_eq(hdr->log_guid, s->headers[s->curr_header]->log_guid)) {
239         goto exit;
240     }
241
242     if (hdr->descriptor_count * sizeof(VHDXLogDescriptor) > hdr->entry_length) {
243         goto exit;
244     }
245
246     valid = true;
247
248 exit:
249     return valid;
250 }
251
252 /*
253  * Given a log header, this will validate that the descriptors and the
254  * corresponding data sectors (if applicable)
255  *
256  * Validation consists of:
257  *      1. Making sure the sequence numbers matches the entry header
258  *      2. Verifying a valid signature ('zero' or 'desc' for descriptors)
259  *      3. File offset field is a multiple of 4KB
260  *      4. If a data descriptor, the corresponding data sector
261  *         has its signature ('data') and matching sequence number
262  *
263  * @desc: the data buffer containing the descriptor
264  * @hdr:  the log entry header
265  *
266  * Returns true if valid
267  */
268 static bool vhdx_log_desc_is_valid(VHDXLogDescriptor *desc,
269                                    VHDXLogEntryHeader *hdr)
270 {
271     bool ret = false;
272
273     if (desc->sequence_number != hdr->sequence_number) {
274         goto exit;
275     }
276     if (desc->file_offset % VHDX_LOG_SECTOR_SIZE) {
277         goto exit;
278     }
279
280     if (desc->signature == VHDX_LOG_ZERO_SIGNATURE) {
281         if (desc->zero_length % VHDX_LOG_SECTOR_SIZE == 0) {
282             /* valid */
283             ret = true;
284         }
285     } else if (desc->signature == VHDX_LOG_DESC_SIGNATURE) {
286             /* valid */
287             ret = true;
288     }
289
290 exit:
291     return ret;
292 }
293
294
295 /* Prior to sector data for a log entry, there is the header
296  * and the descriptors referenced in the header:
297  *
298  * [] = 4KB sector
299  *
300  * [ hdr, desc ][   desc   ][ ... ][ data ][ ... ]
301  *
302  * The first sector in a log entry has a 64 byte header, and
303  * up to 126 32-byte descriptors.  If more descriptors than
304  * 126 are required, then subsequent sectors can have up to 128
305  * descriptors.  Each sector is 4KB.  Data follows the descriptor
306  * sectors.
307  *
308  * This will return the number of sectors needed to encompass
309  * the passed number of descriptors in desc_cnt.
310  *
311  * This will never return 0, even if desc_cnt is 0.
312  */
313 static int vhdx_compute_desc_sectors(uint32_t desc_cnt)
314 {
315     uint32_t desc_sectors;
316
317     desc_cnt += 2; /* account for header in first sector */
318     desc_sectors = desc_cnt / 128;
319     if (desc_cnt % 128) {
320         desc_sectors++;
321     }
322
323     return desc_sectors;
324 }
325
326
327 /* Reads the log header, and subsequent descriptors (if any).  This
328  * will allocate all the space for buffer, which must be NULL when
329  * passed into this function. Each descriptor will also be validated,
330  * and error returned if any are invalid. */
331 static int vhdx_log_read_desc(BlockDriverState *bs, BDRVVHDXState *s,
332                               VHDXLogEntries *log, VHDXLogDescEntries **buffer,
333                               bool convert_endian)
334 {
335     int ret = 0;
336     uint32_t desc_sectors;
337     uint32_t sectors_read;
338     VHDXLogEntryHeader hdr;
339     VHDXLogDescEntries *desc_entries = NULL;
340     VHDXLogDescriptor desc;
341     int i;
342
343     assert(*buffer == NULL);
344
345     ret = vhdx_log_peek_hdr(bs, log, &hdr);
346     if (ret < 0) {
347         goto exit;
348     }
349
350     if (vhdx_log_hdr_is_valid(log, &hdr, s) == false) {
351         ret = -EINVAL;
352         goto exit;
353     }
354
355     desc_sectors = vhdx_compute_desc_sectors(hdr.descriptor_count);
356     desc_entries = qemu_try_blockalign(bs->file,
357                                        desc_sectors * VHDX_LOG_SECTOR_SIZE);
358     if (desc_entries == NULL) {
359         ret = -ENOMEM;
360         goto exit;
361     }
362
363     ret = vhdx_log_read_sectors(bs, log, &sectors_read, desc_entries,
364                                 desc_sectors, false);
365     if (ret < 0) {
366         goto free_and_exit;
367     }
368     if (sectors_read != desc_sectors) {
369         ret = -EINVAL;
370         goto free_and_exit;
371     }
372
373     /* put in proper endianness, and validate each desc */
374     for (i = 0; i < hdr.descriptor_count; i++) {
375         desc = desc_entries->desc[i];
376         vhdx_log_desc_le_import(&desc);
377         if (convert_endian) {
378             desc_entries->desc[i] = desc;
379         }
380         if (vhdx_log_desc_is_valid(&desc, &hdr) == false) {
381             ret = -EINVAL;
382             goto free_and_exit;
383         }
384     }
385     if (convert_endian) {
386         desc_entries->hdr = hdr;
387     }
388
389     *buffer = desc_entries;
390     goto exit;
391
392 free_and_exit:
393     qemu_vfree(desc_entries);
394 exit:
395     return ret;
396 }
397
398
399 /* Flushes the descriptor described by desc to the VHDX image file.
400  * If the descriptor is a data descriptor, than 'data' must be non-NULL,
401  * and >= 4096 bytes (VHDX_LOG_SECTOR_SIZE), containing the data to be
402  * written.
403  *
404  * Verification is performed to make sure the sequence numbers of a data
405  * descriptor match the sequence number in the desc.
406  *
407  * For a zero descriptor, it may describe multiple sectors to fill with zeroes.
408  * In this case, it should be noted that zeroes are written to disk, and the
409  * image file is not extended as a sparse file.  */
410 static int vhdx_log_flush_desc(BlockDriverState *bs, VHDXLogDescriptor *desc,
411                                VHDXLogDataSector *data)
412 {
413     int ret = 0;
414     uint64_t seq, file_offset;
415     uint32_t offset = 0;
416     void *buffer = NULL;
417     uint64_t count = 1;
418     int i;
419
420     buffer = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);
421
422     if (desc->signature == VHDX_LOG_DESC_SIGNATURE) {
423         /* data sector */
424         if (data == NULL) {
425             ret = -EFAULT;
426             goto exit;
427         }
428
429         /* The sequence number of the data sector must match that
430          * in the descriptor */
431         seq = data->sequence_high;
432         seq <<= 32;
433         seq |= data->sequence_low & 0xffffffff;
434
435         if (seq != desc->sequence_number) {
436             ret = -EINVAL;
437             goto exit;
438         }
439
440         /* Each data sector is in total 4096 bytes, however the first
441          * 8 bytes, and last 4 bytes, are located in the descriptor */
442         memcpy(buffer, &desc->leading_bytes, 8);
443         offset += 8;
444
445         memcpy(buffer+offset, data->data, 4084);
446         offset += 4084;
447
448         memcpy(buffer+offset, &desc->trailing_bytes, 4);
449
450     } else if (desc->signature == VHDX_LOG_ZERO_SIGNATURE) {
451         /* write 'count' sectors of sector */
452         memset(buffer, 0, VHDX_LOG_SECTOR_SIZE);
453         count = desc->zero_length / VHDX_LOG_SECTOR_SIZE;
454     } else {
455         error_report("Invalid VHDX log descriptor entry signature 0x%" PRIx32,
456                       desc->signature);
457         ret = -EINVAL;
458         goto exit;
459     }
460
461     file_offset = desc->file_offset;
462
463     /* count is only > 1 if we are writing zeroes */
464     for (i = 0; i < count; i++) {
465         ret = bdrv_pwrite_sync(bs->file, file_offset, buffer,
466                                VHDX_LOG_SECTOR_SIZE);
467         if (ret < 0) {
468             goto exit;
469         }
470         file_offset += VHDX_LOG_SECTOR_SIZE;
471     }
472
473 exit:
474     qemu_vfree(buffer);
475     return ret;
476 }
477
478 /* Flush the entire log (as described by 'logs') to the VHDX image
479  * file, and then set the log to 'empty' status once complete.
480  *
481  * The log entries should be validate prior to flushing */
482 static int vhdx_log_flush(BlockDriverState *bs, BDRVVHDXState *s,
483                           VHDXLogSequence *logs)
484 {
485     int ret = 0;
486     int i;
487     uint32_t cnt, sectors_read;
488     uint64_t new_file_size;
489     void *data = NULL;
490     VHDXLogDescEntries *desc_entries = NULL;
491     VHDXLogEntryHeader hdr_tmp = { 0 };
492
493     cnt = logs->count;
494
495     data = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);
496
497     ret = vhdx_user_visible_write(bs, s);
498     if (ret < 0) {
499         goto exit;
500     }
501
502     /* each iteration represents one log sequence, which may span multiple
503      * sectors */
504     while (cnt--) {
505         ret = vhdx_log_peek_hdr(bs, &logs->log, &hdr_tmp);
506         if (ret < 0) {
507             goto exit;
508         }
509         /* if the log shows a FlushedFileOffset larger than our current file
510          * size, then that means the file has been truncated / corrupted, and
511          * we must refused to open it / use it */
512         if (hdr_tmp.flushed_file_offset > bdrv_getlength(bs->file)) {
513             ret = -EINVAL;
514             goto exit;
515         }
516
517         ret = vhdx_log_read_desc(bs, s, &logs->log, &desc_entries, true);
518         if (ret < 0) {
519             goto exit;
520         }
521
522         for (i = 0; i < desc_entries->hdr.descriptor_count; i++) {
523             if (desc_entries->desc[i].signature == VHDX_LOG_DESC_SIGNATURE) {
524                 /* data sector, so read a sector to flush */
525                 ret = vhdx_log_read_sectors(bs, &logs->log, &sectors_read,
526                                             data, 1, false);
527                 if (ret < 0) {
528                     goto exit;
529                 }
530                 if (sectors_read != 1) {
531                     ret = -EINVAL;
532                     goto exit;
533                 }
534                 vhdx_log_data_le_import(data);
535             }
536
537             ret = vhdx_log_flush_desc(bs, &desc_entries->desc[i], data);
538             if (ret < 0) {
539                 goto exit;
540             }
541         }
542         if (bdrv_getlength(bs->file) < desc_entries->hdr.last_file_offset) {
543             new_file_size = desc_entries->hdr.last_file_offset;
544             if (new_file_size % (1024*1024)) {
545                 /* round up to nearest 1MB boundary */
546                 new_file_size = ((new_file_size >> 20) + 1) << 20;
547                 bdrv_truncate(bs->file, new_file_size);
548             }
549         }
550         qemu_vfree(desc_entries);
551         desc_entries = NULL;
552     }
553
554     bdrv_flush(bs);
555     /* once the log is fully flushed, indicate that we have an empty log
556      * now.  This also sets the log guid to 0, to indicate an empty log */
557     vhdx_log_reset(bs, s);
558
559 exit:
560     qemu_vfree(data);
561     qemu_vfree(desc_entries);
562     return ret;
563 }
564
565 static int vhdx_validate_log_entry(BlockDriverState *bs, BDRVVHDXState *s,
566                                    VHDXLogEntries *log, uint64_t seq,
567                                    bool *valid, VHDXLogEntryHeader *entry)
568 {
569     int ret = 0;
570     VHDXLogEntryHeader hdr;
571     void *buffer = NULL;
572     uint32_t i, desc_sectors, total_sectors, crc;
573     uint32_t sectors_read = 0;
574     VHDXLogDescEntries *desc_buffer = NULL;
575
576     *valid = false;
577
578     ret = vhdx_log_peek_hdr(bs, log, &hdr);
579     if (ret < 0) {
580         goto inc_and_exit;
581     }
582
583     if (vhdx_log_hdr_is_valid(log, &hdr, s) == false) {
584         goto inc_and_exit;
585     }
586
587     if (seq > 0) {
588         if (hdr.sequence_number != seq + 1) {
589             goto inc_and_exit;
590         }
591     }
592
593     desc_sectors = vhdx_compute_desc_sectors(hdr.descriptor_count);
594
595     /* Read all log sectors, and calculate log checksum */
596
597     total_sectors = hdr.entry_length / VHDX_LOG_SECTOR_SIZE;
598
599
600     /* read_desc() will increment the read idx */
601     ret = vhdx_log_read_desc(bs, s, log, &desc_buffer, false);
602     if (ret < 0) {
603         goto free_and_exit;
604     }
605
606     crc = vhdx_checksum_calc(0xffffffff, (void *)desc_buffer,
607                             desc_sectors * VHDX_LOG_SECTOR_SIZE, 4);
608     crc ^= 0xffffffff;
609
610     buffer = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);
611     if (total_sectors > desc_sectors) {
612         for (i = 0; i < total_sectors - desc_sectors; i++) {
613             sectors_read = 0;
614             ret = vhdx_log_read_sectors(bs, log, &sectors_read, buffer,
615                                         1, false);
616             if (ret < 0 || sectors_read != 1) {
617                 goto free_and_exit;
618             }
619             crc = vhdx_checksum_calc(crc, buffer, VHDX_LOG_SECTOR_SIZE, -1);
620             crc ^= 0xffffffff;
621         }
622     }
623     crc ^= 0xffffffff;
624     if (crc != hdr.checksum) {
625         goto free_and_exit;
626     }
627
628     *valid = true;
629     *entry = hdr;
630     goto free_and_exit;
631
632 inc_and_exit:
633     log->read = vhdx_log_inc_idx(log->read, log->length);
634
635 free_and_exit:
636     qemu_vfree(buffer);
637     qemu_vfree(desc_buffer);
638     return ret;
639 }
640
641 /* Search through the log circular buffer, and find the valid, active
642  * log sequence, if any exists
643  * */
644 static int vhdx_log_search(BlockDriverState *bs, BDRVVHDXState *s,
645                            VHDXLogSequence *logs)
646 {
647     int ret = 0;
648     uint32_t tail;
649     bool seq_valid = false;
650     VHDXLogSequence candidate = { 0 };
651     VHDXLogEntryHeader hdr = { 0 };
652     VHDXLogEntries curr_log;
653
654     memcpy(&curr_log, &s->log, sizeof(VHDXLogEntries));
655     curr_log.write = curr_log.length;   /* assume log is full */
656     curr_log.read = 0;
657
658
659     /* now we will go through the whole log sector by sector, until
660      * we find a valid, active log sequence, or reach the end of the
661      * log buffer */
662     for (;;) {
663         uint64_t curr_seq = 0;
664         VHDXLogSequence current = { 0 };
665
666         tail = curr_log.read;
667
668         ret = vhdx_validate_log_entry(bs, s, &curr_log, curr_seq,
669                                       &seq_valid, &hdr);
670         if (ret < 0) {
671             goto exit;
672         }
673
674         if (seq_valid) {
675             current.valid     = true;
676             current.log       = curr_log;
677             current.log.read  = tail;
678             current.log.write = curr_log.read;
679             current.count     = 1;
680             current.hdr       = hdr;
681
682
683             for (;;) {
684                 ret = vhdx_validate_log_entry(bs, s, &curr_log, curr_seq,
685                                               &seq_valid, &hdr);
686                 if (ret < 0) {
687                     goto exit;
688                 }
689                 if (seq_valid == false) {
690                     break;
691                 }
692                 current.log.write = curr_log.read;
693                 current.count++;
694
695                 curr_seq = hdr.sequence_number;
696             }
697         }
698
699         if (current.valid) {
700             if (candidate.valid == false ||
701                 current.hdr.sequence_number > candidate.hdr.sequence_number) {
702                 candidate = current;
703             }
704         }
705
706         if (curr_log.read < tail) {
707             break;
708         }
709     }
710
711     *logs = candidate;
712
713     if (candidate.valid) {
714         /* this is the next sequence number, for writes */
715         s->log.sequence = candidate.hdr.sequence_number + 1;
716     }
717
718
719 exit:
720     return ret;
721 }
722
723 /* Parse the replay log.  Per the VHDX spec, if the log is present
724  * it must be replayed prior to opening the file, even read-only.
725  *
726  * If read-only, we must replay the log in RAM (or refuse to open
727  * a dirty VHDX file read-only) */
728 int vhdx_parse_log(BlockDriverState *bs, BDRVVHDXState *s, bool *flushed,
729                    Error **errp)
730 {
731     int ret = 0;
732     VHDXHeader *hdr;
733     VHDXLogSequence logs = { 0 };
734
735     hdr = s->headers[s->curr_header];
736
737     *flushed = false;
738
739     /* s->log.hdr is freed in vhdx_close() */
740     if (s->log.hdr == NULL) {
741         s->log.hdr = qemu_blockalign(bs, sizeof(VHDXLogEntryHeader));
742     }
743
744     s->log.offset = hdr->log_offset;
745     s->log.length = hdr->log_length;
746
747     if (s->log.offset < VHDX_LOG_MIN_SIZE ||
748         s->log.offset % VHDX_LOG_MIN_SIZE) {
749         ret = -EINVAL;
750         goto exit;
751     }
752
753     /* per spec, only log version of 0 is supported */
754     if (hdr->log_version != 0) {
755         ret = -EINVAL;
756         goto exit;
757     }
758
759     /* If either the log guid, or log length is zero,
760      * then a replay log is not present */
761     if (guid_eq(hdr->log_guid, zero_guid)) {
762         goto exit;
763     }
764
765     if (hdr->log_length == 0) {
766         goto exit;
767     }
768
769     if (hdr->log_length % VHDX_LOG_MIN_SIZE) {
770         ret = -EINVAL;
771         goto exit;
772     }
773
774
775     /* The log is present, we need to find if and where there is an active
776      * sequence of valid entries present in the log.  */
777
778     ret = vhdx_log_search(bs, s, &logs);
779     if (ret < 0) {
780         goto exit;
781     }
782
783     if (logs.valid) {
784         if (bs->read_only) {
785             ret = -EPERM;
786             error_setg_errno(errp, EPERM,
787                              "VHDX image file '%s' opened read-only, but "
788                              "contains a log that needs to be replayed.  To "
789                              "replay the log, execute:\n qemu-img check -r "
790                              "all '%s'",
791                              bs->filename, bs->filename);
792             goto exit;
793         }
794         /* now flush the log */
795         ret = vhdx_log_flush(bs, s, &logs);
796         if (ret < 0) {
797             goto exit;
798         }
799         *flushed = true;
800     }
801
802
803 exit:
804     return ret;
805 }
806
807
808
809 static void vhdx_log_raw_to_le_sector(VHDXLogDescriptor *desc,
810                                       VHDXLogDataSector *sector, void *data,
811                                       uint64_t seq)
812 {
813     /* 8 + 4084 + 4 = 4096, 1 log sector */
814     memcpy(&desc->leading_bytes, data, 8);
815     data += 8;
816     cpu_to_le64s(&desc->leading_bytes);
817     memcpy(sector->data, data, 4084);
818     data += 4084;
819     memcpy(&desc->trailing_bytes, data, 4);
820     cpu_to_le32s(&desc->trailing_bytes);
821     data += 4;
822
823     sector->sequence_high  = (uint32_t) (seq >> 32);
824     sector->sequence_low   = (uint32_t) (seq & 0xffffffff);
825     sector->data_signature = VHDX_LOG_DATA_SIGNATURE;
826
827     vhdx_log_desc_le_export(desc);
828     vhdx_log_data_le_export(sector);
829 }
830
831
832 static int vhdx_log_write(BlockDriverState *bs, BDRVVHDXState *s,
833                           void *data, uint32_t length, uint64_t offset)
834 {
835     int ret = 0;
836     void *buffer = NULL;
837     void *merged_sector = NULL;
838     void *data_tmp, *sector_write;
839     unsigned int i;
840     int sector_offset;
841     uint32_t desc_sectors, sectors, total_length;
842     uint32_t sectors_written = 0;
843     uint32_t aligned_length;
844     uint32_t leading_length = 0;
845     uint32_t trailing_length = 0;
846     uint32_t partial_sectors = 0;
847     uint32_t bytes_written = 0;
848     uint64_t file_offset;
849     VHDXHeader *header;
850     VHDXLogEntryHeader new_hdr;
851     VHDXLogDescriptor *new_desc = NULL;
852     VHDXLogDataSector *data_sector = NULL;
853     MSGUID new_guid = { 0 };
854
855     header = s->headers[s->curr_header];
856
857     /* need to have offset read data, and be on 4096 byte boundary */
858
859     if (length > header->log_length) {
860         /* no log present.  we could create a log here instead of failing */
861         ret = -EINVAL;
862         goto exit;
863     }
864
865     if (guid_eq(header->log_guid, zero_guid)) {
866         vhdx_guid_generate(&new_guid);
867         vhdx_update_headers(bs, s, false, &new_guid);
868     } else {
869         /* currently, we require that the log be flushed after
870          * every write. */
871         ret = -ENOTSUP;
872         goto exit;
873     }
874
875     /* 0 is an invalid sequence number, but may also represent the first
876      * log write (or a wrapped seq) */
877     if (s->log.sequence == 0) {
878         s->log.sequence = 1;
879     }
880
881     sector_offset = offset % VHDX_LOG_SECTOR_SIZE;
882     file_offset = (offset / VHDX_LOG_SECTOR_SIZE) * VHDX_LOG_SECTOR_SIZE;
883
884     aligned_length = length;
885
886     /* add in the unaligned head and tail bytes */
887     if (sector_offset) {
888         leading_length = (VHDX_LOG_SECTOR_SIZE - sector_offset);
889         leading_length = leading_length > length ? length : leading_length;
890         aligned_length -= leading_length;
891         partial_sectors++;
892     }
893
894     sectors = aligned_length / VHDX_LOG_SECTOR_SIZE;
895     trailing_length = aligned_length - (sectors * VHDX_LOG_SECTOR_SIZE);
896     if (trailing_length) {
897         partial_sectors++;
898     }
899
900     sectors += partial_sectors;
901
902     /* sectors is now how many sectors the data itself takes, not
903      * including the header and descriptor metadata */
904
905     new_hdr = (VHDXLogEntryHeader) {
906                 .signature           = VHDX_LOG_SIGNATURE,
907                 .tail                = s->log.tail,
908                 .sequence_number     = s->log.sequence,
909                 .descriptor_count    = sectors,
910                 .reserved            = 0,
911                 .flushed_file_offset = bdrv_getlength(bs->file),
912                 .last_file_offset    = bdrv_getlength(bs->file),
913               };
914
915     new_hdr.log_guid = header->log_guid;
916
917     desc_sectors = vhdx_compute_desc_sectors(new_hdr.descriptor_count);
918
919     total_length = (desc_sectors + sectors) * VHDX_LOG_SECTOR_SIZE;
920     new_hdr.entry_length = total_length;
921
922     vhdx_log_entry_hdr_le_export(&new_hdr);
923
924     buffer = qemu_blockalign(bs, total_length);
925     memcpy(buffer, &new_hdr, sizeof(new_hdr));
926
927     new_desc = buffer + sizeof(new_hdr);
928     data_sector = buffer + (desc_sectors * VHDX_LOG_SECTOR_SIZE);
929     data_tmp = data;
930
931     /* All log sectors are 4KB, so for any partial sectors we must
932      * merge the data with preexisting data from the final file
933      * destination */
934     merged_sector = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);
935
936     for (i = 0; i < sectors; i++) {
937         new_desc->signature       = VHDX_LOG_DESC_SIGNATURE;
938         new_desc->sequence_number = s->log.sequence;
939         new_desc->file_offset     = file_offset;
940
941         if (i == 0 && leading_length) {
942             /* partial sector at the front of the buffer */
943             ret = bdrv_pread(bs->file, file_offset, merged_sector,
944                              VHDX_LOG_SECTOR_SIZE);
945             if (ret < 0) {
946                 goto exit;
947             }
948             memcpy(merged_sector + sector_offset, data_tmp, leading_length);
949             bytes_written = leading_length;
950             sector_write = merged_sector;
951         } else if (i == sectors - 1 && trailing_length) {
952             /* partial sector at the end of the buffer */
953             ret = bdrv_pread(bs->file,
954                             file_offset,
955                             merged_sector + trailing_length,
956                             VHDX_LOG_SECTOR_SIZE - trailing_length);
957             if (ret < 0) {
958                 goto exit;
959             }
960             memcpy(merged_sector, data_tmp, trailing_length);
961             bytes_written = trailing_length;
962             sector_write = merged_sector;
963         } else {
964             bytes_written = VHDX_LOG_SECTOR_SIZE;
965             sector_write = data_tmp;
966         }
967
968         /* populate the raw sector data into the proper structures,
969          * as well as update the descriptor, and convert to proper
970          * endianness */
971         vhdx_log_raw_to_le_sector(new_desc, data_sector, sector_write,
972                                   s->log.sequence);
973
974         data_tmp += bytes_written;
975         data_sector++;
976         new_desc++;
977         file_offset += VHDX_LOG_SECTOR_SIZE;
978     }
979
980     /* checksum covers entire entry, from the log header through the
981      * last data sector */
982     vhdx_update_checksum(buffer, total_length,
983                          offsetof(VHDXLogEntryHeader, checksum));
984
985     /* now write to the log */
986     ret = vhdx_log_write_sectors(bs, &s->log, &sectors_written, buffer,
987                                  desc_sectors + sectors);
988     if (ret < 0) {
989         goto exit;
990     }
991
992     if (sectors_written != desc_sectors + sectors) {
993         /* instead of failing, we could flush the log here */
994         ret = -EINVAL;
995         goto exit;
996     }
997
998     s->log.sequence++;
999     /* write new tail */
1000     s->log.tail = s->log.write;
1001
1002 exit:
1003     qemu_vfree(buffer);
1004     qemu_vfree(merged_sector);
1005     return ret;
1006 }
1007
1008 /* Perform a log write, and then immediately flush the entire log */
1009 int vhdx_log_write_and_flush(BlockDriverState *bs, BDRVVHDXState *s,
1010                              void *data, uint32_t length, uint64_t offset)
1011 {
1012     int ret = 0;
1013     VHDXLogSequence logs = { .valid = true,
1014                              .count = 1,
1015                              .hdr = { 0 } };
1016
1017
1018     /* Make sure data written (new and/or changed blocks) is stable
1019      * on disk, before creating log entry */
1020     bdrv_flush(bs);
1021     ret = vhdx_log_write(bs, s, data, length, offset);
1022     if (ret < 0) {
1023         goto exit;
1024     }
1025     logs.log = s->log;
1026
1027     /* Make sure log is stable on disk */
1028     bdrv_flush(bs);
1029     ret = vhdx_log_flush(bs, s, &logs);
1030     if (ret < 0) {
1031         goto exit;
1032     }
1033
1034     s->log = logs.log;
1035
1036 exit:
1037     return ret;
1038 }
1039