event_notifier.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 "event_notifier.h"
  13. #ifdef CONFIG_EVENTFD
  14. #include <sys/eventfd.h>
  15. #endif
  16. int event_notifier_init(EventNotifier *e, int active)
  17. {
  18. #ifdef CONFIG_EVENTFD
  19. int fd = eventfd(!!active, EFD_NONBLOCK | EFD_CLOEXEC);
  20. if (fd < 0)
  21. return -errno;
  22. e->fd = fd;
  23. return 0;
  24. #else
  25. return -ENOSYS;
  26. #endif
  27. }
  28. void event_notifier_cleanup(EventNotifier *e)
  29. {
  30. close(e->fd);
  31. }
  32. int event_notifier_get_fd(EventNotifier *e)
  33. {
  34. return e->fd;
  35. }
  36. int event_notifier_test_and_clear(EventNotifier *e)
  37. {
  38. uint64_t value;
  39. int r = read(e->fd, &value, sizeof(value));
  40. return r == sizeof(value);
  41. }
  42. int event_notifier_test(EventNotifier *e)
  43. {
  44. uint64_t value;
  45. int r = read(e->fd, &value, sizeof(value));
  46. if (r == sizeof(value)) {
  47. /* restore previous value. */
  48. int s = write(e->fd, &value, sizeof(value));
  49. /* never blocks because we use EFD_SEMAPHORE.
  50. * If we didn't we'd get EAGAIN on overflow
  51. * and we'd have to write code to ignore it. */
  52. assert(s == sizeof(value));
  53. }
  54. return r == sizeof(value);
  55. }