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