event_notifier.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * event notifier support
  3. *
  4. * Copyright Red Hat, Inc. 2010
  5. *
  6. * Authors:
  7. * Michael S. Tsirkin <mst@redhat.com>
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2. See
  10. * the COPYING file in the top-level directory.
  11. */
  12. #include "hw.h"
  13. #include "event_notifier.h"
  14. #ifdef CONFIG_EVENTFD
  15. #include <sys/eventfd.h>
  16. #endif
  17. int event_notifier_init(EventNotifier *e, int active)
  18. {
  19. #ifdef CONFIG_EVENTFD
  20. int fd = eventfd(!!active, EFD_NONBLOCK | EFD_CLOEXEC);
  21. if (fd < 0)
  22. return -errno;
  23. e->fd = fd;
  24. return 0;
  25. #else
  26. return -ENOSYS;
  27. #endif
  28. }
  29. void event_notifier_cleanup(EventNotifier *e)
  30. {
  31. close(e->fd);
  32. }
  33. int event_notifier_get_fd(EventNotifier *e)
  34. {
  35. return e->fd;
  36. }
  37. int event_notifier_test_and_clear(EventNotifier *e)
  38. {
  39. uint64_t value;
  40. int r = read(e->fd, &value, sizeof(value));
  41. return r == sizeof(value);
  42. }
  43. int event_notifier_test(EventNotifier *e)
  44. {
  45. uint64_t value;
  46. int r = read(e->fd, &value, sizeof(value));
  47. if (r == sizeof(value)) {
  48. /* restore previous value. */
  49. int s = write(e->fd, &value, sizeof(value));
  50. /* never blocks because we use EFD_SEMAPHORE.
  51. * If we didn't we'd get EAGAIN on overflow
  52. * and we'd have to write code to ignore it. */
  53. assert(s == sizeof(value));
  54. }
  55. return r == sizeof(value);
  56. }