xref: /openbmc/qemu/block/vhdx-log.c (revision 4c25f365)
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 incrememnt 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 {
711     int ret = 0;
712     VHDXHeader *hdr;
713     VHDXLogSequence logs = { 0 };
714 
715     hdr = s->headers[s->curr_header];
716 
717     *flushed = false;
718 
719     /* s->log.hdr is freed in vhdx_close() */
720     if (s->log.hdr == NULL) {
721         s->log.hdr = qemu_blockalign(bs, sizeof(VHDXLogEntryHeader));
722     }
723 
724     s->log.offset = hdr->log_offset;
725     s->log.length = hdr->log_length;
726 
727     if (s->log.offset < VHDX_LOG_MIN_SIZE ||
728         s->log.offset % VHDX_LOG_MIN_SIZE) {
729         ret = -EINVAL;
730         goto exit;
731     }
732 
733     /* per spec, only log version of 0 is supported */
734     if (hdr->log_version != 0) {
735         ret = -EINVAL;
736         goto exit;
737     }
738 
739     /* If either the log guid, or log length is zero,
740      * then a replay log is not present */
741     if (guid_eq(hdr->log_guid, zero_guid)) {
742         goto exit;
743     }
744 
745     if (hdr->log_length == 0) {
746         goto exit;
747     }
748 
749     if (hdr->log_length % VHDX_LOG_MIN_SIZE) {
750         ret = -EINVAL;
751         goto exit;
752     }
753 
754 
755     /* The log is present, we need to find if and where there is an active
756      * sequence of valid entries present in the log.  */
757 
758     ret = vhdx_log_search(bs, s, &logs);
759     if (ret < 0) {
760         goto exit;
761     }
762 
763     if (logs.valid) {
764         /* now flush the log */
765         ret = vhdx_log_flush(bs, s, &logs);
766         if (ret < 0) {
767             goto exit;
768         }
769         *flushed = true;
770     }
771 
772 
773 exit:
774     return ret;
775 }
776 
777 
778 
779 static void vhdx_log_raw_to_le_sector(VHDXLogDescriptor *desc,
780                                       VHDXLogDataSector *sector, void *data,
781                                       uint64_t seq)
782 {
783     /* 8 + 4084 + 4 = 4096, 1 log sector */
784     memcpy(&desc->leading_bytes, data, 8);
785     data += 8;
786     cpu_to_le64s(&desc->leading_bytes);
787     memcpy(sector->data, data, 4084);
788     data += 4084;
789     memcpy(&desc->trailing_bytes, data, 4);
790     cpu_to_le32s(&desc->trailing_bytes);
791     data += 4;
792 
793     sector->sequence_high  = (uint32_t) (seq >> 32);
794     sector->sequence_low   = (uint32_t) (seq & 0xffffffff);
795     sector->data_signature = VHDX_LOG_DATA_SIGNATURE;
796 
797     vhdx_log_desc_le_export(desc);
798     vhdx_log_data_le_export(sector);
799 }
800 
801 
802 static int vhdx_log_write(BlockDriverState *bs, BDRVVHDXState *s,
803                           void *data, uint32_t length, uint64_t offset)
804 {
805     int ret = 0;
806     void *buffer = NULL;
807     void *merged_sector = NULL;
808     void *data_tmp, *sector_write;
809     unsigned int i;
810     int sector_offset;
811     uint32_t desc_sectors, sectors, total_length;
812     uint32_t sectors_written = 0;
813     uint32_t aligned_length;
814     uint32_t leading_length = 0;
815     uint32_t trailing_length = 0;
816     uint32_t partial_sectors = 0;
817     uint32_t bytes_written = 0;
818     uint64_t file_offset;
819     VHDXHeader *header;
820     VHDXLogEntryHeader new_hdr;
821     VHDXLogDescriptor *new_desc = NULL;
822     VHDXLogDataSector *data_sector = NULL;
823     MSGUID new_guid = { 0 };
824 
825     header = s->headers[s->curr_header];
826 
827     /* need to have offset read data, and be on 4096 byte boundary */
828 
829     if (length > header->log_length) {
830         /* no log present.  we could create a log here instead of failing */
831         ret = -EINVAL;
832         goto exit;
833     }
834 
835     if (guid_eq(header->log_guid, zero_guid)) {
836         vhdx_guid_generate(&new_guid);
837         vhdx_update_headers(bs, s, false, &new_guid);
838     } else {
839         /* currently, we require that the log be flushed after
840          * every write. */
841         ret = -ENOTSUP;
842         goto exit;
843     }
844 
845     /* 0 is an invalid sequence number, but may also represent the first
846      * log write (or a wrapped seq) */
847     if (s->log.sequence == 0) {
848         s->log.sequence = 1;
849     }
850 
851     sector_offset = offset % VHDX_LOG_SECTOR_SIZE;
852     file_offset = (offset / VHDX_LOG_SECTOR_SIZE) * VHDX_LOG_SECTOR_SIZE;
853 
854     aligned_length = length;
855 
856     /* add in the unaligned head and tail bytes */
857     if (sector_offset) {
858         leading_length = (VHDX_LOG_SECTOR_SIZE - sector_offset);
859         leading_length = leading_length > length ? length : leading_length;
860         aligned_length -= leading_length;
861         partial_sectors++;
862     }
863 
864     sectors = aligned_length / VHDX_LOG_SECTOR_SIZE;
865     trailing_length = aligned_length - (sectors * VHDX_LOG_SECTOR_SIZE);
866     if (trailing_length) {
867         partial_sectors++;
868     }
869 
870     sectors += partial_sectors;
871 
872     /* sectors is now how many sectors the data itself takes, not
873      * including the header and descriptor metadata */
874 
875     new_hdr = (VHDXLogEntryHeader) {
876                 .signature           = VHDX_LOG_SIGNATURE,
877                 .tail                = s->log.tail,
878                 .sequence_number     = s->log.sequence,
879                 .descriptor_count    = sectors,
880                 .reserved            = 0,
881                 .flushed_file_offset = bdrv_getlength(bs->file),
882                 .last_file_offset    = bdrv_getlength(bs->file),
883               };
884 
885     new_hdr.log_guid = header->log_guid;
886 
887     desc_sectors = vhdx_compute_desc_sectors(new_hdr.descriptor_count);
888 
889     total_length = (desc_sectors + sectors) * VHDX_LOG_SECTOR_SIZE;
890     new_hdr.entry_length = total_length;
891 
892     vhdx_log_entry_hdr_le_export(&new_hdr);
893 
894     buffer = qemu_blockalign(bs, total_length);
895     memcpy(buffer, &new_hdr, sizeof(new_hdr));
896 
897     new_desc = (VHDXLogDescriptor *) (buffer + sizeof(new_hdr));
898     data_sector = buffer + (desc_sectors * VHDX_LOG_SECTOR_SIZE);
899     data_tmp = data;
900 
901     /* All log sectors are 4KB, so for any partial sectors we must
902      * merge the data with preexisting data from the final file
903      * destination */
904     merged_sector = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);
905 
906     for (i = 0; i < sectors; i++) {
907         new_desc->signature       = VHDX_LOG_DESC_SIGNATURE;
908         new_desc->sequence_number = s->log.sequence;
909         new_desc->file_offset     = file_offset;
910 
911         if (i == 0 && leading_length) {
912             /* partial sector at the front of the buffer */
913             ret = bdrv_pread(bs->file, file_offset, merged_sector,
914                              VHDX_LOG_SECTOR_SIZE);
915             if (ret < 0) {
916                 goto exit;
917             }
918             memcpy(merged_sector + sector_offset, data_tmp, leading_length);
919             bytes_written = leading_length;
920             sector_write = merged_sector;
921         } else if (i == sectors - 1 && trailing_length) {
922             /* partial sector at the end of the buffer */
923             ret = bdrv_pread(bs->file,
924                             file_offset,
925                             merged_sector + trailing_length,
926                             VHDX_LOG_SECTOR_SIZE - trailing_length);
927             if (ret < 0) {
928                 goto exit;
929             }
930             memcpy(merged_sector, data_tmp, trailing_length);
931             bytes_written = trailing_length;
932             sector_write = merged_sector;
933         } else {
934             bytes_written = VHDX_LOG_SECTOR_SIZE;
935             sector_write = data_tmp;
936         }
937 
938         /* populate the raw sector data into the proper structures,
939          * as well as update the descriptor, and convert to proper
940          * endianness */
941         vhdx_log_raw_to_le_sector(new_desc, data_sector, sector_write,
942                                   s->log.sequence);
943 
944         data_tmp += bytes_written;
945         data_sector++;
946         new_desc++;
947         file_offset += VHDX_LOG_SECTOR_SIZE;
948     }
949 
950     /* checksum covers entire entry, from the log header through the
951      * last data sector */
952     vhdx_update_checksum(buffer, total_length,
953                          offsetof(VHDXLogEntryHeader, checksum));
954     cpu_to_le32s((uint32_t *)(buffer + 4));
955 
956     /* now write to the log */
957     vhdx_log_write_sectors(bs, &s->log, &sectors_written, buffer,
958                            desc_sectors + sectors);
959     if (ret < 0) {
960         goto exit;
961     }
962 
963     if (sectors_written != desc_sectors + sectors) {
964         /* instead of failing, we could flush the log here */
965         ret = -EINVAL;
966         goto exit;
967     }
968 
969     s->log.sequence++;
970     /* write new tail */
971     s->log.tail = s->log.write;
972 
973 exit:
974     qemu_vfree(buffer);
975     qemu_vfree(merged_sector);
976     return ret;
977 }
978 
979 /* Perform a log write, and then immediately flush the entire log */
980 int vhdx_log_write_and_flush(BlockDriverState *bs, BDRVVHDXState *s,
981                              void *data, uint32_t length, uint64_t offset)
982 {
983     int ret = 0;
984     VHDXLogSequence logs = { .valid = true,
985                              .count = 1,
986                              .hdr = { 0 } };
987 
988 
989     /* Make sure data written (new and/or changed blocks) is stable
990      * on disk, before creating log entry */
991     bdrv_flush(bs);
992     ret = vhdx_log_write(bs, s, data, length, offset);
993     if (ret < 0) {
994         goto exit;
995     }
996     logs.log = s->log;
997 
998     /* Make sure log is stable on disk */
999     bdrv_flush(bs);
1000     ret = vhdx_log_flush(bs, s, &logs);
1001     if (ret < 0) {
1002         goto exit;
1003     }
1004 
1005     s->log = logs.log;
1006 
1007 exit:
1008     return ret;
1009 }
1010 
1011