Skip to content

Commit d60275f

Browse files
committed
Flush SQE batch by timeout
1 parent c0ca424 commit d60275f

3 files changed

Lines changed: 102 additions & 64 deletions

File tree

‎include/silk/fibers/fiber.h‎

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,13 @@ static_assert(sizeof(FiberId) == 8);
5656
*/
5757
enum class ProfileEventKind : uint8_t
5858
{
59-
SUSPEND_WAIT = 0, // suspended -> enqueueReady: blocked-on-condition latency
60-
IO_SUBMIT = 1, // submitIo: io_uring_submit cost per fiber-suspend flush
61-
IO_WAIT = 2, // enqueueIo -> handleCompletion: IO latency
62-
READY_WAIT = 3, // enqueueReady -> runFiber: ready-queue dwell
63-
FIBER_RUN = 4, // switchToFiberContext -> return: on-CPU time per slice
59+
READY_WAIT = 0, // enqueueReady -> runFiber: ready-queue dwell
60+
FIBER_RUN = 1, // switchToFiberContext -> return: on-CPU time per slice
61+
SUSPEND_WAIT = 2, // suspended -> enqueueReady: blocked-on-condition latency
62+
IO_WAIT = 3, // enqueueIo -> handleCompletion: full IO latency
63+
SQ_WAIT = 4, // enqueueIo -> io_uring_submit: SQE pending in silk's SQ ring before flush to kernel
64+
SUBMIT_IO = 5, // io_uring_submit syscall cost
65+
CQ_WAIT = 6, // wall-clock gap between consecutive non-empty CQ drains on a ring
6466
MAX
6567
};
6668

