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