gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/tcpip/link/stopfd/stopfd.go (about) 1 // Copyright 2022 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //go:build linux 16 // +build linux 17 18 // Package stopfd provides an type that can be used to signal the stop of a dispatcher. 19 package stopfd 20 21 import ( 22 "fmt" 23 24 "golang.org/x/sys/unix" 25 ) 26 27 // StopFD is an eventfd used to signal the stop of a dispatcher. 28 type StopFD struct { 29 EFD int 30 } 31 32 // New returns a new, initialized StopFD. 33 func New() (StopFD, error) { 34 efd, err := unix.Eventfd(0, unix.EFD_NONBLOCK) 35 if err != nil { 36 return StopFD{EFD: -1}, fmt.Errorf("failed to create eventfd: %w", err) 37 } 38 return StopFD{EFD: efd}, nil 39 } 40 41 // Stop writes to the eventfd and notifies the dispatcher to stop. It does not 42 // block. 43 func (sf *StopFD) Stop() { 44 increment := []byte{1, 0, 0, 0, 0, 0, 0, 0} 45 if n, err := unix.Write(sf.EFD, increment); n != len(increment) || err != nil { 46 // There are two possible errors documented in eventfd(2) for writing: 47 // 1. We are writing 8 bytes and not 0xffffffffffffff, thus no EINVAL. 48 // 2. stop is only supposed to be called once, it can't reach the limit, 49 // thus no EAGAIN. 50 panic(fmt.Sprintf("write(EFD) = (%d, %s), want (%d, nil)", n, err, len(increment))) 51 } 52 }