@@ -91,32 +93,36 @@ class FiberScheduler
9193
{
9294
// Per-fiber stack size in bytes. Must be a multiple of the system page size.
9395
// The pool also reserves two guard pages adjacent to each stack.
94-
uint64_t fiberStackSize = 64 * 1024;
96+
uint32_t fiberStackSize = 64 * 1024;
9597

9698
// Per-CPU ready queue capacity (fibers). Must be a power of two and >= 2.
9799
// Sized to absorb dispatch bursts without falling back to the global queue.
98-
uint64_t readyQueueCapacity = 1024;
100+
uint32_t readyQueueCapacity = 1024;
101+
102+
// Hash-table size for futex-style waiter lookups. Must be a power of two.
103+
uint32_t waiterTableSize = 4096;
99104

100105
// Per-CPU io_uring SQ ring capacity. Must be a power of two; the kernel
101106
// rounds up to the nearest supported size.
102-
uint64_t ioUringQueueSize = 256;
107+
uint32_t ioUringQueueSize = 256;
103108

104-
// Mid-drain submit threshold: submitIo defers io_uring_enter until the SQ
105-
// ring holds at least this many entries. Lower values approach per-fiber
106-
// submit (better latency on inline-completion workloads); higher values
107-
// amortize syscall cost across more SQEs (better throughput on networked
108-
// workloads). Must be <= ioUringQueueSize.
109+
// Upper bound on the number of SQEs that may sit in silk's SQ ring
110+
// before being flushed to the kernel. Must be <= ioUringQueueSize.
109111
uint32_t ioUringFlushThreshold = 64;
110112

111-
// Hash-table size for futex-style waiter lookups. Must be a power of two.
112-
uint64_t waiterTableSize = 4096;
113+
// Upper bound on how long an SQE may sit in silk's SQ ring before
114+
// being flushed to the kernel.
115+
uint32_t ioUringFlushTimeout = 100'000;
116+
117+
// Derived in initialize() from ioUringFlushTimeout; users do not set this.
118+
uint64_t ioUringFlushTimeoutCycles = 0;
113119

114120
// Scheduler park backoff (nanoseconds). The dispatch loop spins for up to
115121
// spinThresholdNs after going idle; past that it parks on the eventfd with
116122
// an exponential backoff starting at initialWaitNs and capped at maxWaitNs.
117-
uint64_t initialWaitNs = 1'000;
118-
uint64_t maxWaitNs = 10'000'000;
119-
uint64_t spinThresholdNs = 20'000;
123+
uint32_t initialWaitNs = 1'000;
124+
uint32_t maxWaitNs = 10'000'000;
125+
uint32_t spinThresholdNs = 20'000;
120126

121127
// Allocate per-CPU latency profilers.
122128
bool enableProfiler = false;

‎src/fibers/fiber.cpp‎

Lines changed: 68 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ static constexpr uint16_t INVALID_PROCESSOR_NUMBER = (1 << 10);
6868
x(FIBER_STOLEN, "FiberStolen") \
6969
x(IO_ENQUEUED, "IoEnqueued") \
7070
x(IO_COMPLETED, "IoCompleted") \
71+
x(IO_SUBMITTED, "IoSubmitted") \
7172
x(SQ_RING_OVERFLOW, "SQRingOverflow") \
7273
x(CQ_RING_OVERFLOW, "CQRingOverflow") \
7374
x(SLEEP_ENQUEUED, "SleepEnqueued") \
@@ -533,7 +534,7 @@ struct FiberScheduler::ProcessorState
533534

534535
template <typename Setup>
535536
bool enqueueIo(IoFuture * future, Setup && setup) noexcept;
536-
void submitIo(bool flush) noexcept;
537+
bool submitIo(bool flush) noexcept;
537538

538539
void insertSuspended(Fiber * fiber) noexcept;
539540
void removeSuspended(Fiber * fiber) noexcept;
@@ -579,6 +580,18 @@ struct FiberScheduler::ProcessorState
579580
// Deadline of the in-flight io_uring timeout SQE; 0 when none is pending.
580581
uint64_t wakeupDeadlineCycles = 0;
581582

583+
// Timestamp (TSC cycles) of the most recent successful CQ drain on
584+
// this ring. Used to emit CQ_WAIT profile events bounding how long
585+
// any CQE in the next drain batch could have sat in the ring.
586+
uint64_t lastCqDrainCycles = 0;
587+
588+
// Timestamp (TSC cycles) of the most recent io_uring_submit call.
589+
// Read in submitIo (time-gate) and handleCompletionQueue (SQ_WAIT
590+
// emit) under serviceLoopLock; written in submitIo under
591+
// submissionLock. Relaxed atomic is sufficient: readers tolerate a
592+
// slightly stale value.
593+
std::atomic<uint64_t> lastSubmitCycles{0};
594+
582595
// Per-CPU latency profiler. Allocated only when Options::enableProfiler
583596
// is set; null otherwise. Co-located with the hot path so the null
584597
// check in reportFiberWait/reportIoWait costs no additional miss when
@@ -653,6 +666,9 @@ void FiberScheduler::ProcessorState::initialize(uint32_t cpu) noexcept
653666
{
654667
profiler = std::make_unique<Profiler>();
655668
}
669+
670+
lastCqDrainCycles = Tsc::getCycles();
671+
lastSubmitCycles.store(lastCqDrainCycles, std::memory_order_relaxed);
656672
}
657673

658674
void FiberScheduler::ProcessorState::destroy() noexcept
@@ -841,59 +857,55 @@ bool FiberScheduler::ProcessorState::enqueueIo(IoFuture * future, Setup && setup
841857
return false;
842858
}
843859

