Debian Codegraph @

libgo/go/internal/poll/splice_linux.go

raw
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package poll
6
7 import (
8 "runtime"
9 "sync"
10 "sync/atomic"
11 "syscall"
12 "unsafe"
13 )
14
15 const (
16 // spliceNonblock makes calls to splice(2) non-blocking.
17 spliceNonblock = 0x2
18
19 // maxSpliceSize is the maximum amount of data Splice asks
20 // the kernel to move in a single call to splice(2).
21 maxSpliceSize = 4 << 20
22 )
23
24 // Splice transfers at most remain bytes of data from src to dst, using the
25 // splice system call to minimize copies of data from and to userspace.
26 //
27 // Splice gets a pipe buffer from the pool or creates a new one if needed, to serve as a buffer for the data transfer.
28 // src and dst must both be stream-oriented sockets.
29 //
30 // If err != nil, sc is the system call which caused the error.
31 func Splice(dst, src *FD, remain int64) (written int64, handled bool, sc string, err error) {
32 p, sc, err := getPipe()
33 if err != nil {
34 return 0, false, sc, err
35 }
36 defer putPipe(p)
37 var inPipe, n int
38 for err == nil && remain > 0 {
39 max := maxSpliceSize
40 if int64(max) > remain {
41 max = int(remain)
42 }
43 inPipe, err = spliceDrain(p.wfd, src, max)
44 // The operation is considered handled if splice returns no
45 // error, or an error other than EINVAL. An EINVAL means the
46 // kernel does not support splice for the socket type of src.
47 // The failed syscall does not consume any data so it is safe
48 // to fall back to a generic copy.
49 //
50 // spliceDrain should never return EAGAIN, so if err != nil,
51 // Splice cannot continue.
52 //
53 // If inPipe == 0 && err == nil, src is at EOF, and the
54 // transfer is complete.
55 handled = handled || (err != syscall.EINVAL)
56 if err != nil || inPipe == 0 {
57 break
58 }
59 p.data += inPipe
60
61 n, err = splicePump(dst, p.rfd, inPipe)
62 if n > 0 {
63 written += int64(n)
64 remain -= int64(n)
65 p.data -= n
66 }
67 }
68 if err != nil {
69 return written, handled, "splice", err
70 }
71 return written, true, "", nil
72 }
73
74 // spliceDrain moves data from a socket to a pipe.
75 //
76 // Invariant: when entering spliceDrain, the pipe is empty. It is either in its
77 // initial state, or splicePump has emptied it previously.
78 //
79 // Given this, spliceDrain can reasonably assume that the pipe is ready for
80 // writing, so if splice returns EAGAIN, it must be because the socket is not
81 // ready for reading.
82 //
83 // If spliceDrain returns (0, nil), src is at EOF.
84 func spliceDrain(pipefd int, sock *FD, max int) (int, error) {
85 if err := sock.readLock(); err != nil {
86 return 0, err
87 }
88 defer sock.readUnlock()
89 if err := sock.pd.prepareRead(sock.isFile); err != nil {
90 return 0, err
91 }
92 for {
93 n, err := splice(pipefd, sock.Sysfd, max, spliceNonblock)
94 if err == syscall.EINTR {
95 continue
96 }
97 if err != syscall.EAGAIN {
98 return n, err
99 }
100 if err := sock.pd.waitRead(sock.isFile); err != nil {
101 return n, err
102 }
103 }
104 }
105
106 // splicePump moves all the buffered data from a pipe to a socket.
107 //
108 // Invariant: when entering splicePump, there are exactly inPipe
109 // bytes of data in the pipe, from a previous call to spliceDrain.
110 //
111 // By analogy to the condition from spliceDrain, splicePump
112 // only needs to poll the socket for readiness, if splice returns
113 // EAGAIN.
114 //
115 // If splicePump cannot move all the data in a single call to
116 // splice(2), it loops over the buffered data until it has written
117 // all of it to the socket. This behavior is similar to the Write
118 // step of an io.Copy in userspace.
119 func splicePump(sock *FD, pipefd int, inPipe int) (int, error) {
120 if err := sock.writeLock(); err != nil {
121 return 0, err
122 }
123 defer sock.writeUnlock()
124 if err := sock.pd.prepareWrite(sock.isFile); err != nil {
125 return 0, err
126 }
127 written := 0
128 for inPipe > 0 {
129 n, err := splice(sock.Sysfd, pipefd, inPipe, spliceNonblock)
130 // Here, the condition n == 0 && err == nil should never be
131 // observed, since Splice controls the write side of the pipe.
132 if n > 0 {
133 inPipe -= n
134 written += n
135 continue
136 }
137 if err != syscall.EAGAIN {
138 return written, err
139 }
140 if err := sock.pd.waitWrite(sock.isFile); err != nil {
141 return written, err
142 }
143 }
144 return written, nil
145 }
146
147 // splice wraps the splice system call. Since the current implementation
148 // only uses splice on sockets and pipes, the offset arguments are unused.
149 // splice returns int instead of int64, because callers never ask it to
150 // move more data in a single call than can fit in an int32.
151 func splice(out int, in int, max int, flags int) (int, error) {
152 n, err := syscall.Splice(in, nil, out, nil, max, flags)
153 return int(n), err
154 }
155
156 type splicePipeFields struct {
157 rfd int
158 wfd int
159 data int
160 }
161
162 type splicePipe struct {
163 splicePipeFields
164
165 // We want to use a finalizer, so ensure that the size is
166 // large enough to not use the tiny allocator.
167 _ [24 - unsafe.Sizeof(splicePipeFields{})%24]byte
168 }
169
170 // splicePipePool caches pipes to avoid high-frequency construction and destruction of pipe buffers.
171 // The garbage collector will free all pipes in the sync.Pool periodically, thus we need to set up
172 // a finalizer for each pipe to close its file descriptors before the actual GC.
173 var splicePipePool = sync.Pool{New: newPoolPipe}
174
175 func newPoolPipe() any {
176 // Discard the error which occurred during the creation of pipe buffer,
177 // redirecting the data transmission to the conventional way utilizing read() + write() as a fallback.
178 p := newPipe()
179 if p == nil {
180 return nil
181 }
182 runtime.SetFinalizer(p, destroyPipe)
183 return p
184 }
185
186 // getPipe tries to acquire a pipe buffer from the pool or create a new one with newPipe() if it gets nil from the cache.
187 //
188 // Note that it may fail to create a new pipe buffer by newPipe(), in which case getPipe() will return a generic error
189 // and system call name splice in a string as the indication.
190 func getPipe() (*splicePipe, string, error) {
191 v := splicePipePool.Get()
192 if v == nil {
193 return nil, "splice", syscall.EINVAL
194 }
195 return v.(*splicePipe), "", nil
196 }
197
198 func putPipe(p *splicePipe) {
199 // If there is still data left in the pipe,
200 // then close and discard it instead of putting it back into the pool.
201 if p.data != 0 {
202 runtime.SetFinalizer(p, nil)
203 destroyPipe(p)
204 return
205 }
206 splicePipePool.Put(p)
207 }
208
209 var disableSplice unsafe.Pointer
210
211 // newPipe sets up a pipe for a splice operation.
212 func newPipe() (sp *splicePipe) {
213 p := (*bool)(atomic.LoadPointer(&disableSplice))
214 if p != nil && *p {
215 return nil
216 }
217
218 var fds [2]int
219 // pipe2 was added in 2.6.27 and our minimum requirement is 2.6.23, so it
220 // might not be implemented. Falling back to pipe is possible, but prior to
221 // 2.6.29 splice returns -EAGAIN instead of 0 when the connection is
222 // closed.
223 const flags = syscall.O_CLOEXEC | syscall.O_NONBLOCK
224 if err := syscall.Pipe2(fds[:], flags); err != nil {
225 return nil
226 }
227
228 sp = &splicePipe{splicePipeFields: splicePipeFields{rfd: fds[0], wfd: fds[1]}}
229
230 if p == nil {
231 p = new(bool)
232 defer atomic.StorePointer(&disableSplice, unsafe.Pointer(p))
233
234 // F_GETPIPE_SZ was added in 2.6.35, which does not have the -EAGAIN bug.
235 if syscall.F_GETPIPE_SZ == 0 {
236 *p = true
237 destroyPipe(sp)
238 return nil
239 }
240 if _, err := fcntl(fds[0], syscall.F_GETPIPE_SZ, 0); err != nil {
241 *p = true
242 destroyPipe(sp)
243 return nil
244 }
245 }
246
247 return
248 }
249
250 // destroyPipe destroys a pipe.
251 func destroyPipe(p *splicePipe) {
252 CloseFunc(p.rfd)
253 CloseFunc(p.wfd)
254 }