qemu-coroutine-io.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Coroutine-aware I/O functions
  3. *
  4. * Copyright (C) 2009-2010 Nippon Telegraph and Telephone Corporation.
  5. * Copyright (c) 2011, Red Hat, Inc.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  20. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. */
  25. #include "qemu-common.h"
  26. #include "qemu/sockets.h"
  27. #include "block/coroutine.h"
  28. #include "qemu/iov.h"
  29. ssize_t coroutine_fn
  30. qemu_co_sendv_recvv(int sockfd, struct iovec *iov, unsigned iov_cnt,
  31. size_t offset, size_t bytes, bool do_send)
  32. {
  33. size_t done = 0;
  34. ssize_t ret;
  35. while (done < bytes) {
  36. ret = iov_send_recv(sockfd, iov, iov_cnt,
  37. offset + done, bytes - done, do_send);
  38. if (ret > 0) {
  39. done += ret;
  40. } else if (ret < 0) {
  41. if (errno == EAGAIN) {
  42. qemu_coroutine_yield();
  43. } else if (done == 0) {
  44. return -1;
  45. } else {
  46. break;
  47. }
  48. } else if (ret == 0 && !do_send) {
  49. /* write (send) should never return 0.
  50. * read (recv) returns 0 for end-of-file (-data).
  51. * In both cases there's little point retrying,
  52. * but we do for write anyway, just in case */
  53. break;
  54. }
  55. }
  56. return done;
  57. }
  58. ssize_t coroutine_fn
  59. qemu_co_send_recv(int sockfd, void *buf, size_t bytes, bool do_send)
  60. {
  61. struct iovec iov = { .iov_base = buf, .iov_len = bytes };
  62. return qemu_co_sendv_recvv(sockfd, &iov, 1, 0, bytes, do_send);
  63. }