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"
37 #define IO_BUF_SIZE 32768
38 #define MAX_IOV_SIZE MIN_CONST(IOV_MAX, 64)
45 int buf_size
; /* 0 when writing */
46 uint8_t buf
[IO_BUF_SIZE
];
48 DECLARE_BITMAP(may_free
, MAX_IOV_SIZE
);
49 struct iovec iov
[MAX_IOV_SIZE
];
53 Error
*last_error_obj
;
57 * Stop a file from being read/written - not all backing files can do this
58 * typically only sockets can.
60 * TODO: convert to propagate Error objects instead of squashing
61 * to a fixed errno value
63 int qemu_file_shutdown(QEMUFile
*f
)
66 * We must set qemufile error before the real shutdown(), otherwise
67 * there can be a race window where we thought IO all went though
68 * (because last_error==NULL) but actually IO has already stopped.
70 * If without correct ordering, the race can happen like this:
72 * page receiver other thread
73 * ------------- ------------
76 * returns 0 (buffer all zero)
77 * (we didn't check this retcode)
78 * try to detect IO error
79 * last_error==NULL, IO okay
80 * install ALL-ZERO page
85 qemu_file_set_error(f
, -EIO
);
88 if (!qio_channel_has_feature(f
->ioc
,
89 QIO_CHANNEL_FEATURE_SHUTDOWN
)) {
93 if (qio_channel_shutdown(f
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
) < 0) {
100 static QEMUFile
*qemu_file_new_impl(QIOChannel
*ioc
, bool is_writable
)
104 f
= g_new0(QEMUFile
, 1);
108 f
->is_writable
= is_writable
;
114 * Result: QEMUFile* for a 'return path' for comms in the opposite direction
115 * NULL if not available
117 QEMUFile
*qemu_file_get_return_path(QEMUFile
*f
)
119 return qemu_file_new_impl(f
->ioc
, !f
->is_writable
);
122 QEMUFile
*qemu_file_new_output(QIOChannel
*ioc
)
124 return qemu_file_new_impl(ioc
, true);
127 QEMUFile
*qemu_file_new_input(QIOChannel
*ioc
)
129 return qemu_file_new_impl(ioc
, false);
133 * Get last error for stream f with optional Error*
135 * Return negative error value if there has been an error on previous
136 * operations, return 0 if no error happened.
138 * If errp is specified, a verbose error message will be copied over.
140 int qemu_file_get_error_obj(QEMUFile
*f
, Error
**errp
)
142 if (!f
->last_error
) {
146 /* There is an error */
148 if (f
->last_error_obj
) {
149 *errp
= error_copy(f
->last_error_obj
);
151 error_setg_errno(errp
, -f
->last_error
, "Channel error");
155 return f
->last_error
;
159 * Get last error for either stream f1 or f2 with optional Error*.
160 * The error returned (non-zero) can be either from f1 or f2.
162 * If any of the qemufile* is NULL, then skip the check on that file.
164 * When there is no error on both qemufile, zero is returned.
166 int qemu_file_get_error_obj_any(QEMUFile
*f1
, QEMUFile
*f2
, Error
**errp
)
171 ret
= qemu_file_get_error_obj(f1
, errp
);
172 /* If there's already error detected, return */
179 ret
= qemu_file_get_error_obj(f2
, errp
);
186 * Set the last error for stream f with optional Error*
188 void qemu_file_set_error_obj(QEMUFile
*f
, int ret
, Error
*err
)
190 if (f
->last_error
== 0 && ret
) {
192 error_propagate(&f
->last_error_obj
, err
);
194 error_report_err(err
);
199 * Get last error for stream f
201 * Return negative error value if there has been an error on previous
202 * operations, return 0 if no error happened.
205 int qemu_file_get_error(QEMUFile
*f
)
207 return f
->last_error
;
211 * Set the last error for stream f
213 void qemu_file_set_error(QEMUFile
*f
, int ret
)
215 qemu_file_set_error_obj(f
, ret
, NULL
);
218 static bool qemu_file_is_writable(QEMUFile
*f
)
220 return f
->is_writable
;
223 static void qemu_iovec_release_ram(QEMUFile
*f
)
228 /* Find and release all the contiguous memory ranges marked as may_free. */
229 idx
= find_next_bit(f
->may_free
, f
->iovcnt
, 0);
230 if (idx
>= f
->iovcnt
) {
235 /* The madvise() in the loop is called for iov within a continuous range and
236 * then reinitialize the iov. And in the end, madvise() is called for the
239 while ((idx
= find_next_bit(f
->may_free
, f
->iovcnt
, idx
+ 1)) < f
->iovcnt
) {
240 /* check for adjacent buffer and coalesce them */
241 if (iov
.iov_base
+ iov
.iov_len
== f
->iov
[idx
].iov_base
) {
242 iov
.iov_len
+= f
->iov
[idx
].iov_len
;
245 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
246 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
247 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
251 if (qemu_madvise(iov
.iov_base
, iov
.iov_len
, QEMU_MADV_DONTNEED
) < 0) {
252 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
253 iov
.iov_base
, iov
.iov_len
, strerror(errno
));
255 memset(f
->may_free
, 0, sizeof(f
->may_free
));
260 * Flushes QEMUFile buffer
262 * This will flush all pending data. If data was only partially flushed, it
263 * will set an error state.
265 int qemu_fflush(QEMUFile
*f
)
267 if (!qemu_file_is_writable(f
)) {
268 return f
->last_error
;
272 return f
->last_error
;
275 Error
*local_error
= NULL
;
276 if (qio_channel_writev_all(f
->ioc
,
279 qemu_file_set_error_obj(f
, -EIO
, local_error
);
281 uint64_t size
= iov_size(f
->iov
, f
->iovcnt
);
282 stat64_add(&mig_stats
.qemu_file_transferred
, size
);
285 qemu_iovec_release_ram(f
);
290 return f
->last_error
;
294 * Attempt to fill the buffer from the underlying file
295 * Returns the number of bytes read, or negative value for an error.
297 * Note that it can return a partially full buffer even in a not error/not EOF
298 * case if the underlying file descriptor gives a short read, and that can
299 * happen even on a blocking fd.
301 static ssize_t coroutine_mixed_fn
qemu_fill_buffer(QEMUFile
*f
)
305 Error
*local_error
= NULL
;
307 assert(!qemu_file_is_writable(f
));
309 pending
= f
->buf_size
- f
->buf_index
;
311 memmove(f
->buf
, f
->buf
+ f
->buf_index
, pending
);
314 f
->buf_size
= pending
;
316 if (qemu_file_get_error(f
)) {
321 len
= qio_channel_read(f
->ioc
,
322 (char *)f
->buf
+ pending
,
323 IO_BUF_SIZE
- pending
,
325 if (len
== QIO_CHANNEL_ERR_BLOCK
) {
326 if (qemu_in_coroutine()) {
327 qio_channel_yield(f
->ioc
, G_IO_IN
);
329 qio_channel_wait(f
->ioc
, G_IO_IN
);
331 } else if (len
< 0) {
334 } while (len
== QIO_CHANNEL_ERR_BLOCK
);
338 } else if (len
== 0) {
339 qemu_file_set_error_obj(f
, -EIO
, local_error
);
341 qemu_file_set_error_obj(f
, len
, local_error
);
349 * Returns negative error value if any error happened on previous operations or
350 * while closing the file. Returns 0 or positive number on success.
352 * The meaning of return value on success depends on the specific backend
355 int qemu_fclose(QEMUFile
*f
)
357 int ret
= qemu_fflush(f
);
358 int ret2
= qio_channel_close(f
->ioc
, NULL
);
362 g_clear_pointer(&f
->ioc
, object_unref
);
363 error_free(f
->last_error_obj
);
365 trace_qemu_file_fclose();
370 * Add buf to iovec. Do flush if iovec is full.
373 * 1 iovec is full and flushed
374 * 0 iovec is not flushed
377 static int add_to_iovec(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
380 /* check for adjacent buffer and coalesce them */
381 if (f
->iovcnt
> 0 && buf
== f
->iov
[f
->iovcnt
- 1].iov_base
+
382 f
->iov
[f
->iovcnt
- 1].iov_len
&&
383 may_free
== test_bit(f
->iovcnt
- 1, f
->may_free
))
385 f
->iov
[f
->iovcnt
- 1].iov_len
+= size
;
387 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
388 /* Should only happen if a previous fflush failed */
389 assert(qemu_file_get_error(f
) || !qemu_file_is_writable(f
));
393 set_bit(f
->iovcnt
, f
->may_free
);
395 f
->iov
[f
->iovcnt
].iov_base
= (uint8_t *)buf
;
396 f
->iov
[f
->iovcnt
++].iov_len
= size
;
399 if (f
->iovcnt
>= MAX_IOV_SIZE
) {
407 static void add_buf_to_iovec(QEMUFile
*f
, size_t len
)
409 if (!add_to_iovec(f
, f
->buf
+ f
->buf_index
, len
, false)) {
411 if (f
->buf_index
== IO_BUF_SIZE
) {
417 void qemu_put_buffer_async(QEMUFile
*f
, const uint8_t *buf
, size_t size
,
424 add_to_iovec(f
, buf
, size
, may_free
);
427 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, size_t size
)
436 l
= IO_BUF_SIZE
- f
->buf_index
;
440 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
441 add_buf_to_iovec(f
, l
);
442 if (qemu_file_get_error(f
)) {
450 void qemu_put_byte(QEMUFile
*f
, int v
)
456 f
->buf
[f
->buf_index
] = v
;
457 add_buf_to_iovec(f
, 1);
460 void qemu_file_skip(QEMUFile
*f
, int size
)
462 if (f
->buf_index
+ size
<= f
->buf_size
) {
463 f
->buf_index
+= size
;
468 * Read 'size' bytes from file (at 'offset') without moving the
469 * pointer and set 'buf' to point to that data.
471 * It will return size bytes unless there was an error, in which case it will
472 * return as many as it managed to read (assuming blocking fd's which
473 * all current QEMUFile are)
475 size_t coroutine_mixed_fn
qemu_peek_buffer(QEMUFile
*f
, uint8_t **buf
, size_t size
, size_t offset
)
480 assert(!qemu_file_is_writable(f
));
481 assert(offset
< IO_BUF_SIZE
);
482 assert(size
<= IO_BUF_SIZE
- offset
);
484 /* The 1st byte to read from */
485 index
= f
->buf_index
+ offset
;
486 /* The number of available bytes starting at index */
487 pending
= f
->buf_size
- index
;
490 * qemu_fill_buffer might return just a few bytes, even when there isn't
491 * an error, so loop collecting them until we get enough.
493 while (pending
< size
) {
494 int received
= qemu_fill_buffer(f
);
500 index
= f
->buf_index
+ offset
;
501 pending
= f
->buf_size
- index
;
507 if (size
> pending
) {
511 *buf
= f
->buf
+ index
;
516 * Read 'size' bytes of data from the file into buf.
517 * 'size' can be larger than the internal buffer.
519 * It will return size bytes unless there was an error, in which case it will
520 * return as many as it managed to read (assuming blocking fd's which
521 * all current QEMUFile are)
523 size_t coroutine_mixed_fn
qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, size_t size
)
525 size_t pending
= size
;
528 while (pending
> 0) {
532 res
= qemu_peek_buffer(f
, &src
, MIN(pending
, IO_BUF_SIZE
), 0);
536 memcpy(buf
, src
, res
);
537 qemu_file_skip(f
, res
);
546 * Read 'size' bytes of data from the file.
547 * 'size' can be larger than the internal buffer.
550 * may be held on an internal buffer (in which case *buf is updated
551 * to point to it) that is valid until the next qemu_file operation.
553 * will be copied to the *buf that was passed in.
555 * The code tries to avoid the copy if possible.
557 * It will return size bytes unless there was an error, in which case it will
558 * return as many as it managed to read (assuming blocking fd's which
559 * all current QEMUFile are)
561 * Note: Since **buf may get changed, the caller should take care to
562 * keep a pointer to the original buffer if it needs to deallocate it.
564 size_t coroutine_mixed_fn
qemu_get_buffer_in_place(QEMUFile
*f
, uint8_t **buf
, size_t size
)
566 if (size
< IO_BUF_SIZE
) {
570 res
= qemu_peek_buffer(f
, &src
, size
, 0);
573 qemu_file_skip(f
, res
);
579 return qemu_get_buffer(f
, *buf
, size
);
583 * Peeks a single byte from the buffer; this isn't guaranteed to work if
584 * offset leaves a gap after the previous read/peeked data.
586 int coroutine_mixed_fn
qemu_peek_byte(QEMUFile
*f
, int offset
)
588 int index
= f
->buf_index
+ offset
;
590 assert(!qemu_file_is_writable(f
));
591 assert(offset
< IO_BUF_SIZE
);
593 if (index
>= f
->buf_size
) {
595 index
= f
->buf_index
+ offset
;
596 if (index
>= f
->buf_size
) {
600 return f
->buf
[index
];
603 int coroutine_mixed_fn
qemu_get_byte(QEMUFile
*f
)
607 result
= qemu_peek_byte(f
, 0);
608 qemu_file_skip(f
, 1);
612 uint64_t qemu_file_transferred(QEMUFile
*f
)
614 uint64_t ret
= stat64_get(&mig_stats
.qemu_file_transferred
);
617 g_assert(qemu_file_is_writable(f
));
619 for (i
= 0; i
< f
->iovcnt
; i
++) {
620 ret
+= f
->iov
[i
].iov_len
;
626 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
628 qemu_put_byte(f
, v
>> 8);
632 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
634 qemu_put_byte(f
, v
>> 24);
635 qemu_put_byte(f
, v
>> 16);
636 qemu_put_byte(f
, v
>> 8);
640 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
642 qemu_put_be32(f
, v
>> 32);
646 unsigned int qemu_get_be16(QEMUFile
*f
)
649 v
= qemu_get_byte(f
) << 8;
650 v
|= qemu_get_byte(f
);
654 unsigned int qemu_get_be32(QEMUFile
*f
)
657 v
= (unsigned int)qemu_get_byte(f
) << 24;
658 v
|= qemu_get_byte(f
) << 16;
659 v
|= qemu_get_byte(f
) << 8;
660 v
|= qemu_get_byte(f
);
664 uint64_t qemu_get_be64(QEMUFile
*f
)
667 v
= (uint64_t)qemu_get_be32(f
) << 32;
668 v
|= qemu_get_be32(f
);
672 /* return the size after compression, or negative value on error */
673 static int qemu_compress_data(z_stream
*stream
, uint8_t *dest
, size_t dest_len
,
674 const uint8_t *source
, size_t source_len
)
678 err
= deflateReset(stream
);
683 stream
->avail_in
= source_len
;
684 stream
->next_in
= (uint8_t *)source
;
685 stream
->avail_out
= dest_len
;
686 stream
->next_out
= dest
;
688 err
= deflate(stream
, Z_FINISH
);
689 if (err
!= Z_STREAM_END
) {
693 return stream
->next_out
- dest
;
696 /* Compress size bytes of data start at p and store the compressed
697 * data to the buffer of f.
699 * Since the file is dummy file with empty_ops, return -1 if f has no space to
700 * save the compressed data.
702 ssize_t
qemu_put_compression_data(QEMUFile
*f
, z_stream
*stream
,
703 const uint8_t *p
, size_t size
)
705 ssize_t blen
= IO_BUF_SIZE
- f
->buf_index
- sizeof(int32_t);
707 if (blen
< compressBound(size
)) {
711 blen
= qemu_compress_data(stream
, f
->buf
+ f
->buf_index
+ sizeof(int32_t),
717 qemu_put_be32(f
, blen
);
718 add_buf_to_iovec(f
, blen
);
719 return blen
+ sizeof(int32_t);
722 /* Put the data in the buffer of f_src to the buffer of f_des, and
723 * then reset the buf_index of f_src to 0.
726 int qemu_put_qemu_file(QEMUFile
*f_des
, QEMUFile
*f_src
)
730 if (f_src
->buf_index
> 0) {
731 len
= f_src
->buf_index
;
732 qemu_put_buffer(f_des
, f_src
->buf
, f_src
->buf_index
);
733 f_src
->buf_index
= 0;
740 * Check if the writable buffer is empty
743 bool qemu_file_buffer_empty(QEMUFile
*file
)
745 assert(qemu_file_is_writable(file
));
747 return !file
->iovcnt
;
751 * Get a string whose length is determined by a single preceding byte
752 * A preallocated 256 byte buffer must be passed in.
753 * Returns: len on success and a 0 terminated string in the buffer
755 * (Note a 0 length string will return 0 either way)
757 size_t coroutine_fn
qemu_get_counted_string(QEMUFile
*f
, char buf
[256])
759 size_t len
= qemu_get_byte(f
);
760 size_t res
= qemu_get_buffer(f
, (uint8_t *)buf
, len
);
764 return res
== len
? res
: 0;
768 * Put a string with one preceding byte containing its length. The length of
769 * the string should be less than 256.
771 void qemu_put_counted_string(QEMUFile
*f
, const char *str
)
773 size_t len
= strlen(str
);
776 qemu_put_byte(f
, len
);
777 qemu_put_buffer(f
, (const uint8_t *)str
, len
);
781 * Set the blocking state of the QEMUFile.
782 * Note: On some transports the OS only keeps a single blocking state for
783 * both directions, and thus changing the blocking on the main
784 * QEMUFile can also affect the return path.
786 void qemu_file_set_blocking(QEMUFile
*f
, bool block
)
788 qio_channel_set_blocking(f
->ioc
, block
, NULL
);
794 * Get the ioc object for the file, without incrementing
795 * the reference count.
797 * Returns: the ioc object
799 QIOChannel
*qemu_file_get_ioc(QEMUFile
*file
)
805 * Read size bytes from QEMUFile f and write them to fd.
807 int qemu_file_get_to_fd(QEMUFile
*f
, int fd
, size_t size
)
810 size_t pending
= f
->buf_size
- f
->buf_index
;
814 rc
= qemu_fill_buffer(f
);
824 rc
= write(fd
, f
->buf
+ f
->buf_index
, MIN(pending
, size
));