844-
// Submit pending SQEs to the kernel.
845-
//
846-
// flush=false: pressure-relief mode for dispatch loops - only submit
847-
// once at least options.ioUringFlushThreshold SQEs are queued, otherwise
848-
// let the next fiber accumulate more work before paying the syscall.
849-
//
850-
// flush=true: force submit regardless of count. Used at end-of-drain, by
851-
// the proxy/wakeup paths that need the SQE visible immediately, and by
852-
// worker threads which have no batching boundary.
853-
//
854-
// IO_SUBMIT profile event represents the syscall cost; per-fiber latency
855-
// lives in IO_WAIT. Category 0 because a single io_uring_enter covers SQEs
856-
// from any fibers that contributed.
857-
void FiberScheduler::ProcessorState::submitIo(bool flush) noexcept
858-
{
859-
// Fast path: submitIo is always called on the same thread that just called
860-
// enqueueIo, so our own enqueue is always visible here.
861-
// Suppress the TSan report for the cross-CPU race on sqe_tail.
860+
// Submit pending SQEs to the kernel. flush=true: unconditional flush.
861+
// flush=false: gated by ioUringFlushThreshold (count) or ioUringFlushTimeout.
862+
bool FiberScheduler::ProcessorState::submitIo(bool flush) noexcept
863+
{
864+
// Fast path: read SQ tail outside the lock.
862865
TSAN_IGNORE_BEGIN();
863866
uint32_t count = ::io_uring_sq_ready(&ring);
864867
TSAN_IGNORE_END();
868+
if (count == 0)
869+
{
870+
return false;
871+
}
872+
873+
uint64_t nowCycles = Tsc::getCycles();
865874

866-
uint32_t minCount = flush ? 1 : options.ioUringFlushThreshold;
867-
if (count < minCount)
875+
if (!flush)
868876
{
869-
return;
877+
bool countMet = count >= options.ioUringFlushThreshold;
878+
bool staleMet = nowCycles - lastSubmitCycles.load(std::memory_order_relaxed) > options.ioUringFlushTimeoutCycles;
879+
if (!countMet && !staleMet)
880+
{
881+
return false;
882+
}
870883
}
871884

872885
std::lock_guard lock(submissionLock);
873886

874887
count = ::io_uring_sq_ready(&ring);
875-
if (count >= minCount)
888+
if (count == 0)
876889
{
877-
// TSan needs an explicit barrier between submission/completion.
878-
TSAN_RELEASE(this);
890+
return false;
891+
}
879892

880-
if (profiler)
881-
{
882-
uint64_t startCycles = Tsc::getCycles();
893+
// TSan needs an explicit barrier between submission/completion.
894+
TSAN_RELEASE(this);
883895

884-
int r = ::io_uring_submit(&ring);
885-
SILK_ASSERT(r >= 0);
896+
lastSubmitCycles.store(nowCycles, std::memory_order_relaxed);
886897

887-
profileEvent(ProfileEventKind::IO_SUBMIT, 0, Tsc::getCycles() - startCycles);
888-
}
889-
else
890-
{
891-
int r = ::io_uring_submit(&ring);
892-
SILK_ASSERT(r >= 0);
893-
}
898+
int r = ::io_uring_submit(&ring);
899+
SILK_ASSERT(r >= 0);
894900

895-
Perf::getSimpleCounter(simpleCounters[IO_ENQUEUED], number).increment(count);
901+
if (profiler)
902+
{
903+
profileEvent(ProfileEventKind::SUBMIT_IO, 0, Tsc::getCycles() - nowCycles);
896904
}
905+
906+
Perf::getSimpleCounter(simpleCounters[IO_ENQUEUED], number).increment(count);
907+
Perf::getSimpleCounter(simpleCounters[IO_SUBMITTED], number).increment();
908+
return true;
897909
}
898910

899911
void FiberScheduler::ProcessorState::insertSuspended(Fiber * fiber) noexcept
@@ -996,6 +1008,7 @@ void FiberScheduler::initialize(const Options * userOptions) noexcept
9961008
SILK_ASSERT(options.ioUringQueueSize >= 2 && (options.ioUringQueueSize & (options.ioUringQueueSize - 1)) == 0);
9971009
SILK_ASSERT(options.ioUringFlushThreshold >= 1 && options.ioUringFlushThreshold <= options.ioUringQueueSize);
9981010
SILK_ASSERT(options.waiterTableSize >= 2 && (options.waiterTableSize & (options.waiterTableSize - 1)) == 0);
1011+
options.ioUringFlushTimeoutCycles = Tsc::nanosecondsToCycles(options.ioUringFlushTimeout);
9991012

10001013
scheduler = new SchedulerState();
10011014

@@ -1522,7 +1535,7 @@ void FiberScheduler::runScheduler(ProcessorState * processor) noexcept
15221535
}
15231536
else
15241537
{
1525-
waitNs = waitNs ? std::min(waitNs * 2, options.maxWaitNs) : options.initialWaitNs;
1538+
waitNs = waitNs ? std::min<uint64_t>(waitNs * 2, options.maxWaitNs) : options.initialWaitNs;
15261539
}
15271540
}
15281541
}
@@ -1662,6 +1675,12 @@ bool FiberScheduler::handleCompletionQueue(ProcessorState * processor) noexcept
16621675
// TSan needs an explicit barrier between submission/completion.
16631676
TSAN_ACQUIRE(processor);
16641677

