1 package http
2 3 // Spawned dispatch: the same one-call-per-request handler, run by a fixed pool
4 // of worker routines instead of in the connection's domain.
5 //
6 // The pool exists because a spawn is a fork, not a coroutine: a worker is an OS
7 // thread with its own domain and its own arenas, so one spawn per request would
8 // cost a thread per request (measured by tests/netsmoke/spawncost).
9 //
10 // The boundary carries a QUEUE-OWNED RING OF PREALLOCATED SLOTS, handed off by
11 // index. The slot buffer is mapped MAP_SHARED before the workers are spawned, so
12 // the parent writes one message into slot i and sends i; the worker reads the
13 // bytes in place and answers in the same slot, sending i back. One message per
14 // slot, one copy at a named site (chanSlotPutReq / chanSlotPutResp), and no
15 // allocation in the steady state - the shell reuses its own slot for every
16 // request on a connection, so the request body costs no bytes after warm-up.
17 //
18 // A domain is a thread, so the ring's address is the same in both domains; it
19 // is passed to the worker as a spawn argument because a package global is
20 // thread-local and the worker starts with zeroed TLS.
21 //
22 // Why not send the encoded message as a []byte on a chan []byte? That allocates
23 // a fresh slice per message, and the point of the ring is that the steady state
24 // allocates nothing.
25 //
26 // The slot count is sized by MEASURED in-flight concurrency, not by connections
27 // times slots. The shell serves one connection at a time and blocks on the
28 // response, so at most one request is in flight at any instant (measured: a
29 // counter over the pool call sites reported max 1 with one connection); four
30 // slots give the handoff headroom without the "connections times slots" sizing
31 // that got the first ring attempt reverted.
32 //
33 // The router table is read by the workers through the address the shell passes
34 // at spawn: it is built at startup and only read afterwards, so the sharing is
35 // read-only and needs no copy.
36 37 import (
38 "errors"
39 "runtime"
40 "unsafe"
41 )
42 43 // chanGlobalMux is the table the pool workers read. The shell assigns its own
44 // copy; each worker installs the address it received at spawn.
45 var chanGlobalMux *ChanMux
46 47 func chanRouteHandler(id int32) (h ChanHandler) {
48 if chanGlobalMux == nil || id < 0 || id >= int32(len(chanGlobalMux.routes)) {
49 return nil
50 }
51 return chanGlobalMux.routes[id].h
52 }
53 54 // --- the slot ring ---
55 56 // Slot geometry. slotBytes bounds ONE message (request or response): 1MB, and a
57 // frame that does not fit panics by name rather than truncating. The buffer is
58 // mmap'd shared and lazily faulted, so the committed size is the whole mapping
59 // and the resident size is only the pages a message actually touches.
60 const (
61 // Four slots, 64KB each. The slot count comes from the measured in-flight
62 // concurrency (one: the shell is serial and blocks on the reply); the slot
63 // SIZE comes from the measured message size - a fixture request is a few
64 // hundred bytes, so 64KB is two orders of magnitude of headroom. It is
65 // deliberately small: the ring is MAP_SHARED and its pages are resident, and
66 // 4 x 1MB made the no-accumulation unit measure the mapping being faulted
67 // rather than the steady state (+2096kB over 400 exchanges against a 2048kB
68 // threshold). A frame that does not fit panics by name.
69 chanSlotCount = int32(4)
70 chanSlotBytes = int32(64 << 10)
71 chanSlotFrame = int32(32) // fixed header words: len, status, route, 3 lens, bodylen, nheaders
72 )
73 74 // chanSlotBuf is the shared ring. The shell creates it; each worker
75 // reconstructs the same view from the address it received at spawn.
76 var chanSlotBuf []byte
77 78 // chanSlotInFlightMax records the largest number of pool calls in flight, the
79 // measurement the slot count is sized from.
80 var chanSlotInFlight int32
81 var chanSlotInFlightMax int32
82 83 // chanSlotBase returns the start offset of slot i.
84 func chanSlotBase(i int32) (off int32) {
85 return i * chanSlotBytes
86 }
87 88 func chanSlotPutI32(b []byte, off, v int32) {
89 b[off] = byte(v)
90 b[off+1] = byte(v >> 8)
91 b[off+2] = byte(v >> 16)
92 b[off+3] = byte(v >> 24)
93 }
94 95 func chanSlotGetI32(b []byte, off int32) (v int32) {
96 return int32(b[off]) | int32(b[off+1])<<8 | int32(b[off+2])<<16 | int32(b[off+3])<<24
97 }
98 99 // chanSlotPutRaw writes a length prefix and the bytes: one of the two copy sites.
100 func chanSlotPutRaw(b []byte, off int32, s []byte) (next int32) {
101 n := int32(len(s))
102 chanSlotPutI32(b, off, n)
103 off = off + 4
104 for i := int32(0); i < n; i++ {
105 b[off+i] = s[i]
106 }
107 return off + n
108 }
109 110 // chanSlotGetRaw reads a length prefix and copies the bytes into the caller's
111 // arena (the worker decodes into its request arena, which the shell resets).
112 func chanSlotGetRaw(b []byte, off int32) (s []byte, next int32) {
113 n := chanSlotGetI32(b, off)
114 off = off + 4
115 s = []byte{:n}
116 for i := int32(0); i < n; i++ {
117 s[i] = b[off+i]
118 }
119 return s, off + n
120 }
121 122 func chanSlotPutHeaders(b []byte, off int32, h Header) (next int32) {
123 off = off
124 n := int32(0)
125 if h != nil {
126 n = int32(len(h))
127 }
128 chanSlotPutI32(b, off, n)
129 off = off + 4
130 for k, vv := range h {
131 off = chanSlotPutRaw(b, off, k)
132 chanSlotPutI32(b, off, int32(len(vv)))
133 off = off + 4
134 for i := int32(0); i < len(vv); i++ {
135 off = chanSlotPutRaw(b, off, vv[i])
136 }
137 }
138 return off
139 }
140 141 func chanSlotGetHeaders(b []byte, off int32) (h Header, next int32) {
142 n := chanSlotGetI32(b, off)
143 off = off + 4
144 if n == 0 {
145 return nil, off
146 }
147 h = Header{}
148 for i := int32(0); i < n; i++ {
149 var k []byte
150 k, off = chanSlotGetRaw(b, off)
151 vn := chanSlotGetI32(b, off)
152 off = off + 4
153 vv := [][]byte{:vn}
154 for j := int32(0); j < vn; j++ {
155 vv[j], off = chanSlotGetRaw(b, off)
156 }
157 h[k] = vv
158 }
159 return h, off
160 }
161 162 // chanSlotPutReq is THE request copy: the shell's message into its slot.
163 // chanSlotWindow is a VIEW of one slot in the shared ring.
164 //
165 // A bounded sub-slice (buf[a:b]) allocates and copies in this language, and a
166 // copy is the one thing a shared-memory ring cannot have: the shell writes the
167 // request into its private copy, the worker reads the untouched ring, and
168 // chanSlotGetReq answers "decode failed" for every request. That is what
169 // spawned mode did until round 279 - the manager accepted and read the request,
170 // the four workers were alive and polling, and every frame arrived empty.
171 // unsafe.Add is the only way to name the same bytes without copying them.
172 func chanSlotWindow(base int32) (slot []byte) {
173 if base < 0 || base+chanSlotBytes > int32(len(chanSlotBuf)) {
174 panic("chanpool: slot window out of range")
175 }
176 p := unsafe.Add(unsafe.Pointer(unsafe.SliceData(chanSlotBuf)), uintptr(base))
177 return unsafe.Slice((*byte)(p), chanSlotBytes)
178 }
179 180 func chanSlotPutReq(slot []byte, routeID int32, rq *Req) (n int32) {
181 off := chanSlotFrame
182 off = chanSlotPutRaw(slot, off, rq.Method)
183 off = chanSlotPutRaw(slot, off, rq.Path)
184 off = chanSlotPutRaw(slot, off, rq.Proto)
185 off = chanSlotPutRaw(slot, off, rq.Body)
186 off = chanSlotPutHeaders(slot, off, rq.Headers)
187 if off > int32(len(slot)) {
188 panic("chanpool: request frame exceeds the slot")
189 }
190 chanSlotPutI32(slot, 0, off)
191 chanSlotPutI32(slot, 4, 0)
192 chanSlotPutI32(slot, 8, routeID)
193 return off
194 }
195 196 // chanSlotGetReq decodes a request frame into the worker's request arena.
197 func chanSlotGetReq(slot []byte) (routeID int32, rq *Req, ok bool) {
198 n := chanSlotGetI32(slot, 0)
199 if n <= chanSlotFrame || n > int32(len(slot)) {
200 return -1, nil, false
201 }
202 routeID = chanSlotGetI32(slot, 8)
203 off := chanSlotFrame
204 rq = &Req{}
205 rq.Method, off = chanSlotGetRaw(slot, off)
206 rq.Path, off = chanSlotGetRaw(slot, off)
207 rq.Proto, off = chanSlotGetRaw(slot, off)
208 rq.Body, off = chanSlotGetRaw(slot, off)
209 rq.Headers, off = chanSlotGetHeaders(slot, off)
210 return routeID, rq, true
211 }
212 213 // chanSlotPutResp is THE response copy: the worker's message into the same slot.
214 func chanSlotPutResp(slot []byte, resp *Resp) (n int32) {
215 off := chanSlotFrame
216 off = chanSlotPutRaw(slot, off, resp.Body)
217 off = chanSlotPutHeaders(slot, off, resp.Headers)
218 if off > int32(len(slot)) {
219 panic("chanpool: response frame exceeds the slot")
220 }
221 chanSlotPutI32(slot, 0, off)
222 chanSlotPutI32(slot, 4, resp.Status)
223 chanSlotPutI32(slot, 8, 0)
224 return off
225 }
226 227 // chanSlotPutAbort writes a bodyless abort frame with a reason.
228 func chanSlotPutAbort(slot []byte, reason []byte) (n int32) {
229 off := chanSlotFrame
230 off = chanSlotPutRaw(slot, off, reason)
231 chanSlotPutI32(slot, 0, off)
232 chanSlotPutI32(slot, 4, 0)
233 chanSlotPutI32(slot, 8, -1)
234 return off
235 }
236 237 // chanSlotGetResp decodes a response frame into the shell's request arena.
238 func chanSlotGetResp(slot []byte) (resp *Resp, ok bool) {
239 n := chanSlotGetI32(slot, 0)
240 if n <= chanSlotFrame || n > int32(len(slot)) {
241 return nil, false
242 }
243 status := chanSlotGetI32(slot, 4)
244 off := chanSlotFrame
245 if status == 0 && chanSlotGetI32(slot, 8) == -1 {
246 reason, _ := chanSlotGetRaw(slot, off)
247 chanReportAbort(errors.New(reason))
248 return nil, false
249 }
250 resp = &Resp{}
251 resp.Status = status
252 resp.Body, off = chanSlotGetRaw(slot, off)
253 resp.Headers, off = chanSlotGetHeaders(slot, off)
254 return resp, true
255 }
256 257 // chanWorkerLoop is one pool worker. It owns no socket and no connection state:
258 // it decodes a request slot into ITS request arena, makes the route's one
259 // handler call there, writes the response back into the same slot and resets the
260 // arena, so a worker that served a million requests holds no more memory than
261 // one that served one.
262 func chanWorkerLoop(jobs chan int32, results chan int32, slotPtr, muxPtr uintptr) (closed chan struct{}) {
263 // The shell's package globals are not this domain's: package variables are
264 // thread-local and a new domain starts with zeroed TLS. The two addresses
265 // travel as spawn arguments - the ring is process memory and the table is
266 // read-only after startup - and are installed before the first receive.
267 chanSlotBuf = unsafe.Slice((*byte)(unsafe.Pointer(slotPtr)), chanSlotCount*chanSlotBytes)
268 chanGlobalMux = (*ChanMux)(unsafe.Pointer(muxPtr))
269 prevScope := runtime.SetArenaScope(ArenaScopeRequest)
270 arena := runtime.ArenaAcquire(chanRequestArenaBytes)
271 runtime.SetArenaScope(prevScope)
272 done := false
273 for !done {
274 // EVERY allocation of an iteration belongs to the iteration, so the
275 // request arena is entered before the receive that starts it. The
276 // decode and the handler call were the visible half: with only those
277 // inside, the worker still grew the frame arena it inherited from
278 // spawn - which lives for the life of the process - at ~615B a request
279 // (measured: 50kB after 100 requests, 615kB after 800), and that
280 // overflowed into a chained 64MB region, which the phase-8
281 // no-accumulation unit saw as +2096kB over its 400 exchanges. The
282 // comment below is the rule: one iteration, one arena boundary.
283 runtime.ManualArenaEnter(arena)
284 // The worker serves its inbox and watches its termination breaker in
285 // the same select: a shutdown must not wait for the next request.
286 var i int32
287 select {
288 case <-closed:
289 runtime.ManualArenaExit(arena)
290 runtime.ArenaReset(arena)
291 return closed
292 case j := <-jobs:
293 i = j
294 }
295 if i < 0 {
296 runtime.ManualArenaExit(arena)
297 runtime.ArenaReset(arena)
298 break
299 }
300 if i >= chanSlotCount {
301 panic("chanpool: slot index out of range")
302 }
303 slot := chanSlotWindow(chanSlotBase(i))
304 routeID, rq, ok := chanSlotGetReq(slot)
305 h := chanRouteHandler(routeID)
306 var resp *Resp
307 if ok && h != nil {
308 resp = h.Handle(rq)
309 }
310 if resp == nil {
311 chanSlotPutAbort(slot, []byte("http: channel handler: no route"))
312 } else {
313 chanSlotPutResp(slot, resp)
314 }
315 // Answer before the reset: the shell only ever reads the slot, so it can
316 // take the reply while the worker's arena is still current, and nothing
317 // of the request outlives this line.
318 results <- i
319 runtime.ManualArenaExit(arena)
320 runtime.ArenaReset(arena)
321 // The worker is a request-scope server: drain the deferred compaction
322 // of its own long-lived sovereign receivers at the same boundary the
323 // connection loop uses.
324 runtime.SovDrainCompactions(chanSovDrainBudget)
325 }
326 runtime.ArenaRelease(arena)
327 return closed
328 }
329 330 // chanPool is a fixed set of workers with their own queues, plus the slot ring
331 // they share with the shell. next rotates so a connection does not always land
332 // on the same worker.
333 type chanPool struct {
334 mux *ChanMux
335 jobs []chan int32
336 results []chan int32
337 breakers []chan struct{}
338 next int32
339 }
340 341 // closeBreakers ends every worker this pool started. The spawning frame owns
342 // its children: a return from ChanServeTimeout must not leave a domain behind,
343 // which is why the breakers are kept rather than dropped at spawn.
344 func (p *chanPool) closeBreakers() {
345 if p == nil {
346 return
347 }
348 for i := int32(0); i < int32(len(p.breakers)); i++ {
349 close(p.breakers[i])
350 }
351 p.breakers = nil
352 }
353 354 func (p *chanPool) pick() (i int32) {
355 i = p.next % int32(len(p.jobs))
356 p.next = p.next + 1
357 return i
358 }
359 360 // call hands one decoded request to a worker through its slot and returns the
361 // response the worker wrote back. The response's slices are decoded into the
362 // CALLER's request arena, so the shell can write them and then free the arena.
363 func (p *chanPool) call(routeID int32, rq *Req) (resp *Resp) {
364 i := p.pick()
365 chanSlotInFlight++
366 if chanSlotInFlight > chanSlotInFlightMax {
367 chanSlotInFlightMax = chanSlotInFlight
368 }
369 slot := chanSlotWindow(chanSlotBase(i))
370 chanSlotPutReq(slot, routeID, rq)
371 p.jobs[i] <- i
372 j := <-p.results[i]
373 if j < 0 || j >= chanSlotCount {
374 panic("chanpool: slot index out of range")
375 }
376 out := chanSlotWindow(chanSlotBase(j))
377 resp, _ = chanSlotGetResp(out)
378 chanSlotInFlight--
379 return resp
380 }
381 382 // chanSlotPrefault touches one byte of every page of the slot ring.
383 //
384 // The ring is MAP_SHARED and lazily faulted, so without this its pages are
385 // faulted by the requests that use them: the first few hundred exchanges of a
386 // process pay for the mapping, which reads as per-request retention (+2096kB
387 // over 400 exchanges, against a 2048kB no-accumulation threshold that must not
388 // be widened). A queue-owned ring is taken into service at startup, so its cost
389 // belongs there, before the first request.
390 func chanSlotPrefault() {
391 if len(chanSlotBuf) == 0 {
392 return
393 }
394 page := 4096
395 for off := 0; off < len(chanSlotBuf); off = off + page {
396 chanSlotBuf[off] = 0
397 }
398 }
399 400 // ChanSlotMaxInFlight reports the largest number of pool calls that were ever in
401 // flight, the measurement the slot count is sized from.
402 func ChanSlotMaxInFlight() (n int32) {
403 return chanSlotInFlightMax
404 }
405 406 // ChanSlotCommittedBytes is what the slot ring reserves up front: the mapping is
407 // MAP_SHARED and lazily faulted, so this is committed address space and the
408 // resident part is only the pages the messages touch. It replaces the 32MB per
409 // direction the spawn rings reserve - that is the transport slope this closes.
410 func ChanSlotCommittedBytes() (n int32) {
411 return chanSlotCount * chanSlotBytes
412 }
413