Debian Codegraph @

server/dios.go

raw
1 // Copyright 2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "sync/atomic"
18 "time"
19 )
20
21 const defaultConcurrentIOs = 4096
22 const minConcurrentIOs = 4
23 const maxConcurrentIOs = 8192
24
25 // Used to limit number of disk IO calls in flight since they could all be blocking an OS thread.
26 // https://github.com/nats-io/nats-server/issues/2742
27 type diskIOSemaphore struct {
28 ch chan struct{}
29 waiters atomic.Int64
30 waits atomic.Uint64
31 waitNanos atomic.Uint64
32 maxWaitNanos atomic.Uint64
33 }
34
35 func newDiskIOSemaphore(n int) *diskIOSemaphore {
36 n = max(minConcurrentIOs, min(n, maxConcurrentIOs))
37 d := &diskIOSemaphore{ch: make(chan struct{}, n)}
38 for range n {
39 d.ch <- struct{}{}
40 }
41 return d
42 }
43
44 func defaultDiskIOSemaphore() *diskIOSemaphore {
45 // The disk IO semaphore used to be sized based on the number
46 // of CPU cores. That policy led to poor use of devices that
47 // can handle many requests in parallel, so simply cap the
48 // number of concurrent IO requests handed to the Go runtime.
49 return newDiskIOSemaphore(defaultConcurrentIOs)
50 }
51
52 func (d *diskIOSemaphore) acquire() {
53 select {
54 case <-d.ch:
55 return
56 default:
57 // No slot available, count this
58 // waiter before blocking.
59 d.waiters.Add(1)
60 start := time.Now()
61 <-d.ch
62 waited := time.Since(start)
63 d.waiters.Add(-1)
64 d.countWait(uint64(waited.Nanoseconds()))
65 }
66 }
67
68 func (d *diskIOSemaphore) countWait(ns uint64) {
69 d.waits.Add(1)
70 d.waitNanos.Add(ns)
71 for {
72 cur := d.maxWaitNanos.Load()
73 if ns <= cur || d.maxWaitNanos.CompareAndSwap(cur, ns) {
74 return
75 }
76 }
77 }
78
79 func (d *diskIOSemaphore) release() {
80 d.ch <- struct{}{}
81 }
82
83 func (d *diskIOSemaphore) cap() int {
84 return cap(d.ch)
85 }