1678+
uint64_t entryCycles = 0;
1679+
if (processor->profiler)
1680+
{
1681+
entryCycles = Tsc::getCycles();
1682+
}
1683+
16651684
for (;;)
16661685
{
16671686
// Handle completion entries in the ring.
@@ -1704,7 +1723,10 @@ bool FiberScheduler::handleCompletionQueue(ProcessorState * processor) noexcept
17041723

17051724
if (processor->profiler)
17061725
{
1707-
processor->profileEvent(ProfileEventKind::IO_WAIT, future->category, Tsc::getCycles() - future->submitTimestamp);
1726+
uint64_t nowCycles = Tsc::getCycles();
1727+
uint64_t submitCycles = processor->lastSubmitCycles.load(std::memory_order_relaxed);
1728+
processor->profileEvent(ProfileEventKind::IO_WAIT, future->category, nowCycles - future->submitTimestamp);
1729+
processor->profileEvent(ProfileEventKind::SQ_WAIT, future->category, submitCycles - future->submitTimestamp);
17081730
}
17091731

17101732
int result = cqe->res;
@@ -1742,6 +1764,12 @@ bool FiberScheduler::handleCompletionQueue(ProcessorState * processor) noexcept
17421764
SILK_ASSERT(r >= 0);
17431765
}
17441766

1767+
if (didWork && processor->profiler)
1768+
{
1769+
processor->profileEvent(ProfileEventKind::CQ_WAIT, 0, entryCycles - processor->lastCqDrainCycles);
1770+
processor->lastCqDrainCycles = entryCycles;
1771+
}
1772+
17451773
return didWork;
17461774
}
17471775

‎src/perf/common.cpp‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,16 +112,20 @@ static const char * profileEventKindName(silk::ProfileEventKind kind) noexcept
112112
{
113113
switch (kind)
114114
{
115-
case silk::ProfileEventKind::SUSPEND_WAIT:
116-
return "suspend_wait";
117-
case silk::ProfileEventKind::IO_SUBMIT:
118-
return "io_submit";
119-
case silk::ProfileEventKind::IO_WAIT:
120-
return "io_wait";
121115
case silk::ProfileEventKind::READY_WAIT:
122116
return "ready_wait";
123117
case silk::ProfileEventKind::FIBER_RUN:
124118
return "fiber_run";
119+
case silk::ProfileEventKind::SUSPEND_WAIT:
120+
return "suspend_wait";
121+
case silk::ProfileEventKind::IO_WAIT:
122+
return "io_wait";
123+
case silk::ProfileEventKind::CQ_WAIT:
124+
return "cq_wait";
125+
case silk::ProfileEventKind::SQ_WAIT:
126+
return "sq_wait";
127+
case silk::ProfileEventKind::SUBMIT_IO:
128+
return "submit_io";
125129
default:
126130
return "unknown";
127131
}

0 commit comments

Comments
 (0)