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 #include "io/channel-file.h"
38 #define IO_BUF_SIZE 32768
39 #define MAX_IOV_SIZE MIN_CONST(IOV_MAX, 64)
46 int buf_size
; /* 0 when writing */
47 uint8_t buf
[IO_BUF_SIZE
];
49 DECLARE_BITMAP(may_free
, MAX_IOV_SIZE
);
50 struct iovec iov
[MAX_IOV_SIZE
];
54 Error
*last_error_obj
;
58 * Stop a file from being read/written - not all backing files can do this
59 * typically only sockets can.
61 * TODO: convert to propagate Error objects instead of squashing
62 * to a fixed errno value
64 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
, &err
) < 0) {
97 error_report_err(err
);
104 static QEMUFile
*qemu_file_new_impl(QIOChannel
*ioc
, bool is_writable
)
108 f
= g_new0(QEMUFile
, 1);
112 f
->is_writable
= is_writable
;
118 * Result: QEMUFile* for a 'return path' for comms in the opposite direction
119 * NULL if not available
121 QEMUFile
*qemu_file_get_return_path(QEMUFile
*f
)
123 return qemu_file_new_impl(f
->ioc
, !f
->is_writable
);
126 QEMUFile
*qemu_file_new_output(QIOChannel
*ioc
)
128 return qemu_file_new_impl(ioc
, true);
131 QEMUFile
*qemu_file_new_input(QIOChannel
*ioc
)
133 return qemu_file_new_impl(ioc
, false);
137 * Get last error for stream f with optional Error*
139 * Return negative error value if there has been an error on previous
140 * operations, return 0 if no error happened.
142 * If errp is specified, a verbose error message will be copied over.
144 int qemu_file_get_error_obj(QEMUFile
*f
, Error
**errp
)
146 if (!f
->last_error
) {
150 /* There is an error */
152 if (f
->last_error_obj
) {
153 *errp
= error_copy(f
->last_error_obj
);
155 error_setg_errno(errp
, -f
->last_error
, "Channel error");
159 return f
->last_error
;
163 * Get last error for either stream f1 or f2 with optional Error*.
164 * The error returned (non-zero) can be either from f1 or f2.
166 * If any of the qemufile* is NULL, then skip the check on that file.
168 * When there is no error on both qemufile, zero is returned.
170 int qemu_file_get_error_obj_any(QEMUFile
*f1
, QEMUFile
*f2
, Error
**errp
)
175 ret
= qemu_file_get_error_obj(f1
, errp
);
176 /* If there's already error detected, return */
183 ret
= qemu_file_get_error_obj(f2
, errp
);
190 * Set the last error for stream f with optional Error*
192 void qemu_file_set_error_obj(QEMUFile
*f
, int ret
, Error
*err
)
194 if (f
->last_error
== 0 && ret
) {
196 error_propagate(&f
->last_error_obj
, err
);
198 error_report_err(err
);
203 * Get last error for stream f
205 * Return negative error value if there has been an error on previous
206 * operations, return 0 if no error happened.
209 int qemu_file_get_error(QEMUFile
*f
)
211 return f
->last_error
;
215 * Set the last error for stream f
217 void qemu_file_set_error(QEMUFile
*f
, int ret
)
219 qemu_file_set_error_obj(f
, ret
, NULL
);
222 static bool qemu_file_is_writable(QEMUFile
*f
)
224 return f
->is_writable
;
227 static void qemu_iovec_release_ram(QEMUFile
*f
)
232 /* Find and release all the contiguous memory ranges marked as may_free. */
233 idx
= find_next_bit(f
->may_free
, f
->iovcnt
, 0);
234 if (idx
>= f
->iovcnt
) {
239 /* The madvise() in the loop is called for iov within a continuous range and
240 * then reinitialize the iov. And in the end, madvise() is called for the
243 while ((idx
= find_next_bit(f
->may_free
, f
->iovcnt
, idx
+ 1)) < f
->iovcnt
) {
244 /* check for adjacent buffer and coalesce them */
245 if (iov
.iov_base
+ iov
.iov_len
== f
->iov
[idx
].iov_base
) {
246 iov
.iov_len
+= f
->iov
[idx
].iov_len
;
249 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
250 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
251 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
255 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
256 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
257 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
259 memset(f
->may_free
, 0, sizeof(f
->may_free
));
262 bool qemu_file_is_seekable(QEMUFile
*f
)
264 return qio_channel_has_feature(f
->ioc
, QIO_CHANNEL_FEATURE_SEEKABLE
);
268 * Flushes QEMUFile buffer
270 * This will flush all pending data. If data was only partially flushed, it
271 * will set an error state.
273 int qemu_fflush(QEMUFile
*f
)
275 if (!qemu_file_is_writable(f
)) {
276 return f
->last_error
;
280 return f
->last_error
;
283 Error
*local_error
= NULL
;
284 if (qio_channel_writev_all(f
->ioc
,
287 qemu_file_set_error_obj(f
, -EIO
, local_error
);
289 uint64_t size
= iov_size(f
->iov
, f
->iovcnt
);
290 stat64_add(&mig_stats
.qemu_file_transferred
, size
);
293 qemu_iovec_release_ram(f
);
298 return f
->last_error
;
302 * Attempt to fill the buffer from the underlying file
303 * Returns the number of bytes read, or negative value for an error.
305 * Note that it can return a partially full buffer even in a not error/not EOF
306 * case if the underlying file descriptor gives a short read, and that can
307 * happen even on a blocking fd.
309 static ssize_t coroutine_mixed_fn
qemu_fill_buffer(QEMUFile
*f
)
313 Error
*local_error
= NULL
;
315 assert(!qemu_file_is_writable(f
));
317 pending
= f
->buf_size
- f
->buf_index
;
319 memmove(f
->buf
, f
->buf
+ f
->buf_index
, pending
);
322 f
->buf_size
= pending
;
324 if (qemu_file_get_error(f
)) {
329 len
= qio_channel_read(f
->ioc
,
330 (char *)f
->buf
+ pending
,
331 IO_BUF_SIZE
- pending
,
333 if (len
== QIO_CHANNEL_ERR_BLOCK
) {
334 if (qemu_in_coroutine()) {
335 qio_channel_yield(f
->ioc
, G_IO_IN
);
337 qio_channel_wait(f
->ioc
, G_IO_IN
);
339 } else if (len
< 0) {
342 } while (len
== QIO_CHANNEL_ERR_BLOCK
);
346 } else if (len
== 0) {
347 qemu_file_set_error_obj(f
, -EIO
, local_error
);
349 qemu_file_set_error_obj(f
, len
, local_error
);
357 * Returns negative error value if any error happened on previous operations or
358 * while closing the file. Returns 0 or positive number on success.
360 * The meaning of return value on success depends on the specific backend
363 int qemu_fclose(QEMUFile
*f
)
365 int ret
= qemu_fflush(f
);
366 int ret2
= qio_channel_close(f
->ioc
, NULL
);
370 g_clear_pointer(&f
->ioc
, object_unref
);
371 error_free(f
->last_error_obj
);
373 trace_qemu_file_fclose();
378 * Add buf to iovec. Do flush if iovec is full.
381 * 1 iovec is full and flushed
382 * 0 iovec is not flushed
385 static int add_to_iovec(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
388 /* check for adjacent buffer and coalesce them */
389 if (f
->iovcnt
> 0 && buf
== f
->iov
[f
->iovcnt
- 1].iov_base
+
390 f
->iov
[f
->iovcnt
- 1].iov_len
&&
391 may_free
== test_bit(f
->iovcnt
- 1, f
->may_free
))
393 f
->iov
[f
->iovcnt
- 1].iov_len
+= size
;
395 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
396 /* Should only happen if a previous fflush failed */
397 assert(qemu_file_get_error(f
) || !qemu_file_is_writable(f
));
401 set_bit(f
->iovcnt
, f
->may_free
);
403 f
->iov
[f
->iovcnt
].iov_base
= (uint8_t *)buf
;
404 f
->iov
[f
->iovcnt
++].iov_len
= size
;
407 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
415 static void add_buf_to_iovec(QEMUFile
*f
, size_t len
)
417 if (!add_to_iovec(f
, f
->buf
+ f
->buf_index
, len
, false)) {
419 if (f
->buf_index
== IO_BUF_SIZE
) {
425 void qemu_put_buffer_async(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
432 add_to_iovec(f
, buf
, size
, may_free
);
435 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, size_t size
)
444 l
= IO_BUF_SIZE
- f
->buf_index
;
448 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
449 add_buf_to_iovec(f
, l
);
450 if (qemu_file_get_error(f
)) {
458 void qemu_put_buffer_at(QEMUFile
*f
, const uint8_t *buf
, size_t buflen
,
469 ret
= qio_channel_pwrite(f
->ioc
, (char *)buf
, buflen
, pos
, &err
);
472 qemu_file_set_error_obj(f
, -EIO
, err
);
476 if ((ssize_t
)ret
== QIO_CHANNEL_ERR_BLOCK
) {
477 qemu_file_set_error_obj(f
, -EAGAIN
, NULL
);
482 error_setg(&err
, "Partial write of size %zu, expected %zu", ret
,
484 qemu_file_set_error_obj(f
, -EIO
, err
);
488 stat64_add(&mig_stats
.qemu_file_transferred
, buflen
);
494 size_t qemu_get_buffer_at(QEMUFile
*f
, const uint8_t *buf
, size_t buflen
,
504 ret
= qio_channel_pread(f
->ioc
, (char *)buf
, buflen
, pos
, &err
);
506 if ((ssize_t
)ret
== -1 || err
) {
507 qemu_file_set_error_obj(f
, -EIO
, err
);
511 if ((ssize_t
)ret
== QIO_CHANNEL_ERR_BLOCK
) {
512 qemu_file_set_error_obj(f
, -EAGAIN
, NULL
);
517 error_setg(&err
, "Partial read of size %zu, expected %zu", ret
, buflen
);
518 qemu_file_set_error_obj(f
, -EIO
, err
);
525 void qemu_set_offset(QEMUFile
*f
, off_t off
, int whence
)
530 if (qemu_file_is_writable(f
)) {
533 /* Drop all cached buffers if existed; will trigger a re-fill later */
538 ret
= qio_channel_io_seek(f
->ioc
, off
, whence
, &err
);
539 if (ret
== (off_t
)-1) {
540 qemu_file_set_error_obj(f
, -EIO
, err
);
544 off_t
qemu_get_offset(QEMUFile
*f
)
551 ret
= qio_channel_io_seek(f
->ioc
, 0, SEEK_CUR
, &err
);
552 if (ret
== (off_t
)-1) {
553 qemu_file_set_error_obj(f
, -EIO
, err
);
559 void qemu_put_byte(QEMUFile
*f
, int v
)
565 f
->buf
[f
->buf_index
] = v
;
566 add_buf_to_iovec(f
, 1);
569 void qemu_file_skip(QEMUFile
*f
, int size
)
571 if (f
->buf_index
+ size
<= f
->buf_size
) {
572 f
->buf_index
+= size
;
577 * Read 'size' bytes from file (at 'offset') without moving the
578 * pointer and set 'buf' to point to that data.
580 * It will return size bytes unless there was an error, in which case it will
581 * return as many as it managed to read (assuming blocking fd's which
582 * all current QEMUFile are)
584 size_t coroutine_mixed_fn
qemu_peek_buffer(QEMUFile
*f
, uint8_t **buf
, size_t size
, size_t offset
)
589 assert(!qemu_file_is_writable(f
));
590 assert(offset
< IO_BUF_SIZE
);
591 assert(size
<= IO_BUF_SIZE
- offset
);
593 /* The 1st byte to read from */
594 index
= f
->buf_index
+ offset
;
595 /* The number of available bytes starting at index */
596 pending
= f
->buf_size
- index
;
599 * qemu_fill_buffer might return just a few bytes, even when there isn't
600 * an error, so loop collecting them until we get enough.
602 while (pending
< size
) {
603 int received
= qemu_fill_buffer(f
);
609 index
= f
->buf_index
+ offset
;
610 pending
= f
->buf_size
- index
;
616 if (size
> pending
) {
620 *buf
= f
->buf
+ index
;
625 * Read 'size' bytes of data from the file into buf.
626 * 'size' can be larger than the internal buffer.
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 size_t coroutine_mixed_fn
qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, size_t size
)
634 size_t pending
= size
;
637 while (pending
> 0) {
641 res
= qemu_peek_buffer(f
, &src
, MIN(pending
, IO_BUF_SIZE
), 0);
645 memcpy(buf
, src
, res
);
646 qemu_file_skip(f
, res
);
655 * Read 'size' bytes of data from the file.
656 * 'size' can be larger than the internal buffer.
659 * may be held on an internal buffer (in which case *buf is updated
660 * to point to it) that is valid until the next qemu_file operation.
662 * will be copied to the *buf that was passed in.
664 * The code tries to avoid the copy if possible.
666 * It will return size bytes unless there was an error, in which case it will
667 * return as many as it managed to read (assuming blocking fd's which
668 * all current QEMUFile are)
670 * Note: Since **buf may get changed, the caller should take care to
671 * keep a pointer to the original buffer if it needs to deallocate it.
673 size_t coroutine_mixed_fn
qemu_get_buffer_in_place(QEMUFile
*f
, uint8_t **buf
, size_t size
)
675 if (size
< IO_BUF_SIZE
) {
679 res
= qemu_peek_buffer(f
, &src
, size
, 0);
682 qemu_file_skip(f
, res
);
688 return qemu_get_buffer(f
, *buf
, size
);
692 * Peeks a single byte from the buffer; this isn't guaranteed to work if
693 * offset leaves a gap after the previous read/peeked data.
695 int coroutine_mixed_fn
qemu_peek_byte(QEMUFile
*f
, int offset
)
697 int index
= f
->buf_index
+ offset
;
699 assert(!qemu_file_is_writable(f
));
700 assert(offset
< IO_BUF_SIZE
);
702 if (index
>= f
->buf_size
) {
704 index
= f
->buf_index
+ offset
;
705 if (index
>= f
->buf_size
) {
709 return f
->buf
[index
];
712 int coroutine_mixed_fn
qemu_get_byte(QEMUFile
*f
)
716 result
= qemu_peek_byte(f
, 0);
717 qemu_file_skip(f
, 1);
721 uint64_t qemu_file_transferred(QEMUFile
*f
)
723 uint64_t ret
= stat64_get(&mig_stats
.qemu_file_transferred
);
726 g_assert(qemu_file_is_writable(f
));
728 for (i
= 0; i
< f
->iovcnt
; i
++) {
729 ret
+= f
->iov
[i
].iov_len
;
735 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
737 qemu_put_byte(f
, v
>> 8);
741 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
743 qemu_put_byte(f
, v
>> 24);
744 qemu_put_byte(f
, v
>> 16);
745 qemu_put_byte(f
, v
>> 8);
749 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
751 qemu_put_be32(f
, v
>> 32);
755 unsigned int qemu_get_be16(QEMUFile
*f
)
758 v
= qemu_get_byte(f
) << 8;
759 v
|= qemu_get_byte(f
);
763 unsigned int qemu_get_be32(QEMUFile
*f
)
766 v
= (unsigned int)qemu_get_byte(f
) << 24;
767 v
|= qemu_get_byte(f
) << 16;
768 v
|= qemu_get_byte(f
) << 8;
769 v
|= qemu_get_byte(f
);
773 uint64_t qemu_get_be64(QEMUFile
*f
)
776 v
= (uint64_t)qemu_get_be32(f
) << 32;
777 v
|= qemu_get_be32(f
);
781 /* return the size after compression, or negative value on error */
782 static int qemu_compress_data(z_stream
*stream
, uint8_t *dest
, size_t dest_len
,
783 const uint8_t *source
, size_t source_len
)
787 err
= deflateReset(stream
);
792 stream
->avail_in
= source_len
;
793 stream
->next_in
= (uint8_t *)source
;
794 stream
->avail_out
= dest_len
;
795 stream
->next_out
= dest
;
797 err
= deflate(stream
, Z_FINISH
);
798 if (err
!= Z_STREAM_END
) {
802 return stream
->next_out
- dest
;
805 /* Compress size bytes of data start at p and store the compressed
806 * data to the buffer of f.
808 * Since the file is dummy file with empty_ops, return -1 if f has no space to
809 * save the compressed data.
811 ssize_t
qemu_put_compression_data(QEMUFile
*f
, z_stream
*stream
,
812 const uint8_t *p
, size_t size
)
814 ssize_t blen
= IO_BUF_SIZE
- f
->buf_index
- sizeof(int32_t);
816 if (blen
< compressBound(size
)) {
820 blen
= qemu_compress_data(stream
, f
->buf
+ f
->buf_index
+ sizeof(int32_t),
826 qemu_put_be32(f
, blen
);
827 add_buf_to_iovec(f
, blen
);
828 return blen
+ sizeof(int32_t);
831 /* Put the data in the buffer of f_src to the buffer of f_des, and
832 * then reset the buf_index of f_src to 0.
835 int qemu_put_qemu_file(QEMUFile
*f_des
, QEMUFile
*f_src
)
839 if (f_src
->buf_index
> 0) {
840 len
= f_src
->buf_index
;
841 qemu_put_buffer(f_des
, f_src
->buf
, f_src
->buf_index
);
842 f_src
->buf_index
= 0;
849 * Check if the writable buffer is empty
852 bool qemu_file_buffer_empty(QEMUFile
*file
)
854 assert(qemu_file_is_writable(file
));
856 return !file
->iovcnt
;
860 * Get a string whose length is determined by a single preceding byte
861 * A preallocated 256 byte buffer must be passed in.
862 * Returns: len on success and a 0 terminated string in the buffer
864 * (Note a 0 length string will return 0 either way)
866 size_t coroutine_fn
qemu_get_counted_string(QEMUFile
*f
, char buf
[256])
868 size_t len
= qemu_get_byte(f
);
869 size_t res
= qemu_get_buffer(f
, (uint8_t *)buf
, len
);
873 return res
== len
? res
: 0;
877 * Put a string with one preceding byte containing its length. The length of
878 * the string should be less than 256.
880 void qemu_put_counted_string(QEMUFile
*f
, const char *str
)
882 size_t len
= strlen(str
);
885 qemu_put_byte(f
, len
);
886 qemu_put_buffer(f
, (const uint8_t *)str
, len
);
890 * Set the blocking state of the QEMUFile.
891 * Note: On some transports the OS only keeps a single blocking state for
892 * both directions, and thus changing the blocking on the main
893 * QEMUFile can also affect the return path.
895 void qemu_file_set_blocking(QEMUFile
*f
, bool block
)
897 qio_channel_set_blocking(f
->ioc
, block
, NULL
);
903 * Get the ioc object for the file, without incrementing
904 * the reference count.
906 * Returns: the ioc object
908 QIOChannel
*qemu_file_get_ioc(QEMUFile
*file
)
914 * Read size bytes from QEMUFile f and write them to fd.
916 int qemu_file_get_to_fd(QEMUFile
*f
, int fd
, size_t size
)
919 size_t pending
= f
->buf_size
- f
->buf_index
;
923 rc
= qemu_fill_buffer(f
);
933 rc
= write(fd
, f
->buf
+ f
->buf_index
, MIN(pending
, size
));