queueset_poll_linux.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //go:build linux && !android
  2. // +build linux,!android
  3. package tio
  4. import (
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "sync/atomic"
  9. "golang.org/x/sys/unix"
  10. )
  11. type pollQueueSet struct {
  12. pq []*Poll
  13. // pqi is exactly the same as pq, but stored as the interface type
  14. pqi []Queue
  15. shutdownFd int
  16. closed atomic.Bool
  17. }
  18. func NewPollQueueSet() (QueueSet, error) {
  19. shutdownFd, err := unix.Eventfd(0, unix.EFD_NONBLOCK|unix.EFD_CLOEXEC)
  20. if err != nil {
  21. return nil, fmt.Errorf("failed to create eventfd: %w", err)
  22. }
  23. out := &pollQueueSet{
  24. pq: []*Poll{},
  25. pqi: []Queue{},
  26. shutdownFd: shutdownFd,
  27. }
  28. return out, nil
  29. }
  30. func (c *pollQueueSet) Queues() []Queue {
  31. return c.pqi
  32. }
  33. func (c *pollQueueSet) Add(fd int) error {
  34. if c.closed.Load() {
  35. return errors.New("queue set already closed")
  36. }
  37. x, err := newPoll(fd, c.shutdownFd)
  38. if err != nil {
  39. return err
  40. }
  41. c.pq = append(c.pq, x)
  42. c.pqi = append(c.pqi, x)
  43. return nil
  44. }
  45. func (c *pollQueueSet) wakeForShutdown() error {
  46. var buf [8]byte
  47. binary.NativeEndian.PutUint64(buf[:], 1)
  48. _, err := unix.Write(int(c.shutdownFd), buf[:])
  49. return err
  50. }
  51. func (c *pollQueueSet) Close() error {
  52. if c.closed.Swap(true) {
  53. return nil
  54. }
  55. errs := []error{}
  56. // Signal all readers blocked in poll to wake up and exit.
  57. // They observe POLLIN on the shutdown eventfd and return os.ErrClosed.
  58. if err := c.wakeForShutdown(); err != nil {
  59. errs = append(errs, err)
  60. }
  61. // Close the per-queue tun fds; this also unblocks any in-flight reads.
  62. for _, x := range c.pq {
  63. if err := x.Close(); err != nil {
  64. errs = append(errs, err)
  65. }
  66. }
  67. // Close the shutdown eventfd last: every reader's pollfd set references it,
  68. // so it must outlive the wake + per-queue teardown above.
  69. if err := unix.Close(c.shutdownFd); err != nil {
  70. errs = append(errs, err)
  71. }
  72. c.shutdownFd = -1
  73. return errors.Join(errs...)
  74. }