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"
33 #include "qapi/error.h"
35 #define IO_BUF_SIZE 32768
36 #define MAX_IOV_SIZE MIN_CONST(IOV_MAX, 64)
39 const QEMUFileHooks
*hooks
;
44 * Maximum amount of data in bytes to transfer during one
45 * rate limiting time window
47 uint64_t rate_limit_max
;
49 * Total amount of data in bytes queued for transfer
50 * during this rate limiting time window
52 uint64_t rate_limit_used
;
54 /* The sum of bytes transferred on the wire */
55 uint64_t total_transferred
;
58 int buf_size
; /* 0 when writing */
59 uint8_t buf
[IO_BUF_SIZE
];
61 DECLARE_BITMAP(may_free
, MAX_IOV_SIZE
);
62 struct iovec iov
[MAX_IOV_SIZE
];
66 Error
*last_error_obj
;
70 * Stop a file from being read/written - not all backing files can do this
71 * typically only sockets can.
73 * TODO: convert to propagate Error objects instead of squashing
74 * to a fixed errno value
76 int qemu_file_shutdown(QEMUFile
*f
)
81 * We must set qemufile error before the real shutdown(), otherwise
82 * there can be a race window where we thought IO all went though
83 * (because last_error==NULL) but actually IO has already stopped.
85 * If without correct ordering, the race can happen like this:
87 * page receiver other thread
88 * ------------- ------------
91 * returns 0 (buffer all zero)
92 * (we didn't check this retcode)
93 * try to detect IO error
94 * last_error==NULL, IO okay
95 * install ALL-ZERO page
100 qemu_file_set_error(f
, -EIO
);
103 if (!qio_channel_has_feature(f
->ioc
,
104 QIO_CHANNEL_FEATURE_SHUTDOWN
)) {
108 if (qio_channel_shutdown(f
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
) < 0) {
115 bool qemu_file_mode_is_not_valid(const char *mode
)
118 (mode
[0] != 'r' && mode
[0] != 'w') ||
119 mode
[1] != 'b' || mode
[2] != 0) {
120 fprintf(stderr
, "qemu_fopen: Argument validity check failed\n");
127 static QEMUFile
*qemu_file_new_impl(QIOChannel
*ioc
, bool is_writable
)
131 f
= g_new0(QEMUFile
, 1);
135 f
->is_writable
= is_writable
;
141 * Result: QEMUFile* for a 'return path' for comms in the opposite direction
142 * NULL if not available
144 QEMUFile
*qemu_file_get_return_path(QEMUFile
*f
)
146 return qemu_file_new_impl(f
->ioc
, !f
->is_writable
);
149 QEMUFile
*qemu_file_new_output(QIOChannel
*ioc
)
151 return qemu_file_new_impl(ioc
, true);
154 QEMUFile
*qemu_file_new_input(QIOChannel
*ioc
)
156 return qemu_file_new_impl(ioc
, false);
159 void qemu_file_set_hooks(QEMUFile
*f
, const QEMUFileHooks
*hooks
)
165 * Get last error for stream f with optional Error*
167 * Return negative error value if there has been an error on previous
168 * operations, return 0 if no error happened.
169 * Optional, it returns Error* in errp, but it may be NULL even if return value
173 int qemu_file_get_error_obj(QEMUFile
*f
, Error
**errp
)
176 *errp
= f
->last_error_obj
? error_copy(f
->last_error_obj
) : NULL
;
178 return f
->last_error
;
182 * Get last error for either stream f1 or f2 with optional Error*.
183 * The error returned (non-zero) can be either from f1 or f2.
185 * If any of the qemufile* is NULL, then skip the check on that file.
187 * When there is no error on both qemufile, zero is returned.
189 int qemu_file_get_error_obj_any(QEMUFile
*f1
, QEMUFile
*f2
, Error
**errp
)
194 ret
= qemu_file_get_error_obj(f1
, errp
);
195 /* If there's already error detected, return */
202 ret
= qemu_file_get_error_obj(f2
, errp
);
209 * Set the last error for stream f with optional Error*
211 void qemu_file_set_error_obj(QEMUFile
*f
, int ret
, Error
*err
)
213 if (f
->last_error
== 0 && ret
) {
215 error_propagate(&f
->last_error_obj
, err
);
217 error_report_err(err
);
222 * Get last error for stream f
224 * Return negative error value if there has been an error on previous
225 * operations, return 0 if no error happened.
228 int qemu_file_get_error(QEMUFile
*f
)
230 return qemu_file_get_error_obj(f
, NULL
);
234 * Set the last error for stream f
236 void qemu_file_set_error(QEMUFile
*f
, int ret
)
238 qemu_file_set_error_obj(f
, ret
, NULL
);
241 bool qemu_file_is_writable(QEMUFile
*f
)
243 return f
->is_writable
;
246 static void qemu_iovec_release_ram(QEMUFile
*f
)
251 /* Find and release all the contiguous memory ranges marked as may_free. */
252 idx
= find_next_bit(f
->may_free
, f
->iovcnt
, 0);
253 if (idx
>= f
->iovcnt
) {
258 /* The madvise() in the loop is called for iov within a continuous range and
259 * then reinitialize the iov. And in the end, madvise() is called for the
262 while ((idx
= find_next_bit(f
->may_free
, f
->iovcnt
, idx
+ 1)) < f
->iovcnt
) {
263 /* check for adjacent buffer and coalesce them */
264 if (iov
.iov_base
+ iov
.iov_len
== f
->iov
[idx
].iov_base
) {
265 iov
.iov_len
+= f
->iov
[idx
].iov_len
;
268 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
269 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
270 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
274 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
275 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
276 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
278 memset(f
->may_free
, 0, sizeof(f
->may_free
));
283 * Flushes QEMUFile buffer
285 * This will flush all pending data. If data was only partially flushed, it
286 * will set an error state.
288 void qemu_fflush(QEMUFile
*f
)
290 if (!qemu_file_is_writable(f
)) {
294 if (qemu_file_get_error(f
)) {
298 Error
*local_error
= NULL
;
299 if (qio_channel_writev_all(f
->ioc
,
302 qemu_file_set_error_obj(f
, -EIO
, local_error
);
304 f
->total_transferred
+= iov_size(f
->iov
, f
->iovcnt
);
307 qemu_iovec_release_ram(f
);
314 void ram_control_before_iterate(QEMUFile
*f
, uint64_t flags
)
318 if (f
->hooks
&& f
->hooks
->before_ram_iterate
) {
319 ret
= f
->hooks
->before_ram_iterate(f
, flags
, NULL
);
321 qemu_file_set_error(f
, ret
);
326 void ram_control_after_iterate(QEMUFile
*f
, uint64_t flags
)
330 if (f
->hooks
&& f
->hooks
->after_ram_iterate
) {
331 ret
= f
->hooks
->after_ram_iterate(f
, flags
, NULL
);
333 qemu_file_set_error(f
, ret
);
338 void ram_control_load_hook(QEMUFile
*f
, uint64_t flags
, void *data
)
340 if (f
->hooks
&& f
->hooks
->hook_ram_load
) {
341 int ret
= f
->hooks
->hook_ram_load(f
, flags
, data
);
343 qemu_file_set_error(f
, ret
);
348 size_t ram_control_save_page(QEMUFile
*f
, ram_addr_t block_offset
,
349 ram_addr_t offset
, size_t size
,
350 uint64_t *bytes_sent
)
352 if (f
->hooks
&& f
->hooks
->save_page
) {
353 int ret
= f
->hooks
->save_page(f
, block_offset
,
354 offset
, size
, bytes_sent
);
355 if (ret
!= RAM_SAVE_CONTROL_NOT_SUPP
) {
356 qemu_file_acct_rate_limit(f
, size
);
359 if (ret
!= RAM_SAVE_CONTROL_DELAYED
&&
360 ret
!= RAM_SAVE_CONTROL_NOT_SUPP
) {
361 if (bytes_sent
&& *bytes_sent
> 0) {
362 qemu_file_credit_transfer(f
, *bytes_sent
);
363 } else if (ret
< 0) {
364 qemu_file_set_error(f
, ret
);
371 return RAM_SAVE_CONTROL_NOT_SUPP
;
375 * Attempt to fill the buffer from the underlying file
376 * Returns the number of bytes read, or negative value for an error.
378 * Note that it can return a partially full buffer even in a not error/not EOF
379 * case if the underlying file descriptor gives a short read, and that can
380 * happen even on a blocking fd.
382 static ssize_t coroutine_mixed_fn
qemu_fill_buffer(QEMUFile
*f
)
386 Error
*local_error
= NULL
;
388 assert(!qemu_file_is_writable(f
));
390 pending
= f
->buf_size
- f
->buf_index
;
392 memmove(f
->buf
, f
->buf
+ f
->buf_index
, pending
);
395 f
->buf_size
= pending
;
397 if (qemu_file_get_error(f
)) {
402 len
= qio_channel_read(f
->ioc
,
403 (char *)f
->buf
+ pending
,
404 IO_BUF_SIZE
- pending
,
406 if (len
== QIO_CHANNEL_ERR_BLOCK
) {
407 if (qemu_in_coroutine()) {
408 qio_channel_yield(f
->ioc
, G_IO_IN
);
410 qio_channel_wait(f
->ioc
, G_IO_IN
);
412 } else if (len
< 0) {
415 } while (len
== QIO_CHANNEL_ERR_BLOCK
);
419 f
->total_transferred
+= len
;
420 } else if (len
== 0) {
421 qemu_file_set_error_obj(f
, -EIO
, local_error
);
423 qemu_file_set_error_obj(f
, len
, local_error
);
429 void qemu_file_credit_transfer(QEMUFile
*f
, size_t size
)
431 f
->total_transferred
+= size
;
436 * Returns negative error value if any error happened on previous operations or
437 * while closing the file. Returns 0 or positive number on success.
439 * The meaning of return value on success depends on the specific backend
442 int qemu_fclose(QEMUFile
*f
)
446 ret
= qemu_file_get_error(f
);
448 ret2
= qio_channel_close(f
->ioc
, NULL
);
452 g_clear_pointer(&f
->ioc
, object_unref
);
454 /* If any error was spotted before closing, we should report it
455 * instead of the close() return value.
460 error_free(f
->last_error_obj
);
462 trace_qemu_file_fclose();
467 * Add buf to iovec. Do flush if iovec is full.
470 * 1 iovec is full and flushed
471 * 0 iovec is not flushed
474 static int add_to_iovec(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
477 /* check for adjacent buffer and coalesce them */
478 if (f
->iovcnt
> 0 && buf
== f
->iov
[f
->iovcnt
- 1].iov_base
+
479 f
->iov
[f
->iovcnt
- 1].iov_len
&&
480 may_free
== test_bit(f
->iovcnt
- 1, f
->may_free
))
482 f
->iov
[f
->iovcnt
- 1].iov_len
+= size
;
484 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
485 /* Should only happen if a previous fflush failed */
486 assert(qemu_file_get_error(f
) || !qemu_file_is_writable(f
));
490 set_bit(f
->iovcnt
, f
->may_free
);
492 f
->iov
[f
->iovcnt
].iov_base
= (uint8_t *)buf
;
493 f
->iov
[f
->iovcnt
++].iov_len
= size
;
496 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
504 static void add_buf_to_iovec(QEMUFile
*f
, size_t len
)
506 if (!add_to_iovec(f
, f
->buf
+ f
->buf_index
, len
, false)) {
508 if (f
->buf_index
== IO_BUF_SIZE
) {
514 void qemu_put_buffer_async(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
521 f
->rate_limit_used
+= size
;
522 add_to_iovec(f
, buf
, size
, may_free
);
525 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, size_t size
)
534 l
= IO_BUF_SIZE
- f
->buf_index
;
538 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
539 f
->rate_limit_used
+= l
;
540 add_buf_to_iovec(f
, l
);
541 if (qemu_file_get_error(f
)) {
549 void qemu_put_byte(QEMUFile
*f
, int v
)
555 f
->buf
[f
->buf_index
] = v
;
556 f
->rate_limit_used
++;
557 add_buf_to_iovec(f
, 1);
560 void qemu_file_skip(QEMUFile
*f
, int size
)
562 if (f
->buf_index
+ size
<= f
->buf_size
) {
563 f
->buf_index
+= size
;
568 * Read 'size' bytes from file (at 'offset') without moving the
569 * pointer and set 'buf' to point to that data.
571 * It will return size bytes unless there was an error, in which case it will
572 * return as many as it managed to read (assuming blocking fd's which
573 * all current QEMUFile are)
575 size_t coroutine_mixed_fn
qemu_peek_buffer(QEMUFile
*f
, uint8_t **buf
, size_t size
, size_t offset
)
580 assert(!qemu_file_is_writable(f
));
581 assert(offset
< IO_BUF_SIZE
);
582 assert(size
<= IO_BUF_SIZE
- offset
);
584 /* The 1st byte to read from */
585 index
= f
->buf_index
+ offset
;
586 /* The number of available bytes starting at index */
587 pending
= f
->buf_size
- index
;
590 * qemu_fill_buffer might return just a few bytes, even when there isn't
591 * an error, so loop collecting them until we get enough.
593 while (pending
< size
) {
594 int received
= qemu_fill_buffer(f
);
600 index
= f
->buf_index
+ offset
;
601 pending
= f
->buf_size
- index
;
607 if (size
> pending
) {
611 *buf
= f
->buf
+ index
;
616 * Read 'size' bytes of data from the file into buf.
617 * 'size' can be larger than the internal buffer.
619 * It will return size bytes unless there was an error, in which case it will
620 * return as many as it managed to read (assuming blocking fd's which
621 * all current QEMUFile are)
623 size_t coroutine_mixed_fn
qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, size_t size
)
625 size_t pending
= size
;
628 while (pending
> 0) {
632 res
= qemu_peek_buffer(f
, &src
, MIN(pending
, IO_BUF_SIZE
), 0);
636 memcpy(buf
, src
, res
);
637 qemu_file_skip(f
, res
);
646 * Read 'size' bytes of data from the file.
647 * 'size' can be larger than the internal buffer.
650 * may be held on an internal buffer (in which case *buf is updated
651 * to point to it) that is valid until the next qemu_file operation.
653 * will be copied to the *buf that was passed in.
655 * The code tries to avoid the copy if possible.
657 * It will return size bytes unless there was an error, in which case it will
658 * return as many as it managed to read (assuming blocking fd's which
659 * all current QEMUFile are)
661 * Note: Since **buf may get changed, the caller should take care to
662 * keep a pointer to the original buffer if it needs to deallocate it.
664 size_t coroutine_mixed_fn
qemu_get_buffer_in_place(QEMUFile
*f
, uint8_t **buf
, size_t size
)
666 if (size
< IO_BUF_SIZE
) {
670 res
= qemu_peek_buffer(f
, &src
, size
, 0);
673 qemu_file_skip(f
, res
);
679 return qemu_get_buffer(f
, *buf
, size
);
683 * Peeks a single byte from the buffer; this isn't guaranteed to work if
684 * offset leaves a gap after the previous read/peeked data.
686 int coroutine_mixed_fn
qemu_peek_byte(QEMUFile
*f
, int offset
)
688 int index
= f
->buf_index
+ offset
;
690 assert(!qemu_file_is_writable(f
));
691 assert(offset
< IO_BUF_SIZE
);
693 if (index
>= f
->buf_size
) {
695 index
= f
->buf_index
+ offset
;
696 if (index
>= f
->buf_size
) {
700 return f
->buf
[index
];
703 int coroutine_mixed_fn
qemu_get_byte(QEMUFile
*f
)
707 result
= qemu_peek_byte(f
, 0);
708 qemu_file_skip(f
, 1);
712 uint64_t qemu_file_transferred_fast(QEMUFile
*f
)
714 uint64_t ret
= f
->total_transferred
;
717 for (i
= 0; i
< f
->iovcnt
; i
++) {
718 ret
+= f
->iov
[i
].iov_len
;
724 uint64_t qemu_file_transferred(QEMUFile
*f
)
727 return f
->total_transferred
;
730 int qemu_file_rate_limit(QEMUFile
*f
)
732 if (qemu_file_get_error(f
)) {
735 if (f
->rate_limit_max
> 0 && f
->rate_limit_used
> f
->rate_limit_max
) {
741 uint64_t qemu_file_get_rate_limit(QEMUFile
*f
)
743 return f
->rate_limit_max
;
746 void qemu_file_set_rate_limit(QEMUFile
*f
, uint64_t limit
)
749 * 'limit' is per second. But we check it each 100 miliseconds.
751 f
->rate_limit_max
= limit
/ XFER_LIMIT_RATIO
;
754 void qemu_file_reset_rate_limit(QEMUFile
*f
)
756 f
->rate_limit_used
= 0;
759 void qemu_file_acct_rate_limit(QEMUFile
*f
, uint64_t len
)
761 f
->rate_limit_used
+= len
;
764 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
766 qemu_put_byte(f
, v
>> 8);
770 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
772 qemu_put_byte(f
, v
>> 24);
773 qemu_put_byte(f
, v
>> 16);
774 qemu_put_byte(f
, v
>> 8);
778 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
780 qemu_put_be32(f
, v
>> 32);
784 unsigned int qemu_get_be16(QEMUFile
*f
)
787 v
= qemu_get_byte(f
) << 8;
788 v
|= qemu_get_byte(f
);
792 unsigned int qemu_get_be32(QEMUFile
*f
)
795 v
= (unsigned int)qemu_get_byte(f
) << 24;
796 v
|= qemu_get_byte(f
) << 16;
797 v
|= qemu_get_byte(f
) << 8;
798 v
|= qemu_get_byte(f
);
802 uint64_t qemu_get_be64(QEMUFile
*f
)
805 v
= (uint64_t)qemu_get_be32(f
) << 32;
806 v
|= qemu_get_be32(f
);
810 /* return the size after compression, or negative value on error */
811 static int qemu_compress_data(z_stream
*stream
, uint8_t *dest
, size_t dest_len
,
812 const uint8_t *source
, size_t source_len
)
816 err
= deflateReset(stream
);
821 stream
->avail_in
= source_len
;
822 stream
->next_in
= (uint8_t *)source
;
823 stream
->avail_out
= dest_len
;
824 stream
->next_out
= dest
;
826 err
= deflate(stream
, Z_FINISH
);
827 if (err
!= Z_STREAM_END
) {
831 return stream
->next_out
- dest
;
834 /* Compress size bytes of data start at p and store the compressed
835 * data to the buffer of f.
837 * Since the file is dummy file with empty_ops, return -1 if f has no space to
838 * save the compressed data.
840 ssize_t
qemu_put_compression_data(QEMUFile
*f
, z_stream
*stream
,
841 const uint8_t *p
, size_t size
)
843 ssize_t blen
= IO_BUF_SIZE
- f
->buf_index
- sizeof(int32_t);
845 if (blen
< compressBound(size
)) {
849 blen
= qemu_compress_data(stream
, f
->buf
+ f
->buf_index
+ sizeof(int32_t),
855 qemu_put_be32(f
, blen
);
856 add_buf_to_iovec(f
, blen
);
857 return blen
+ sizeof(int32_t);
860 /* Put the data in the buffer of f_src to the buffer of f_des, and
861 * then reset the buf_index of f_src to 0.
864 int qemu_put_qemu_file(QEMUFile
*f_des
, QEMUFile
*f_src
)
868 if (f_src
->buf_index
> 0) {
869 len
= f_src
->buf_index
;
870 qemu_put_buffer(f_des
, f_src
->buf
, f_src
->buf_index
);
871 f_src
->buf_index
= 0;
878 * Check if the writable buffer is empty
881 bool qemu_file_buffer_empty(QEMUFile
*file
)
883 assert(qemu_file_is_writable(file
));
885 return !file
->iovcnt
;
889 * Get a string whose length is determined by a single preceding byte
890 * A preallocated 256 byte buffer must be passed in.
891 * Returns: len on success and a 0 terminated string in the buffer
893 * (Note a 0 length string will return 0 either way)
895 size_t coroutine_fn
qemu_get_counted_string(QEMUFile
*f
, char buf
[256])
897 size_t len
= qemu_get_byte(f
);
898 size_t res
= qemu_get_buffer(f
, (uint8_t *)buf
, len
);
902 return res
== len
? res
: 0;
906 * Put a string with one preceding byte containing its length. The length of
907 * the string should be less than 256.
909 void qemu_put_counted_string(QEMUFile
*f
, const char *str
)
911 size_t len
= strlen(str
);
914 qemu_put_byte(f
, len
);
915 qemu_put_buffer(f
, (const uint8_t *)str
, len
);
919 * Set the blocking state of the QEMUFile.
920 * Note: On some transports the OS only keeps a single blocking state for
921 * both directions, and thus changing the blocking on the main
922 * QEMUFile can also affect the return path.
924 void qemu_file_set_blocking(QEMUFile
*f
, bool block
)
926 qio_channel_set_blocking(f
->ioc
, block
, NULL
);
932 * Get the ioc object for the file, without incrementing
933 * the reference count.
935 * Returns: the ioc object
937 QIOChannel
*qemu_file_get_ioc(QEMUFile
*file
)
943 * Read size bytes from QEMUFile f and write them to fd.
945 int qemu_file_get_to_fd(QEMUFile
*f
, int fd
, size_t size
)
948 size_t pending
= f
->buf_size
- f
->buf_index
;
952 rc
= qemu_fill_buffer(f
);
962 rc
= write(fd
, f
->buf
+ f
->buf_index
, MIN(pending
, size
));