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 "qemu-file.h"
32 #include "qapi/error.h"
34 #define IO_BUF_SIZE 32768
35 #define MAX_IOV_SIZE MIN_CONST(IOV_MAX, 64)
38 const QEMUFileHooks
*hooks
;
43 * Maximum amount of data in bytes to transfer during one
44 * rate limiting time window
46 int64_t rate_limit_max
;
48 * Total amount of data in bytes queued for transfer
49 * during this rate limiting time window
51 int64_t rate_limit_used
;
53 /* The sum of bytes transferred on the wire */
54 int64_t total_transferred
;
57 int buf_size
; /* 0 when writing */
58 uint8_t buf
[IO_BUF_SIZE
];
60 DECLARE_BITMAP(may_free
, MAX_IOV_SIZE
);
61 struct iovec iov
[MAX_IOV_SIZE
];
65 Error
*last_error_obj
;
66 /* has the file has been shutdown */
71 * Stop a file from being read/written - not all backing files can do this
72 * typically only sockets can.
74 * TODO: convert to propagate Error objects instead of squashing
75 * to a fixed errno value
77 int qemu_file_shutdown(QEMUFile
*f
)
82 if (!qio_channel_has_feature(f
->ioc
,
83 QIO_CHANNEL_FEATURE_SHUTDOWN
)) {
87 if (qio_channel_shutdown(f
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
) < 0) {
92 qemu_file_set_error(f
, -EIO
);
97 bool qemu_file_mode_is_not_valid(const char *mode
)
100 (mode
[0] != 'r' && mode
[0] != 'w') ||
101 mode
[1] != 'b' || mode
[2] != 0) {
102 fprintf(stderr
, "qemu_fopen: Argument validity check failed\n");
109 static QEMUFile
*qemu_file_new_impl(QIOChannel
*ioc
, bool is_writable
)
113 f
= g_new0(QEMUFile
, 1);
117 f
->is_writable
= is_writable
;
123 * Result: QEMUFile* for a 'return path' for comms in the opposite direction
124 * NULL if not available
126 QEMUFile
*qemu_file_get_return_path(QEMUFile
*f
)
128 return qemu_file_new_impl(f
->ioc
, !f
->is_writable
);
131 QEMUFile
*qemu_file_new_output(QIOChannel
*ioc
)
133 return qemu_file_new_impl(ioc
, true);
136 QEMUFile
*qemu_file_new_input(QIOChannel
*ioc
)
138 return qemu_file_new_impl(ioc
, false);
141 void qemu_file_set_hooks(QEMUFile
*f
, const QEMUFileHooks
*hooks
)
147 * Get last error for stream f with optional Error*
149 * Return negative error value if there has been an error on previous
150 * operations, return 0 if no error happened.
151 * Optional, it returns Error* in errp, but it may be NULL even if return value
155 int qemu_file_get_error_obj(QEMUFile
*f
, Error
**errp
)
158 *errp
= f
->last_error_obj
? error_copy(f
->last_error_obj
) : NULL
;
160 return f
->last_error
;
164 * Get last error for either stream f1 or f2 with optional Error*.
165 * The error returned (non-zero) can be either from f1 or f2.
167 * If any of the qemufile* is NULL, then skip the check on that file.
169 * When there is no error on both qemufile, zero is returned.
171 int qemu_file_get_error_obj_any(QEMUFile
*f1
, QEMUFile
*f2
, Error
**errp
)
176 ret
= qemu_file_get_error_obj(f1
, errp
);
177 /* If there's already error detected, return */
184 ret
= qemu_file_get_error_obj(f2
, errp
);
191 * Set the last error for stream f with optional Error*
193 void qemu_file_set_error_obj(QEMUFile
*f
, int ret
, Error
*err
)
195 if (f
->last_error
== 0 && ret
) {
197 error_propagate(&f
->last_error_obj
, err
);
199 error_report_err(err
);
204 * Get last error for stream f
206 * Return negative error value if there has been an error on previous
207 * operations, return 0 if no error happened.
210 int qemu_file_get_error(QEMUFile
*f
)
212 return qemu_file_get_error_obj(f
, NULL
);
216 * Set the last error for stream f
218 void qemu_file_set_error(QEMUFile
*f
, int ret
)
220 qemu_file_set_error_obj(f
, ret
, NULL
);
223 bool qemu_file_is_writable(QEMUFile
*f
)
225 return f
->is_writable
;
228 static void qemu_iovec_release_ram(QEMUFile
*f
)
233 /* Find and release all the contiguous memory ranges marked as may_free. */
234 idx
= find_next_bit(f
->may_free
, f
->iovcnt
, 0);
235 if (idx
>= f
->iovcnt
) {
240 /* The madvise() in the loop is called for iov within a continuous range and
241 * then reinitialize the iov. And in the end, madvise() is called for the
244 while ((idx
= find_next_bit(f
->may_free
, f
->iovcnt
, idx
+ 1)) < f
->iovcnt
) {
245 /* check for adjacent buffer and coalesce them */
246 if (iov
.iov_base
+ iov
.iov_len
== f
->iov
[idx
].iov_base
) {
247 iov
.iov_len
+= f
->iov
[idx
].iov_len
;
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
));
256 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
257 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
258 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
260 memset(f
->may_free
, 0, sizeof(f
->may_free
));
265 * Flushes QEMUFile buffer
267 * This will flush all pending data. If data was only partially flushed, it
268 * will set an error state.
270 void qemu_fflush(QEMUFile
*f
)
272 if (!qemu_file_is_writable(f
)) {
280 Error
*local_error
= NULL
;
281 if (qio_channel_writev_all(f
->ioc
,
284 qemu_file_set_error_obj(f
, -EIO
, local_error
);
286 f
->total_transferred
+= iov_size(f
->iov
, f
->iovcnt
);
289 qemu_iovec_release_ram(f
);
296 void ram_control_before_iterate(QEMUFile
*f
, uint64_t flags
)
300 if (f
->hooks
&& f
->hooks
->before_ram_iterate
) {
301 ret
= f
->hooks
->before_ram_iterate(f
, flags
, NULL
);
303 qemu_file_set_error(f
, ret
);
308 void ram_control_after_iterate(QEMUFile
*f
, uint64_t flags
)
312 if (f
->hooks
&& f
->hooks
->after_ram_iterate
) {
313 ret
= f
->hooks
->after_ram_iterate(f
, flags
, NULL
);
315 qemu_file_set_error(f
, ret
);
320 void ram_control_load_hook(QEMUFile
*f
, uint64_t flags
, void *data
)
324 if (f
->hooks
&& f
->hooks
->hook_ram_load
) {
325 ret
= f
->hooks
->hook_ram_load(f
, flags
, data
);
327 qemu_file_set_error(f
, ret
);
331 * Hook is a hook specifically requested by the source sending a flag
332 * that expects there to be a hook on the destination.
334 if (flags
== RAM_CONTROL_HOOK
) {
335 qemu_file_set_error(f
, ret
);
340 size_t ram_control_save_page(QEMUFile
*f
, ram_addr_t block_offset
,
341 ram_addr_t offset
, size_t size
,
342 uint64_t *bytes_sent
)
344 if (f
->hooks
&& f
->hooks
->save_page
) {
345 int ret
= f
->hooks
->save_page(f
, block_offset
,
346 offset
, size
, bytes_sent
);
347 if (ret
!= RAM_SAVE_CONTROL_NOT_SUPP
) {
348 f
->rate_limit_used
+= size
;
351 if (ret
!= RAM_SAVE_CONTROL_DELAYED
&&
352 ret
!= RAM_SAVE_CONTROL_NOT_SUPP
) {
353 if (bytes_sent
&& *bytes_sent
> 0) {
354 qemu_file_credit_transfer(f
, *bytes_sent
);
355 } else if (ret
< 0) {
356 qemu_file_set_error(f
, ret
);
363 return RAM_SAVE_CONTROL_NOT_SUPP
;
367 * Attempt to fill the buffer from the underlying file
368 * Returns the number of bytes read, or negative value for an error.
370 * Note that it can return a partially full buffer even in a not error/not EOF
371 * case if the underlying file descriptor gives a short read, and that can
372 * happen even on a blocking fd.
374 static ssize_t
qemu_fill_buffer(QEMUFile
*f
)
378 Error
*local_error
= NULL
;
380 assert(!qemu_file_is_writable(f
));
382 pending
= f
->buf_size
- f
->buf_index
;
384 memmove(f
->buf
, f
->buf
+ f
->buf_index
, pending
);
387 f
->buf_size
= pending
;
394 len
= qio_channel_read(f
->ioc
,
395 (char *)f
->buf
+ pending
,
396 IO_BUF_SIZE
- pending
,
398 if (len
== QIO_CHANNEL_ERR_BLOCK
) {
399 if (qemu_in_coroutine()) {
400 qio_channel_yield(f
->ioc
, G_IO_IN
);
402 qio_channel_wait(f
->ioc
, G_IO_IN
);
404 } else if (len
< 0) {
407 } while (len
== QIO_CHANNEL_ERR_BLOCK
);
411 f
->total_transferred
+= len
;
412 } else if (len
== 0) {
413 qemu_file_set_error_obj(f
, -EIO
, local_error
);
415 qemu_file_set_error_obj(f
, len
, local_error
);
421 void qemu_file_credit_transfer(QEMUFile
*f
, size_t size
)
423 f
->total_transferred
+= size
;
428 * Returns negative error value if any error happened on previous operations or
429 * while closing the file. Returns 0 or positive number on success.
431 * The meaning of return value on success depends on the specific backend
434 int qemu_fclose(QEMUFile
*f
)
438 ret
= qemu_file_get_error(f
);
440 ret2
= qio_channel_close(f
->ioc
, NULL
);
444 g_clear_pointer(&f
->ioc
, object_unref
);
446 /* If any error was spotted before closing, we should report it
447 * instead of the close() return value.
452 error_free(f
->last_error_obj
);
454 trace_qemu_file_fclose();
459 * Add buf to iovec. Do flush if iovec is full.
462 * 1 iovec is full and flushed
463 * 0 iovec is not flushed
466 static int add_to_iovec(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
469 /* check for adjacent buffer and coalesce them */
470 if (f
->iovcnt
> 0 && buf
== f
->iov
[f
->iovcnt
- 1].iov_base
+
471 f
->iov
[f
->iovcnt
- 1].iov_len
&&
472 may_free
== test_bit(f
->iovcnt
- 1, f
->may_free
))
474 f
->iov
[f
->iovcnt
- 1].iov_len
+= size
;
476 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
477 /* Should only happen if a previous fflush failed */
478 assert(f
->shutdown
|| !qemu_file_is_writable(f
));
482 set_bit(f
->iovcnt
, f
->may_free
);
484 f
->iov
[f
->iovcnt
].iov_base
= (uint8_t *)buf
;
485 f
->iov
[f
->iovcnt
++].iov_len
= size
;
488 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
496 static void add_buf_to_iovec(QEMUFile
*f
, size_t len
)
498 if (!add_to_iovec(f
, f
->buf
+ f
->buf_index
, len
, false)) {
500 if (f
->buf_index
== IO_BUF_SIZE
) {
506 void qemu_put_buffer_async(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
513 f
->rate_limit_used
+= size
;
514 add_to_iovec(f
, buf
, size
, may_free
);
517 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, size_t size
)
526 l
= IO_BUF_SIZE
- f
->buf_index
;
530 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
531 f
->rate_limit_used
+= l
;
532 add_buf_to_iovec(f
, l
);
533 if (qemu_file_get_error(f
)) {
541 void qemu_put_byte(QEMUFile
*f
, int v
)
547 f
->buf
[f
->buf_index
] = v
;
548 f
->rate_limit_used
++;
549 add_buf_to_iovec(f
, 1);
552 void qemu_file_skip(QEMUFile
*f
, int size
)
554 if (f
->buf_index
+ size
<= f
->buf_size
) {
555 f
->buf_index
+= size
;
560 * Read 'size' bytes from file (at 'offset') without moving the
561 * pointer and set 'buf' to point to that data.
563 * It will return size bytes unless there was an error, in which case it will
564 * return as many as it managed to read (assuming blocking fd's which
565 * all current QEMUFile are)
567 size_t qemu_peek_buffer(QEMUFile
*f
, uint8_t **buf
, size_t size
, size_t offset
)
572 assert(!qemu_file_is_writable(f
));
573 assert(offset
< IO_BUF_SIZE
);
574 assert(size
<= IO_BUF_SIZE
- offset
);
576 /* The 1st byte to read from */
577 index
= f
->buf_index
+ offset
;
578 /* The number of available bytes starting at index */
579 pending
= f
->buf_size
- index
;
582 * qemu_fill_buffer might return just a few bytes, even when there isn't
583 * an error, so loop collecting them until we get enough.
585 while (pending
< size
) {
586 int received
= qemu_fill_buffer(f
);
592 index
= f
->buf_index
+ offset
;
593 pending
= f
->buf_size
- index
;
599 if (size
> pending
) {
603 *buf
= f
->buf
+ index
;
608 * Read 'size' bytes of data from the file into buf.
609 * 'size' can be larger than the internal buffer.
611 * It will return size bytes unless there was an error, in which case it will
612 * return as many as it managed to read (assuming blocking fd's which
613 * all current QEMUFile are)
615 size_t qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, size_t size
)
617 size_t pending
= size
;
620 while (pending
> 0) {
624 res
= qemu_peek_buffer(f
, &src
, MIN(pending
, IO_BUF_SIZE
), 0);
628 memcpy(buf
, src
, res
);
629 qemu_file_skip(f
, res
);
638 * Read 'size' bytes of data from the file.
639 * 'size' can be larger than the internal buffer.
642 * may be held on an internal buffer (in which case *buf is updated
643 * to point to it) that is valid until the next qemu_file operation.
645 * will be copied to the *buf that was passed in.
647 * The code tries to avoid the copy if possible.
649 * It will return size bytes unless there was an error, in which case it will
650 * return as many as it managed to read (assuming blocking fd's which
651 * all current QEMUFile are)
653 * Note: Since **buf may get changed, the caller should take care to
654 * keep a pointer to the original buffer if it needs to deallocate it.
656 size_t qemu_get_buffer_in_place(QEMUFile
*f
, uint8_t **buf
, size_t size
)
658 if (size
< IO_BUF_SIZE
) {
662 res
= qemu_peek_buffer(f
, &src
, size
, 0);
665 qemu_file_skip(f
, res
);
671 return qemu_get_buffer(f
, *buf
, size
);
675 * Peeks a single byte from the buffer; this isn't guaranteed to work if
676 * offset leaves a gap after the previous read/peeked data.
678 int qemu_peek_byte(QEMUFile
*f
, int offset
)
680 int index
= f
->buf_index
+ offset
;
682 assert(!qemu_file_is_writable(f
));
683 assert(offset
< IO_BUF_SIZE
);
685 if (index
>= f
->buf_size
) {
687 index
= f
->buf_index
+ offset
;
688 if (index
>= f
->buf_size
) {
692 return f
->buf
[index
];
695 int qemu_get_byte(QEMUFile
*f
)
699 result
= qemu_peek_byte(f
, 0);
700 qemu_file_skip(f
, 1);
704 int64_t qemu_file_total_transferred_fast(QEMUFile
*f
)
706 int64_t ret
= f
->total_transferred
;
709 for (i
= 0; i
< f
->iovcnt
; i
++) {
710 ret
+= f
->iov
[i
].iov_len
;
716 int64_t qemu_file_total_transferred(QEMUFile
*f
)
719 return f
->total_transferred
;
722 int qemu_file_rate_limit(QEMUFile
*f
)
727 if (qemu_file_get_error(f
)) {
730 if (f
->rate_limit_max
> 0 && f
->rate_limit_used
> f
->rate_limit_max
) {
736 int64_t qemu_file_get_rate_limit(QEMUFile
*f
)
738 return f
->rate_limit_max
;
741 void qemu_file_set_rate_limit(QEMUFile
*f
, int64_t limit
)
743 f
->rate_limit_max
= limit
;
746 void qemu_file_reset_rate_limit(QEMUFile
*f
)
748 f
->rate_limit_used
= 0;
751 void qemu_file_acct_rate_limit(QEMUFile
*f
, int64_t len
)
753 f
->rate_limit_used
+= len
;
756 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
758 qemu_put_byte(f
, v
>> 8);
762 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
764 qemu_put_byte(f
, v
>> 24);
765 qemu_put_byte(f
, v
>> 16);
766 qemu_put_byte(f
, v
>> 8);
770 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
772 qemu_put_be32(f
, v
>> 32);
776 unsigned int qemu_get_be16(QEMUFile
*f
)
779 v
= qemu_get_byte(f
) << 8;
780 v
|= qemu_get_byte(f
);
784 unsigned int qemu_get_be32(QEMUFile
*f
)
787 v
= (unsigned int)qemu_get_byte(f
) << 24;
788 v
|= qemu_get_byte(f
) << 16;
789 v
|= qemu_get_byte(f
) << 8;
790 v
|= qemu_get_byte(f
);
794 uint64_t qemu_get_be64(QEMUFile
*f
)
797 v
= (uint64_t)qemu_get_be32(f
) << 32;
798 v
|= qemu_get_be32(f
);
802 /* return the size after compression, or negative value on error */
803 static int qemu_compress_data(z_stream
*stream
, uint8_t *dest
, size_t dest_len
,
804 const uint8_t *source
, size_t source_len
)
808 err
= deflateReset(stream
);
813 stream
->avail_in
= source_len
;
814 stream
->next_in
= (uint8_t *)source
;
815 stream
->avail_out
= dest_len
;
816 stream
->next_out
= dest
;
818 err
= deflate(stream
, Z_FINISH
);
819 if (err
!= Z_STREAM_END
) {
823 return stream
->next_out
- dest
;
826 /* Compress size bytes of data start at p and store the compressed
827 * data to the buffer of f.
829 * Since the file is dummy file with empty_ops, return -1 if f has no space to
830 * save the compressed data.
832 ssize_t
qemu_put_compression_data(QEMUFile
*f
, z_stream
*stream
,
833 const uint8_t *p
, size_t size
)
835 ssize_t blen
= IO_BUF_SIZE
- f
->buf_index
- sizeof(int32_t);
837 if (blen
< compressBound(size
)) {
841 blen
= qemu_compress_data(stream
, f
->buf
+ f
->buf_index
+ sizeof(int32_t),
847 qemu_put_be32(f
, blen
);
848 add_buf_to_iovec(f
, blen
);
849 return blen
+ sizeof(int32_t);
852 /* Put the data in the buffer of f_src to the buffer of f_des, and
853 * then reset the buf_index of f_src to 0.
856 int qemu_put_qemu_file(QEMUFile
*f_des
, QEMUFile
*f_src
)
860 if (f_src
->buf_index
> 0) {
861 len
= f_src
->buf_index
;
862 qemu_put_buffer(f_des
, f_src
->buf
, f_src
->buf_index
);
863 f_src
->buf_index
= 0;
870 * Get a string whose length is determined by a single preceding byte
871 * A preallocated 256 byte buffer must be passed in.
872 * Returns: len on success and a 0 terminated string in the buffer
874 * (Note a 0 length string will return 0 either way)
876 size_t qemu_get_counted_string(QEMUFile
*f
, char buf
[256])
878 size_t len
= qemu_get_byte(f
);
879 size_t res
= qemu_get_buffer(f
, (uint8_t *)buf
, len
);
883 return res
== len
? res
: 0;
887 * Put a string with one preceding byte containing its length. The length of
888 * the string should be less than 256.
890 void qemu_put_counted_string(QEMUFile
*f
, const char *str
)
892 size_t len
= strlen(str
);
895 qemu_put_byte(f
, len
);
896 qemu_put_buffer(f
, (const uint8_t *)str
, len
);
900 * Set the blocking state of the QEMUFile.
901 * Note: On some transports the OS only keeps a single blocking state for
902 * both directions, and thus changing the blocking on the main
903 * QEMUFile can also affect the return path.
905 void qemu_file_set_blocking(QEMUFile
*f
, bool block
)
907 qio_channel_set_blocking(f
->ioc
, block
, NULL
);
913 * Get the ioc object for the file, without incrementing
914 * the reference count.
916 * Returns: the ioc object
918 QIOChannel
*qemu_file_get_ioc(QEMUFile
*file
)