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