4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu/osdep.h"
26 #include "qemu/madvise.h"
27 #include "qemu/error-report.h"
29 #include "migration.h"
30 #include "migration-stats.h"
31 #include "qemu-file.h"
34 #include "qapi/error.h"
36 #define IO_BUF_SIZE 32768
37 #define MAX_IOV_SIZE MIN_CONST(IOV_MAX, 64)
40 const QEMUFileHooks
*hooks
;
44 /* The sum of bytes transferred on the wire */
45 uint64_t total_transferred
;
48 int buf_size
; /* 0 when writing */
49 uint8_t buf
[IO_BUF_SIZE
];
51 DECLARE_BITMAP(may_free
, MAX_IOV_SIZE
);
52 struct iovec iov
[MAX_IOV_SIZE
];
56 Error
*last_error_obj
;
60 * Stop a file from being read/written - not all backing files can do this
61 * typically only sockets can.
63 * TODO: convert to propagate Error objects instead of squashing
64 * to a fixed errno value
66 int qemu_file_shutdown(QEMUFile
*f
)
69 * We must set qemufile error before the real shutdown(), otherwise
70 * there can be a race window where we thought IO all went though
71 * (because last_error==NULL) but actually IO has already stopped.
73 * If without correct ordering, the race can happen like this:
75 * page receiver other thread
76 * ------------- ------------
79 * returns 0 (buffer all zero)
80 * (we didn't check this retcode)
81 * try to detect IO error
82 * last_error==NULL, IO okay
83 * install ALL-ZERO page
88 qemu_file_set_error(f
, -EIO
);
91 if (!qio_channel_has_feature(f
->ioc
,
92 QIO_CHANNEL_FEATURE_SHUTDOWN
)) {
96 if (qio_channel_shutdown(f
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
) < 0) {
103 static QEMUFile
*qemu_file_new_impl(QIOChannel
*ioc
, bool is_writable
)
107 f
= g_new0(QEMUFile
, 1);
111 f
->is_writable
= is_writable
;
117 * Result: QEMUFile* for a 'return path' for comms in the opposite direction
118 * NULL if not available
120 QEMUFile
*qemu_file_get_return_path(QEMUFile
*f
)
122 return qemu_file_new_impl(f
->ioc
, !f
->is_writable
);
125 QEMUFile
*qemu_file_new_output(QIOChannel
*ioc
)
127 return qemu_file_new_impl(ioc
, true);
130 QEMUFile
*qemu_file_new_input(QIOChannel
*ioc
)
132 return qemu_file_new_impl(ioc
, false);
135 void qemu_file_set_hooks(QEMUFile
*f
, const QEMUFileHooks
*hooks
)
141 * Get last error for stream f with optional Error*
143 * Return negative error value if there has been an error on previous
144 * operations, return 0 if no error happened.
145 * Optional, it returns Error* in errp, but it may be NULL even if return value
149 static int qemu_file_get_error_obj(QEMUFile
*f
, Error
**errp
)
152 *errp
= f
->last_error_obj
? error_copy(f
->last_error_obj
) : NULL
;
154 return f
->last_error
;
158 * Get last error for either stream f1 or f2 with optional Error*.
159 * The error returned (non-zero) can be either from f1 or f2.
161 * If any of the qemufile* is NULL, then skip the check on that file.
163 * When there is no error on both qemufile, zero is returned.
165 int qemu_file_get_error_obj_any(QEMUFile
*f1
, QEMUFile
*f2
, Error
**errp
)
170 ret
= qemu_file_get_error_obj(f1
, errp
);
171 /* If there's already error detected, return */
178 ret
= qemu_file_get_error_obj(f2
, errp
);
185 * Set the last error for stream f with optional Error*
187 void qemu_file_set_error_obj(QEMUFile
*f
, int ret
, Error
*err
)
189 if (f
->last_error
== 0 && ret
) {
191 error_propagate(&f
->last_error_obj
, err
);
193 error_report_err(err
);
198 * Get last error for stream f
200 * Return negative error value if there has been an error on previous
201 * operations, return 0 if no error happened.
204 int qemu_file_get_error(QEMUFile
*f
)
206 return qemu_file_get_error_obj(f
, NULL
);
210 * Set the last error for stream f
212 void qemu_file_set_error(QEMUFile
*f
, int ret
)
214 qemu_file_set_error_obj(f
, ret
, NULL
);
217 static bool qemu_file_is_writable(QEMUFile
*f
)
219 return f
->is_writable
;
222 static void qemu_iovec_release_ram(QEMUFile
*f
)
227 /* Find and release all the contiguous memory ranges marked as may_free. */
228 idx
= find_next_bit(f
->may_free
, f
->iovcnt
, 0);
229 if (idx
>= f
->iovcnt
) {
234 /* The madvise() in the loop is called for iov within a continuous range and
235 * then reinitialize the iov. And in the end, madvise() is called for the
238 while ((idx
= find_next_bit(f
->may_free
, f
->iovcnt
, idx
+ 1)) < f
->iovcnt
) {
239 /* check for adjacent buffer and coalesce them */
240 if (iov
.iov_base
+ iov
.iov_len
== f
->iov
[idx
].iov_base
) {
241 iov
.iov_len
+= f
->iov
[idx
].iov_len
;
244 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
245 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
246 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
250 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
251 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
252 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
254 memset(f
->may_free
, 0, sizeof(f
->may_free
));
259 * Flushes QEMUFile buffer
261 * This will flush all pending data. If data was only partially flushed, it
262 * will set an error state.
264 void qemu_fflush(QEMUFile
*f
)
266 if (!qemu_file_is_writable(f
)) {
270 if (qemu_file_get_error(f
)) {
274 Error
*local_error
= NULL
;
275 if (qio_channel_writev_all(f
->ioc
,
278 qemu_file_set_error_obj(f
, -EIO
, local_error
);
280 uint64_t size
= iov_size(f
->iov
, f
->iovcnt
);
281 f
->total_transferred
+= size
;
284 qemu_iovec_release_ram(f
);
291 void ram_control_before_iterate(QEMUFile
*f
, uint64_t flags
)
295 if (f
->hooks
&& f
->hooks
->before_ram_iterate
) {
296 ret
= f
->hooks
->before_ram_iterate(f
, flags
, NULL
);
298 qemu_file_set_error(f
, ret
);
303 void ram_control_after_iterate(QEMUFile
*f
, uint64_t flags
)
307 if (f
->hooks
&& f
->hooks
->after_ram_iterate
) {
308 ret
= f
->hooks
->after_ram_iterate(f
, flags
, NULL
);
310 qemu_file_set_error(f
, ret
);
315 void ram_control_load_hook(QEMUFile
*f
, uint64_t flags
, void *data
)
317 if (f
->hooks
&& f
->hooks
->hook_ram_load
) {
318 int ret
= f
->hooks
->hook_ram_load(f
, flags
, data
);
320 qemu_file_set_error(f
, ret
);
325 size_t ram_control_save_page(QEMUFile
*f
, ram_addr_t block_offset
,
326 ram_addr_t offset
, size_t size
,
327 uint64_t *bytes_sent
)
329 if (f
->hooks
&& f
->hooks
->save_page
) {
330 int ret
= f
->hooks
->save_page(f
, block_offset
,
331 offset
, size
, bytes_sent
);
333 if (ret
!= RAM_SAVE_CONTROL_DELAYED
&&
334 ret
!= RAM_SAVE_CONTROL_NOT_SUPP
) {
335 if (bytes_sent
&& *bytes_sent
> 0) {
336 qemu_file_credit_transfer(f
, *bytes_sent
);
337 } else if (ret
< 0) {
338 qemu_file_set_error(f
, ret
);
345 return RAM_SAVE_CONTROL_NOT_SUPP
;
349 * Attempt to fill the buffer from the underlying file
350 * Returns the number of bytes read, or negative value for an error.
352 * Note that it can return a partially full buffer even in a not error/not EOF
353 * case if the underlying file descriptor gives a short read, and that can
354 * happen even on a blocking fd.
356 static ssize_t coroutine_mixed_fn
qemu_fill_buffer(QEMUFile
*f
)
360 Error
*local_error
= NULL
;
362 assert(!qemu_file_is_writable(f
));
364 pending
= f
->buf_size
- f
->buf_index
;
366 memmove(f
->buf
, f
->buf
+ f
->buf_index
, pending
);
369 f
->buf_size
= pending
;
371 if (qemu_file_get_error(f
)) {
376 len
= qio_channel_read(f
->ioc
,
377 (char *)f
->buf
+ pending
,
378 IO_BUF_SIZE
- pending
,
380 if (len
== QIO_CHANNEL_ERR_BLOCK
) {
381 if (qemu_in_coroutine()) {
382 qio_channel_yield(f
->ioc
, G_IO_IN
);
384 qio_channel_wait(f
->ioc
, G_IO_IN
);
386 } else if (len
< 0) {
389 } while (len
== QIO_CHANNEL_ERR_BLOCK
);
393 f
->total_transferred
+= len
;
394 } else if (len
== 0) {
395 qemu_file_set_error_obj(f
, -EIO
, local_error
);
397 qemu_file_set_error_obj(f
, len
, local_error
);
403 void qemu_file_credit_transfer(QEMUFile
*f
, size_t size
)
405 f
->total_transferred
+= size
;
410 * Returns negative error value if any error happened on previous operations or
411 * while closing the file. Returns 0 or positive number on success.
413 * The meaning of return value on success depends on the specific backend
416 int qemu_fclose(QEMUFile
*f
)
420 ret
= qemu_file_get_error(f
);
422 ret2
= qio_channel_close(f
->ioc
, NULL
);
426 g_clear_pointer(&f
->ioc
, object_unref
);
428 /* If any error was spotted before closing, we should report it
429 * instead of the close() return value.
434 error_free(f
->last_error_obj
);
436 trace_qemu_file_fclose();
441 * Add buf to iovec. Do flush if iovec is full.
444 * 1 iovec is full and flushed
445 * 0 iovec is not flushed
448 static int add_to_iovec(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
451 /* check for adjacent buffer and coalesce them */
452 if (f
->iovcnt
> 0 && buf
== f
->iov
[f
->iovcnt
- 1].iov_base
+
453 f
->iov
[f
->iovcnt
- 1].iov_len
&&
454 may_free
== test_bit(f
->iovcnt
- 1, f
->may_free
))
456 f
->iov
[f
->iovcnt
- 1].iov_len
+= size
;
458 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
459 /* Should only happen if a previous fflush failed */
460 assert(qemu_file_get_error(f
) || !qemu_file_is_writable(f
));
464 set_bit(f
->iovcnt
, f
->may_free
);
466 f
->iov
[f
->iovcnt
].iov_base
= (uint8_t *)buf
;
467 f
->iov
[f
->iovcnt
++].iov_len
= size
;
470 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
478 static void add_buf_to_iovec(QEMUFile
*f
, size_t len
)
480 if (!add_to_iovec(f
, f
->buf
+ f
->buf_index
, len
, false)) {
482 if (f
->buf_index
== IO_BUF_SIZE
) {
488 void qemu_put_buffer_async(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
495 add_to_iovec(f
, buf
, size
, may_free
);
498 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, size_t size
)
507 l
= IO_BUF_SIZE
- f
->buf_index
;
511 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
512 add_buf_to_iovec(f
, l
);
513 if (qemu_file_get_error(f
)) {
521 void qemu_put_byte(QEMUFile
*f
, int v
)
527 f
->buf
[f
->buf_index
] = v
;
528 add_buf_to_iovec(f
, 1);
531 void qemu_file_skip(QEMUFile
*f
, int size
)
533 if (f
->buf_index
+ size
<= f
->buf_size
) {
534 f
->buf_index
+= size
;
539 * Read 'size' bytes from file (at 'offset') without moving the
540 * pointer and set 'buf' to point to that data.
542 * It will return size bytes unless there was an error, in which case it will
543 * return as many as it managed to read (assuming blocking fd's which
544 * all current QEMUFile are)
546 size_t coroutine_mixed_fn
qemu_peek_buffer(QEMUFile
*f
, uint8_t **buf
, size_t size
, size_t offset
)
551 assert(!qemu_file_is_writable(f
));
552 assert(offset
< IO_BUF_SIZE
);
553 assert(size
<= IO_BUF_SIZE
- offset
);
555 /* The 1st byte to read from */
556 index
= f
->buf_index
+ offset
;
557 /* The number of available bytes starting at index */
558 pending
= f
->buf_size
- index
;
561 * qemu_fill_buffer might return just a few bytes, even when there isn't
562 * an error, so loop collecting them until we get enough.
564 while (pending
< size
) {
565 int received
= qemu_fill_buffer(f
);
571 index
= f
->buf_index
+ offset
;
572 pending
= f
->buf_size
- index
;
578 if (size
> pending
) {
582 *buf
= f
->buf
+ index
;
587 * Read 'size' bytes of data from the file into buf.
588 * 'size' can be larger than the internal buffer.
590 * It will return size bytes unless there was an error, in which case it will
591 * return as many as it managed to read (assuming blocking fd's which
592 * all current QEMUFile are)
594 size_t coroutine_mixed_fn
qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, size_t size
)
596 size_t pending
= size
;
599 while (pending
> 0) {
603 res
= qemu_peek_buffer(f
, &src
, MIN(pending
, IO_BUF_SIZE
), 0);
607 memcpy(buf
, src
, res
);
608 qemu_file_skip(f
, res
);
617 * Read 'size' bytes of data from the file.
618 * 'size' can be larger than the internal buffer.
621 * may be held on an internal buffer (in which case *buf is updated
622 * to point to it) that is valid until the next qemu_file operation.
624 * will be copied to the *buf that was passed in.
626 * The code tries to avoid the copy if possible.
628 * It will return size bytes unless there was an error, in which case it will
629 * return as many as it managed to read (assuming blocking fd's which
630 * all current QEMUFile are)
632 * Note: Since **buf may get changed, the caller should take care to
633 * keep a pointer to the original buffer if it needs to deallocate it.
635 size_t coroutine_mixed_fn
qemu_get_buffer_in_place(QEMUFile
*f
, uint8_t **buf
, size_t size
)
637 if (size
< IO_BUF_SIZE
) {
641 res
= qemu_peek_buffer(f
, &src
, size
, 0);
644 qemu_file_skip(f
, res
);
650 return qemu_get_buffer(f
, *buf
, size
);
654 * Peeks a single byte from the buffer; this isn't guaranteed to work if
655 * offset leaves a gap after the previous read/peeked data.
657 int coroutine_mixed_fn
qemu_peek_byte(QEMUFile
*f
, int offset
)
659 int index
= f
->buf_index
+ offset
;
661 assert(!qemu_file_is_writable(f
));
662 assert(offset
< IO_BUF_SIZE
);
664 if (index
>= f
->buf_size
) {
666 index
= f
->buf_index
+ offset
;
667 if (index
>= f
->buf_size
) {
671 return f
->buf
[index
];
674 int coroutine_mixed_fn
qemu_get_byte(QEMUFile
*f
)
678 result
= qemu_peek_byte(f
, 0);
679 qemu_file_skip(f
, 1);
683 uint64_t qemu_file_transferred_noflush(QEMUFile
*f
)
685 uint64_t ret
= f
->total_transferred
;
688 for (i
= 0; i
< f
->iovcnt
; i
++) {
689 ret
+= f
->iov
[i
].iov_len
;
695 uint64_t qemu_file_transferred(QEMUFile
*f
)
698 return f
->total_transferred
;
701 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
703 qemu_put_byte(f
, v
>> 8);
707 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
709 qemu_put_byte(f
, v
>> 24);
710 qemu_put_byte(f
, v
>> 16);
711 qemu_put_byte(f
, v
>> 8);
715 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
717 qemu_put_be32(f
, v
>> 32);
721 unsigned int qemu_get_be16(QEMUFile
*f
)
724 v
= qemu_get_byte(f
) << 8;
725 v
|= qemu_get_byte(f
);
729 unsigned int qemu_get_be32(QEMUFile
*f
)
732 v
= (unsigned int)qemu_get_byte(f
) << 24;
733 v
|= qemu_get_byte(f
) << 16;
734 v
|= qemu_get_byte(f
) << 8;
735 v
|= qemu_get_byte(f
);
739 uint64_t qemu_get_be64(QEMUFile
*f
)
742 v
= (uint64_t)qemu_get_be32(f
) << 32;
743 v
|= qemu_get_be32(f
);
747 /* return the size after compression, or negative value on error */
748 static int qemu_compress_data(z_stream
*stream
, uint8_t *dest
, size_t dest_len
,
749 const uint8_t *source
, size_t source_len
)
753 err
= deflateReset(stream
);
758 stream
->avail_in
= source_len
;
759 stream
->next_in
= (uint8_t *)source
;
760 stream
->avail_out
= dest_len
;
761 stream
->next_out
= dest
;
763 err
= deflate(stream
, Z_FINISH
);
764 if (err
!= Z_STREAM_END
) {
768 return stream
->next_out
- dest
;
771 /* Compress size bytes of data start at p and store the compressed
772 * data to the buffer of f.
774 * Since the file is dummy file with empty_ops, return -1 if f has no space to
775 * save the compressed data.
777 ssize_t
qemu_put_compression_data(QEMUFile
*f
, z_stream
*stream
,
778 const uint8_t *p
, size_t size
)
780 ssize_t blen
= IO_BUF_SIZE
- f
->buf_index
- sizeof(int32_t);
782 if (blen
< compressBound(size
)) {
786 blen
= qemu_compress_data(stream
, f
->buf
+ f
->buf_index
+ sizeof(int32_t),
792 qemu_put_be32(f
, blen
);
793 add_buf_to_iovec(f
, blen
);
794 return blen
+ sizeof(int32_t);
797 /* Put the data in the buffer of f_src to the buffer of f_des, and
798 * then reset the buf_index of f_src to 0.
801 int qemu_put_qemu_file(QEMUFile
*f_des
, QEMUFile
*f_src
)
805 if (f_src
->buf_index
> 0) {
806 len
= f_src
->buf_index
;
807 qemu_put_buffer(f_des
, f_src
->buf
, f_src
->buf_index
);
808 f_src
->buf_index
= 0;
815 * Check if the writable buffer is empty
818 bool qemu_file_buffer_empty(QEMUFile
*file
)
820 assert(qemu_file_is_writable(file
));
822 return !file
->iovcnt
;
826 * Get a string whose length is determined by a single preceding byte
827 * A preallocated 256 byte buffer must be passed in.
828 * Returns: len on success and a 0 terminated string in the buffer
830 * (Note a 0 length string will return 0 either way)
832 size_t coroutine_fn
qemu_get_counted_string(QEMUFile
*f
, char buf
[256])
834 size_t len
= qemu_get_byte(f
);
835 size_t res
= qemu_get_buffer(f
, (uint8_t *)buf
, len
);
839 return res
== len
? res
: 0;
843 * Put a string with one preceding byte containing its length. The length of
844 * the string should be less than 256.
846 void qemu_put_counted_string(QEMUFile
*f
, const char *str
)
848 size_t len
= strlen(str
);
851 qemu_put_byte(f
, len
);
852 qemu_put_buffer(f
, (const uint8_t *)str
, len
);
856 * Set the blocking state of the QEMUFile.
857 * Note: On some transports the OS only keeps a single blocking state for
858 * both directions, and thus changing the blocking on the main
859 * QEMUFile can also affect the return path.
861 void qemu_file_set_blocking(QEMUFile
*f
, bool block
)
863 qio_channel_set_blocking(f
->ioc
, block
, NULL
);
869 * Get the ioc object for the file, without incrementing
870 * the reference count.
872 * Returns: the ioc object
874 QIOChannel
*qemu_file_get_ioc(QEMUFile
*file
)
880 * Read size bytes from QEMUFile f and write them to fd.
882 int qemu_file_get_to_fd(QEMUFile
*f
, int fd
, size_t size
)
885 size_t pending
= f
->buf_size
- f
->buf_index
;
889 rc
= qemu_fill_buffer(f
);
899 rc
= write(fd
, f
->buf
+ f
->buf_index
, MIN(pending
, size
));