queueset_poll_linux.go 1.8 KB

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