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 QEMUFileOps *ops;
39 const QEMUFileHooks *hooks;
44 * Maximum amount of data in bytes to transfer during one
45 * rate limiting time window
47 int64_t rate_limit_max;
49 * Total amount of data in bytes queued for transfer
50 * during this rate limiting time window
52 int64_t rate_limit_used;
54 /* The sum of bytes transferred on the wire */
55 int64_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;
67 /* has the file has been shutdown */
72 * Stop a file from being read/written - not all backing files can do this
73 * typically only sockets can.
75 * TODO: convert to propagate Error objects instead of squashing
76 * to a fixed errno value
78 int qemu_file_shutdown(QEMUFile *f)
83 if (!qio_channel_has_feature(f->ioc,
84 QIO_CHANNEL_FEATURE_SHUTDOWN)) {
88 if (qio_channel_shutdown(f->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL) < 0) {
93 qemu_file_set_error(f, -EIO);
99 * Result: QEMUFile* for a 'return path' for comms in the opposite direction
100 * NULL if not available
102 QEMUFile *qemu_file_get_return_path(QEMUFile *f)
104 if (!f->ops->get_return_path) {
107 return f->ops->get_return_path(f->ioc);
110 bool qemu_file_mode_is_not_valid(const char *mode)
113 (mode[0] != 'r' && mode[0] != 'w') ||
114 mode[1] != 'b' || mode[2] != 0) {
115 fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
122 static QEMUFile *qemu_file_new_impl(QIOChannel *ioc,
123 const QEMUFileOps *ops,
128 f = g_new0(QEMUFile, 1);
132 f->is_writable = is_writable;
137 QEMUFile *qemu_file_new_output(QIOChannel *ioc, const QEMUFileOps *ops)
139 return qemu_file_new_impl(ioc, ops, true);
142 QEMUFile *qemu_file_new_input(QIOChannel *ioc, const QEMUFileOps *ops)
144 return qemu_file_new_impl(ioc, ops, false);
148 void qemu_file_set_hooks(QEMUFile *f, const QEMUFileHooks *hooks)
154 * Get last error for stream f with optional Error*
156 * Return negative error value if there has been an error on previous
157 * operations, return 0 if no error happened.
158 * Optional, it returns Error* in errp, but it may be NULL even if return value
162 int qemu_file_get_error_obj(QEMUFile *f, Error **errp)
165 *errp = f->last_error_obj ? error_copy(f->last_error_obj) : NULL;
167 return f->last_error;
171 * Set the last error for stream f with optional Error*
173 void qemu_file_set_error_obj(QEMUFile *f, int ret, Error *err)
175 if (f->last_error == 0 && ret) {
177 error_propagate(&f->last_error_obj, err);
179 error_report_err(err);
184 * Get last error for stream f
186 * Return negative error value if there has been an error on previous
187 * operations, return 0 if no error happened.
190 int qemu_file_get_error(QEMUFile *f)
192 return qemu_file_get_error_obj(f, NULL);
196 * Set the last error for stream f
198 void qemu_file_set_error(QEMUFile *f, int ret)
200 qemu_file_set_error_obj(f, ret, NULL);
203 bool qemu_file_is_writable(QEMUFile *f)
205 return f->is_writable;
208 static void qemu_iovec_release_ram(QEMUFile *f)
213 /* Find and release all the contiguous memory ranges marked as may_free. */
214 idx = find_next_bit(f->may_free, f->iovcnt, 0);
215 if (idx >= f->iovcnt) {
220 /* The madvise() in the loop is called for iov within a continuous range and
221 * then reinitialize the iov. And in the end, madvise() is called for the
224 while ((idx = find_next_bit(f->may_free, f->iovcnt, idx + 1)) < f->iovcnt) {
225 /* check for adjacent buffer and coalesce them */
226 if (iov.iov_base + iov.iov_len == f->iov[idx].iov_base) {
227 iov.iov_len += f->iov[idx].iov_len;
230 if (qemu_madvise(iov.iov_base, iov.iov_len, QEMU_MADV_DONTNEED) < 0) {
231 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
232 iov.iov_base, iov.iov_len, strerror(errno));
236 if (qemu_madvise(iov.iov_base, iov.iov_len, QEMU_MADV_DONTNEED) < 0) {
237 error_report("migrate: madvise DONTNEED failed %p %zd: %s",
238 iov.iov_base, iov.iov_len, strerror(errno));
240 memset(f->may_free, 0, sizeof(f->may_free));
244 * Flushes QEMUFile buffer
246 * This will flush all pending data. If data was only partially flushed, it
247 * will set an error state.
249 void qemu_fflush(QEMUFile *f)
253 Error *local_error = NULL;
255 if (!qemu_file_is_writable(f)) {
263 expect = iov_size(f->iov, f->iovcnt);
264 ret = f->ops->writev_buffer(f->ioc, f->iov, f->iovcnt,
265 f->total_transferred, &local_error);
267 qemu_iovec_release_ram(f);
271 f->total_transferred += ret;
273 /* We expect the QEMUFile write impl to send the full
274 * data set we requested, so sanity check that.
277 qemu_file_set_error_obj(f, ret < 0 ? ret : -EIO, local_error);
283 void ram_control_before_iterate(QEMUFile *f, uint64_t flags)
287 if (f->hooks && f->hooks->before_ram_iterate) {
288 ret = f->hooks->before_ram_iterate(f, flags, NULL);
290 qemu_file_set_error(f, ret);
295 void ram_control_after_iterate(QEMUFile *f, uint64_t flags)
299 if (f->hooks && f->hooks->after_ram_iterate) {
300 ret = f->hooks->after_ram_iterate(f, flags, NULL);
302 qemu_file_set_error(f, ret);
307 void ram_control_load_hook(QEMUFile *f, uint64_t flags, void *data)
311 if (f->hooks && f->hooks->hook_ram_load) {
312 ret = f->hooks->hook_ram_load(f, flags, data);
314 qemu_file_set_error(f, ret);
318 * Hook is a hook specifically requested by the source sending a flag
319 * that expects there to be a hook on the destination.
321 if (flags == RAM_CONTROL_HOOK) {
322 qemu_file_set_error(f, ret);
327 size_t ram_control_save_page(QEMUFile *f, ram_addr_t block_offset,
328 ram_addr_t offset, size_t size,
329 uint64_t *bytes_sent)
331 if (f->hooks && f->hooks->save_page) {
332 int ret = f->hooks->save_page(f, block_offset,
333 offset, size, bytes_sent);
334 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
335 f->rate_limit_used += size;
338 if (ret != RAM_SAVE_CONTROL_DELAYED &&
339 ret != RAM_SAVE_CONTROL_NOT_SUPP) {
340 if (bytes_sent && *bytes_sent > 0) {
341 qemu_file_credit_transfer(f, *bytes_sent);
342 } else if (ret < 0) {
343 qemu_file_set_error(f, ret);
350 return RAM_SAVE_CONTROL_NOT_SUPP;
354 * Attempt to fill the buffer from the underlying file
355 * Returns the number of bytes read, or negative value for an error.
357 * Note that it can return a partially full buffer even in a not error/not EOF
358 * case if the underlying file descriptor gives a short read, and that can
359 * happen even on a blocking fd.
361 static ssize_t qemu_fill_buffer(QEMUFile *f)
365 Error *local_error = NULL;
367 assert(!qemu_file_is_writable(f));
369 pending = f->buf_size - f->buf_index;
371 memmove(f->buf, f->buf + f->buf_index, pending);
374 f->buf_size = pending;
381 len = qio_channel_read(f->ioc,
382 (char *)f->buf + pending,
383 IO_BUF_SIZE - pending,
385 if (len == QIO_CHANNEL_ERR_BLOCK) {
386 if (qemu_in_coroutine()) {
387 qio_channel_yield(f->ioc, G_IO_IN);
389 qio_channel_wait(f->ioc, G_IO_IN);
391 } else if (len < 0) {
394 } while (len == QIO_CHANNEL_ERR_BLOCK);
398 f->total_transferred += len;
399 } else if (len == 0) {
400 qemu_file_set_error_obj(f, -EIO, local_error);
401 } else if (len != -EAGAIN) {
402 qemu_file_set_error_obj(f, len, local_error);
404 error_free(local_error);
410 void qemu_file_credit_transfer(QEMUFile *f, size_t size)
412 f->total_transferred += size;
417 * Returns negative error value if any error happened on previous operations or
418 * while closing the file. Returns 0 or positive number on success.
420 * The meaning of return value on success depends on the specific backend
423 int qemu_fclose(QEMUFile *f)
427 ret = qemu_file_get_error(f);
429 ret2 = qio_channel_close(f->ioc, NULL);
433 g_clear_pointer(&f->ioc, object_unref);
435 /* If any error was spotted before closing, we should report it
436 * instead of the close() return value.
441 error_free(f->last_error_obj);
443 trace_qemu_file_fclose();
448 * Add buf to iovec. Do flush if iovec is full.
451 * 1 iovec is full and flushed
452 * 0 iovec is not flushed
455 static int add_to_iovec(QEMUFile *f, const uint8_t *buf, size_t size,
458 /* check for adjacent buffer and coalesce them */
459 if (f->iovcnt > 0 && buf == f->iov[f->iovcnt - 1].iov_base +
460 f->iov[f->iovcnt - 1].iov_len &&
461 may_free == test_bit(f->iovcnt - 1, f->may_free))
463 f->iov[f->iovcnt - 1].iov_len += size;
465 if (f->iovcnt >= MAX_IOV_SIZE) {
466 /* Should only happen if a previous fflush failed */
467 assert(f->shutdown || !qemu_file_is_writable(f));
471 set_bit(f->iovcnt, f->may_free);
473 f->iov[f->iovcnt].iov_base = (uint8_t *)buf;
474 f->iov[f->iovcnt++].iov_len = size;
477 if (f->iovcnt >= MAX_IOV_SIZE) {
485 static void add_buf_to_iovec(QEMUFile *f, size_t len)
487 if (!add_to_iovec(f, f->buf + f->buf_index, len, false)) {
489 if (f->buf_index == IO_BUF_SIZE) {
495 void qemu_put_buffer_async(QEMUFile *f, const uint8_t *buf, size_t size,
502 f->rate_limit_used += size;
503 add_to_iovec(f, buf, size, may_free);
506 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size)
515 l = IO_BUF_SIZE - f->buf_index;
519 memcpy(f->buf + f->buf_index, buf, l);
520 f->rate_limit_used += l;
521 add_buf_to_iovec(f, l);
522 if (qemu_file_get_error(f)) {
530 void qemu_put_byte(QEMUFile *f, int v)
536 f->buf[f->buf_index] = v;
537 f->rate_limit_used++;
538 add_buf_to_iovec(f, 1);
541 void qemu_file_skip(QEMUFile *f, int size)
543 if (f->buf_index + size <= f->buf_size) {
544 f->buf_index += size;
549 * Read 'size' bytes from file (at 'offset') without moving the
550 * pointer and set 'buf' to point to that data.
552 * It will return size bytes unless there was an error, in which case it will
553 * return as many as it managed to read (assuming blocking fd's which
554 * all current QEMUFile are)
556 size_t qemu_peek_buffer(QEMUFile *f, uint8_t **buf, size_t size, size_t offset)
561 assert(!qemu_file_is_writable(f));
562 assert(offset < IO_BUF_SIZE);
563 assert(size <= IO_BUF_SIZE - offset);
565 /* The 1st byte to read from */
566 index = f->buf_index + offset;
567 /* The number of available bytes starting at index */
568 pending = f->buf_size - index;
571 * qemu_fill_buffer might return just a few bytes, even when there isn't
572 * an error, so loop collecting them until we get enough.
574 while (pending < size) {
575 int received = qemu_fill_buffer(f);
581 index = f->buf_index + offset;
582 pending = f->buf_size - index;
588 if (size > pending) {
592 *buf = f->buf + index;
597 * Read 'size' bytes of data from the file into buf.
598 * 'size' can be larger than the internal buffer.
600 * It will return size bytes unless there was an error, in which case it will
601 * return as many as it managed to read (assuming blocking fd's which
602 * all current QEMUFile are)
604 size_t qemu_get_buffer(QEMUFile *f, uint8_t *buf, size_t size)
606 size_t pending = size;
609 while (pending > 0) {
613 res = qemu_peek_buffer(f, &src, MIN(pending, IO_BUF_SIZE), 0);
617 memcpy(buf, src, res);
618 qemu_file_skip(f, res);
627 * Read 'size' bytes of data from the file.
628 * 'size' can be larger than the internal buffer.
631 * may be held on an internal buffer (in which case *buf is updated
632 * to point to it) that is valid until the next qemu_file operation.
634 * will be copied to the *buf that was passed in.
636 * The code tries to avoid the copy if possible.
638 * It will return size bytes unless there was an error, in which case it will
639 * return as many as it managed to read (assuming blocking fd's which
640 * all current QEMUFile are)
642 * Note: Since **buf may get changed, the caller should take care to
643 * keep a pointer to the original buffer if it needs to deallocate it.
645 size_t qemu_get_buffer_in_place(QEMUFile *f, uint8_t **buf, size_t size)
647 if (size < IO_BUF_SIZE) {
651 res = qemu_peek_buffer(f, &src, size, 0);
654 qemu_file_skip(f, res);
660 return qemu_get_buffer(f, *buf, size);
664 * Peeks a single byte from the buffer; this isn't guaranteed to work if
665 * offset leaves a gap after the previous read/peeked data.
667 int qemu_peek_byte(QEMUFile *f, int offset)
669 int index = f->buf_index + offset;
671 assert(!qemu_file_is_writable(f));
672 assert(offset < IO_BUF_SIZE);
674 if (index >= f->buf_size) {
676 index = f->buf_index + offset;
677 if (index >= f->buf_size) {
681 return f->buf[index];
684 int qemu_get_byte(QEMUFile *f)
688 result = qemu_peek_byte(f, 0);
689 qemu_file_skip(f, 1);
693 int64_t qemu_file_total_transferred_fast(QEMUFile *f)
695 int64_t ret = f->total_transferred;
698 for (i = 0; i < f->iovcnt; i++) {
699 ret += f->iov[i].iov_len;
705 int64_t qemu_file_total_transferred(QEMUFile *f)
708 return f->total_transferred;
711 int qemu_file_rate_limit(QEMUFile *f)
716 if (qemu_file_get_error(f)) {
719 if (f->rate_limit_max > 0 && f->rate_limit_used > f->rate_limit_max) {
725 int64_t qemu_file_get_rate_limit(QEMUFile *f)
727 return f->rate_limit_max;
730 void qemu_file_set_rate_limit(QEMUFile *f, int64_t limit)
732 f->rate_limit_max = limit;
735 void qemu_file_reset_rate_limit(QEMUFile *f)
737 f->rate_limit_used = 0;
740 void qemu_file_acct_rate_limit(QEMUFile *f, int64_t len)
742 f->rate_limit_used += len;
745 void qemu_put_be16(QEMUFile *f, unsigned int v)
747 qemu_put_byte(f, v >> 8);
751 void qemu_put_be32(QEMUFile *f, unsigned int v)
753 qemu_put_byte(f, v >> 24);
754 qemu_put_byte(f, v >> 16);
755 qemu_put_byte(f, v >> 8);
759 void qemu_put_be64(QEMUFile *f, uint64_t v)
761 qemu_put_be32(f, v >> 32);
765 unsigned int qemu_get_be16(QEMUFile *f)
768 v = qemu_get_byte(f) << 8;
769 v |= qemu_get_byte(f);
773 unsigned int qemu_get_be32(QEMUFile *f)
776 v = (unsigned int)qemu_get_byte(f) << 24;
777 v |= qemu_get_byte(f) << 16;
778 v |= qemu_get_byte(f) << 8;
779 v |= qemu_get_byte(f);
783 uint64_t qemu_get_be64(QEMUFile *f)
786 v = (uint64_t)qemu_get_be32(f) << 32;
787 v |= qemu_get_be32(f);
791 /* return the size after compression, or negative value on error */
792 static int qemu_compress_data(z_stream *stream, uint8_t *dest, size_t dest_len,
793 const uint8_t *source, size_t source_len)
797 err = deflateReset(stream);
802 stream->avail_in = source_len;
803 stream->next_in = (uint8_t *)source;
804 stream->avail_out = dest_len;
805 stream->next_out = dest;
807 err = deflate(stream, Z_FINISH);
808 if (err != Z_STREAM_END) {
812 return stream->next_out - dest;
815 /* Compress size bytes of data start at p and store the compressed
816 * data to the buffer of f.
818 * Since the file is dummy file with empty_ops, return -1 if f has no space to
819 * save the compressed data.
821 ssize_t qemu_put_compression_data(QEMUFile *f, z_stream *stream,
822 const uint8_t *p, size_t size)
824 ssize_t blen = IO_BUF_SIZE - f->buf_index - sizeof(int32_t);
826 if (blen < compressBound(size)) {
830 blen = qemu_compress_data(stream, f->buf + f->buf_index + sizeof(int32_t),
836 qemu_put_be32(f, blen);
837 add_buf_to_iovec(f, blen);
838 return blen + sizeof(int32_t);
841 /* Put the data in the buffer of f_src to the buffer of f_des, and
842 * then reset the buf_index of f_src to 0.
845 int qemu_put_qemu_file(QEMUFile *f_des, QEMUFile *f_src)
849 if (f_src->buf_index > 0) {
850 len = f_src->buf_index;
851 qemu_put_buffer(f_des, f_src->buf, f_src->buf_index);
852 f_src->buf_index = 0;
859 * Get a string whose length is determined by a single preceding byte
860 * A preallocated 256 byte buffer must be passed in.
861 * Returns: len on success and a 0 terminated string in the buffer
863 * (Note a 0 length string will return 0 either way)
865 size_t qemu_get_counted_string(QEMUFile *f, char buf[256])
867 size_t len = qemu_get_byte(f);
868 size_t res = qemu_get_buffer(f, (uint8_t *)buf, len);
872 return res == len ? res : 0;
876 * Put a string with one preceding byte containing its length. The length of
877 * the string should be less than 256.
879 void qemu_put_counted_string(QEMUFile *f, const char *str)
881 size_t len = strlen(str);
884 qemu_put_byte(f, len);
885 qemu_put_buffer(f, (const uint8_t *)str, len);
889 * Set the blocking state of the QEMUFile.
890 * Note: On some transports the OS only keeps a single blocking state for
891 * both directions, and thus changing the blocking on the main
892 * QEMUFile can also affect the return path.
894 void qemu_file_set_blocking(QEMUFile *f, bool block)
896 qio_channel_set_blocking(f->ioc, block, NULL);
902 * Get the ioc object for the file, without incrementing
903 * the reference count.
905 * Returns: the ioc object
907 QIOChannel *qemu_file_get_ioc(QEMUFile *file)