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