Skip to contentSkip to conversation

nvme-pci: add adaptive interrupt polling

RFC PATCH Superseded Fengnan Chang 3 participants 9 messages Aug 6 – Aug 14 NVMe

lore
Share & tools
lore
#0 lore raw

RFC PATCH v2 1/1 nvme-pci: add adaptive interrupt polling

The idea behind this approach is: Let each I/O queue switch itself between interrupt and poll mode based on its own recent completion rate.

This version is still in the testing phase, and there are still some issues with the code implementation. I releasing it now to see if the approach is generally acceptable. If the approach looks good, I’ll continue to refine it and conduct more extensive testing. The main implementation logic is in nvme_adaptive_sample and nvme_adaptive_irq_poll; you should focus on reviewing the implementation of these two functions.

Compared to the previous version, this represents a much smaller performance regression while offering greater benefits.

In high-IOPS scenarios, relying on interrupts to handle I/O operations can limit performance. This issue becomes particularly pronounced in multi-disk environments, where performance is constrained by the CPU's interrupt-handling capacity.

Each Solidigm SB5PH27X038T device used for testing can deliver about 3.2M 4 KiB random-read IOPS. Four of them should be good for about 12.8M IOPS, but interrupt-driven completion tops out at 5.59M, only about 44% of that.

Polling gets rid of that cost, but polling every queue all the time burns CPU and hurts the sparse or bursty queues that interrupts handle just fine. So instead of a global switch, let each queue make the call on its own, from how fast it has been completing lately, and re-check often enough that the decision tracks the workload rather than a fixed tunable.

Each queue runs a small loop with three stages. First it samples its completion rate while still on interrupts. Only if that rate is high enough to fill a small batch inside a bounded latency window does it mask its own IRQ and start draining the CQ from a high-resolution timer, with each wait sized to collect roughly one batch. It keeps polling as long as it keeps up with that rate; the moment it stalls or slows down it turns the IRQ back on and backs off, waiting longer the further behind it fell. A queue that doesn't benefit drops back quickly and only gets retried once in a while, so polling stays on the queues that are actually interrupt-bound and everything else keeps running on the untouched IRQ path.

Measured with 4 KiB random reads on Solidigm SB5PH27X038T, adaptive on versus off:

                                   QD32      QD64      QD128
  one device, one job             +18.44%   +24.35%   +26.38%
  four devices, eight jobs        +83.76%   +99.02%   +96.26%

The four-device eight-job aggregate goes from 5.59M IOPS (44% of the 12.8M ceiling) to 10.89M IOPS (85%). Tail latency improves too: QD64 p99 drops from 1073 us to 498 us (-54%) and p99.9 from 1909 us to 741 us (-61%). Interrupts per I/O drop from about 0.91 to 0.08 (~12x fewer) in the four-device case, and from 0.96 to 0.03 (~33x fewer) on a single high-QD queue.

---
 drivers/nvme/host/Kconfig |   1 +
 drivers/nvme/host/pci.c   | 468 ++++++++++++++++++++++++++++++++++++--
 2 files changed, 452 insertions(+), 17 deletions(-)
drivers/nvme/host/Kconfig +1 -0
index 31974c7dd20c9..22164b901da85 100644
@@ -5,6 +5,7 @@ config NVME_CORE
 config BLK_DEV_NVME
 	tristate "NVM Express block device"
 	depends on PCI && BLOCK
+	select IRQ_POLL
 	select NVME_CORE
 	help
 	  The NVM Express driver is for solid state drives directly
drivers/nvme/host/pci.c +451 -17

593 lines not on this page · raw message

Signature · 1 line
2.39.5 (Apple Git-154)
maintainer
#1 lore raw
Quoted 9 lines · Fengnan Chang

The idea behind this approach is: Let each I/O queue switch itself between interrupt and poll mode based on its own recent completion rate.

This version is still in the testing phase, and there are still some issues with the code implementation. I releasing it now to see if the approach is generally acceptable. If the approach looks good, I´ll continue to refine it and conduct more extensive testing. The main implementation logic is in nvme_adaptive_sample and nvme_adaptive_irq_poll; you should focus on reviewing the implementation of these two functions.

Can we subscribe to the dynamic interrupt moderation (dim) library? I know it's generally used in conjuction with a hardware interrupt coalescing feature, but we can just do pure software with it too. The library provides a hill climb to adapt the policy at run time.

This is a quick PoC I put together. I haven't tested on fast devices, so I'm not sure if I've dialed in the profiles, but it's start of what I had in mind.

---

drivers/nvme/host/Kconfig +1 -0
index 31974c7dd20c9..9fad1c7b1f678 100644
@@ -6,6 +6,7 @@ config BLK_DEV_NVME
 	tristate "NVM Express block device"
 	depends on PCI && BLOCK
 	select NVME_CORE
+	select DIMLIB
 	help
 	  The NVM Express driver is for solid state drives directly
 	  connected to the PCI or PCI Express bus.  If you know you
drivers/nvme/host/pci.c +309 -23

424 lines not on this page · raw message

drivers/nvme/host/trace.c +1 -0
index ad25ad1e40412..4bdd5abc60880 100644
@@ -498,3 +498,4 @@ const char *nvme_trace_disk_name(struct trace_seq *p, char *name)
 }
 
 EXPORT_TRACEPOINT_SYMBOL_GPL(nvme_sq);
+EXPORT_TRACEPOINT_SYMBOL_GPL(nvme_dim);
drivers/nvme/host/trace.h +23 -0
index 4fb5922ffdac5..b7099b3026079 100644
@@ -161,6 +161,29 @@ TRACE_EVENT(nvme_sq,
 	)
 );
 
+TRACE_EVENT(nvme_dim,
+	TP_PROTO(u16 qid, int cpms, int epms, int cpe_ratio, u8 profile),
+	TP_ARGS(qid, cpms, epms, cpe_ratio, profile),
+	TP_STRUCT__entry(
+		__field(u16, qid)
+		__field(int, cpms)
+		__field(int, epms)
+		__field(int, cpe_ratio)
+		__field(u8, profile)
+	),
+	TP_fast_assign(
+		__entry->qid = qid;
+		__entry->cpms = cpms;
+		__entry->epms = epms;
+		__entry->cpe_ratio = cpe_ratio;
+		__entry->profile = profile;
+	),
+	TP_printk("qid=%u cpms=%d epms=%d cpe_ratio=%d profile=%u",
+		__entry->qid, __entry->cpms, __entry->epms,
+		__entry->cpe_ratio, __entry->profile
+	)
+);
+
 #endif /* _TRACE_NVME_H */
 
 #undef TRACE_INCLUDE_PATH

--

#2 lore raw
Quoted 16 lines

From: "Keith Busch"<[email protected]>
Date:  Tue, Aug 11, 2026, 04:55
Subject:  Re: [RESEND RFC PATCH v2] nvme-pci: add adaptive interrupt polling
To: "Fengnan Chang"<[email protected]>
Cc: <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, "Guzebing"<[email protected]>

Quoted 9 lines · Fengnan Chang

The idea behind this approach is: Let each I/O queue switch itself between interrupt and poll mode based on its own recent completion rate.
This version is still in the testing phase, and there are still some issues with the code implementation.  I releasing it now to see if the approach is generally acceptable.  If the approach looks good, I´ll continue to refine it and conduct more extensive testing.  The main implementation logic is in nvme_adaptive_sample and nvme_adaptive_irq_poll; you should focus on reviewing the implementation of these two functions.

Quoted 9 lines


Can we subscribe to the dynamic interrupt moderation (dim) library? I know it's generally used in conjuction with a hardware interrupt coalescing feature, but we can just do pure software with it too. The library provides a hill climb to adapt the policy at run time.
This is a quick PoC I put together. I haven't tested on fast devices, so I'm not sure if I've dialed in the profiles, but it's start of what I had in mind.

The code looks much cleaner when using dim, I'll see if I can replace the sample-and-poll logic I wrote myself with the dim library.
I ran a quick test on the POC patch and didn't see any performance improvements; in fact, there were quite a few regressions. Maybe some parameters need to be adjusted.

Quoted 498 lines


---

drivers/nvme/host/Kconfig +0 -0
index 31974c7dd20c9..9fad1c7b1f678 100644
@@ -6,6 +6,7 @@ config BLK_DEV_NVME

         tristate "NVM Express block device"
         depends on PCI && BLOCK
         select NVME_CORE
+        select DIMLIB
         help
           The NVM Express driver is for solid state drives directly connected to the PCI or PCI Express bus.  If you know you

drivers/nvme/host/pci.c +2 -0
index 8438c904ec496..ff0c8d74fae08 100644
@@ -9,6 +9,8 @@
  #include <linux/blkdev.h>
  #include <linux/blk-mq-dma.h>
  #include <linux/blk-integrity.h>
+#include <linux/delay.h>
+#include <linux/dim.h>
  #include <linux/dmi.h>
  #include <linux/init.h>
  #include <linux/interrupt.h>
@@ -82,6 +84,45 @@ struct quirk_entry {
  static int use_threaded_interrupts;
  module_param(use_threaded_interrupts, int, 0444);

drivers/nvme/host/pci.c +39 -0
+static unsigned int irq_poll_thresh = 7;
+module_param(irq_poll_thresh, uint, 0644);
+MODULE_PARM_DESC(irq_poll_thresh,
+        "outstanding depth after which a queue switches to threaded polling");
+
+static unsigned int irq_poll_spin = 7;
+module_param(irq_poll_spin, uint, 0644);
+MODULE_PARM_DESC(irq_poll_spin,
+        "poll iterations to spin (cpu_relax) before sleeping in the poll loop (zero based)");
+
+static unsigned int irq_poll_sleep_us = 20;
+static unsigned int irq_poll_idle_us = 80;
+static unsigned int irq_poll_idle_rounds = DIV_ROUND_UP(80, 20);
+
+static int irq_poll_us_set(const char *val, const struct kernel_param *kp)
+{
+        int ret = param_set_uint(val, kp);
+
+        if (ret)
+                return ret;
+
+        irq_poll_idle_rounds = irq_poll_sleep_us ?
+                DIV_ROUND_UP(irq_poll_idle_us, irq_poll_sleep_us) : 1;
+        return 0;
+}
+
+static const struct kernel_param_ops irq_poll_us_ops = {
+        .set = irq_poll_us_set,
+        .get = param_get_uint,
+};
+
+module_param_cb(irq_poll_sleep_us, &irq_poll_us_ops, &irq_poll_sleep_us, 0644);
+MODULE_PARM_DESC(irq_poll_sleep_us,
+        "microseconds to sleep between poll bursts (<=10 busy-delays, does not yield)");
+
+module_param_cb(irq_poll_idle_us, &irq_poll_us_ops, &irq_poll_idle_us, 0644);
+MODULE_PARM_DESC(irq_poll_idle_us,
+        "microseconds to wait for stragglers before handing a queue back to the IRQ path");
+

 static bool use_cmb_sqes = true;
 module_param(use_cmb_sqes, bool, 0444); MODULE_PARM_DESC(use_cmb_sqes, "use controller's memory buffer for I/O SQes");

drivers/nvme/host/pci.c +10 -0
@@ -381,11 +422,21 @@ struct nvme_queue {
          u16 qid;
          u8 cq_phase;
          u8 sqes;
+        /* Adaptive polling knobs, seeded from the irq_poll_* module params. */
+        unsigned int poll_thresh;
+        unsigned int poll_sleep_us;
+        unsigned int poll_idle_rounds;
+        unsigned int poll_budget;
+        /* Adaptive interrupt moderation (DIM) sampling state. */
+        struct dim dim;
+        u16 dim_events;                        /* cumulative interrupts (BIT_GAP-safe) */
+        u32 dim_comps;                        /* cumulative completions */
          unsigned long flags;
  #define NVMEQ_ENABLED                0
  #define NVMEQ_SQ_CMB                1
  #define NVMEQ_DELETE_ERROR        2
  #define NVMEQ_POLLED                3
+#define NVMEQ_POLLING                4
          __le32 *dbbuf_sq_db;
          __le32 *dbbuf_cq_db;
          __le32 *dbbuf_sq_ei;
@@ -1606,13 +1657,13 @@ static inline void nvme_update_cq_head(struct nvme_queue *nvmeq)
          }
  }

drivers/nvme/host/pci.c +2 -2
-static inline bool nvme_poll_cq(struct nvme_queue *nvmeq,
-                                struct io_comp_batch *iob)
+static inline int __nvme_poll_cq(struct nvme_queue *nvmeq,
+                                  struct io_comp_batch *iob, int budget)

 {
-        bool found = false;
+        int found = 0;

         while (nvme_cqe_pending(nvmeq)) {
-                found = true;
+                found++;
                 /*
                  * load-load control dependency between phase and the rest of
                  * the cqe requires a full read memory barrier

drivers/nvme/host/pci.c +2 -0
@@ -1620,6 +1671,8 @@ static inline bool nvme_poll_cq(struct nvme_queue *nvmeq,
                  dma_rmb();
                  nvme_handle_cqe(nvmeq, iob, nvmeq->cq_head);
                  nvme_update_cq_head(nvmeq);
+                if (budget && found == budget)
+                        break;
          }


         if (found)

drivers/nvme/host/pci.c +0 -0
@@ -1627,26 +1680,253 @@ static inline bool nvme_poll_cq(struct nvme_queue *nvmeq,
          return found;
  }

drivers/nvme/host/pci.c +160 -0
+/* budget == 0 means reap the whole queue. */
+static int nvme_poll_cq(struct nvme_queue *nvmeq, int budget)
+{
+        DEFINE_IO_COMP_BATCH(iob);
+        int found = __nvme_poll_cq(nvmeq, &iob, budget);
+
+        if (found && !rq_list_empty(&iob.req_list))
+                nvme_pci_complete_batch(&iob);
+        return found;
+}
+
+static inline unsigned int nvmeq_outstanding(struct nvme_queue *nvmeq)
+{
+        u16 sq_tail = READ_ONCE(nvmeq->last_sq_tail);
+        u16 cq_head = nvmeq->cq_head;
+
+        if (sq_tail >= cq_head)
+                return sq_tail - cq_head;
+        return nvmeq->q_depth - cq_head + sq_tail;
+}
+
+static inline bool nvmeq_cq_continue(struct nvme_queue *nvmeq)
+{
+        return nvmeq_outstanding(nvmeq) > nvmeq->poll_thresh;
+}
+
+static inline bool nvmeq_cq_idle(struct nvme_queue *nvmeq)
+{
+        return nvmeq->cq_head == READ_ONCE(nvmeq->last_sq_tail);
+}
+
+/*
+ * Interrupt-moderation profiles, ordered from least moderation (index 0: enter
+ * polling late, short sleep, brief linger -> lowest latency, most interrupts)
+ * to most moderation (enter early, long sleep, long linger -> fewest
+ * interrupts).  The hill-climb walks this table to keep completions-per-
+ * interrupt high, which is what bounds the interrupt rate.
+ */
+static const struct nvme_poll_prof {
+        u16 thresh;
+        u16 sleep_us;
+        u16 idle_rounds;
+        u16 budget;                /* hard-IRQ initial poll cap; 0 == reap all */
+} nvme_poll_prof[] = {
+        { 31,  0,  1,  0 },        /* drain inline: lowest latency, most interrupts */
+        { 15, 10,  2, 16 },
+        {  7, 20,  4,  8 },        /* start profile; matches irq_poll_* defaults */
+        {  3, 40,  8,  4 },
+        {  1, 80, 16,  2 },        /* reap a little, hand the bulk to the thread */
+};
+
+#define NVME_DIM_START_PROFILE 2
+
+static void nvme_apply_profile(struct nvme_queue *nvmeq)
+{
+        const struct nvme_poll_prof *p = &nvme_poll_prof[nvmeq->dim.profile_ix];
+
+        nvmeq->poll_thresh = p->thresh;
+        nvmeq->poll_sleep_us = p->sleep_us;
+        nvmeq->poll_idle_rounds = p->idle_rounds;
+        nvmeq->poll_budget = p->budget;
+}
+
+/* Mirror of rdma_dim_step() bounded to our profile table. */
+static int nvme_dim_step(struct dim *dim)
+{
+        if (dim->tune_state == DIM_GOING_RIGHT) {
+                if (dim->profile_ix == ARRAY_SIZE(nvme_poll_prof) - 1)
+                        return DIM_ON_EDGE;
+                dim->profile_ix++;
+                dim->steps_right++;
+        }
+        if (dim->tune_state == DIM_GOING_LEFT) {
+                if (dim->profile_ix == 0)
+                        return DIM_ON_EDGE;
+                dim->profile_ix--;
+                dim->steps_left++;
+        }
+        return DIM_STEPPED;
+}
+
+/* Mirror of rdma_dim_stats_compare(): completion rate first, then batching. */
+static int nvme_dim_stats_compare(struct dim_stats *curr, struct dim_stats *prev)
+{
+        if (!prev->cpms)
+                return DIM_STATS_SAME;
+
+        if (IS_SIGNIFICANT_DIFF(curr->cpms, prev->cpms))
+                return curr->cpms > prev->cpms ? DIM_STATS_BETTER :
+                                                 DIM_STATS_WORSE;
+
+        if (IS_SIGNIFICANT_DIFF(curr->cpe_ratio, prev->cpe_ratio))
+                return curr->cpe_ratio > prev->cpe_ratio ? DIM_STATS_BETTER :
+                                                           DIM_STATS_WORSE;
+
+        return DIM_STATS_SAME;
+}
+
+/* Mirror of rdma_dim_decision(); returns true if the profile changed. */
+static bool nvme_dim_decision(struct dim_stats *curr, struct dim *dim)
+{
+        int prev_ix = dim->profile_ix;
+        int stats_res;
+
+        stats_res = nvme_dim_stats_compare(curr, &dim->prev_stats);
+        switch (stats_res) {
+        case DIM_STATS_SAME:
+                if (curr->cpe_ratio <= 50 * prev_ix)
+                        dim->profile_ix = 0;
+                break;
+        case DIM_STATS_WORSE:
+                dim_turn(dim);
+                fallthrough;
+        case DIM_STATS_BETTER:
+                if (nvme_dim_step(dim) == DIM_ON_EDGE)
+                        dim_turn(dim);
+                break;
+        }
+
+        dim->prev_stats = *curr;
+        return dim->profile_ix != prev_ix;
+}
+
+/*
+ * Sample the completion/interrupt counters and, once per DIM_NEVENTS
+ * interrupts, compute the load stats.  Called only from the interrupt owner
+ * (never concurrently with the poll thread), so the counters have a single
+ * writer.  ktime_get() is taken only at a window boundary, not per interrupt.
+ *
+ * On each completed window the hill-climb picks a profile and, if it changed,
+ * applies it to nvmeq->poll_*.
+ */
+static void nvme_dim(struct nvme_queue *nvmeq)
+{
+        struct dim *dim = &nvmeq->dim;
+        struct dim_sample end;
+        struct dim_stats stats;
+
+        if (dim->state == DIM_START_MEASURE) {
+                dim_update_sample_with_comps(nvmeq->dim_events, 0, 0,
+                                             nvmeq->dim_comps, &dim->start_sample);
+                dim->state = DIM_MEASURE_IN_PROGRESS;
+                return;
+        }
+
+        /* Cheap gate: only recompute once a full window of events accrues. */
+        if ((u16)(nvmeq->dim_events - dim->start_sample.event_ctr) < DIM_NEVENTS)
+                return;
+
+        dim_update_sample_with_comps(nvmeq->dim_events, 0, 0, nvmeq->dim_comps,
+                                     &end);
+        if (dim_calc_stats(&dim->start_sample, &end, &stats)) {
+                if (nvme_dim_decision(&stats, dim))
+                        nvme_apply_profile(nvmeq);
+                trace_nvme_dim(nvmeq->qid, stats.cpms, stats.epms,
+                               stats.cpe_ratio, dim->profile_ix);
+        }
+        dim->start_sample = end;
+}
+

 static irqreturn_t nvme_irq(int irq, void *data) {
         struct nvme_queue *nvmeq = data;
-        DEFINE_IO_COMP_BATCH(iob);
+        struct nvme_dev *dev = nvmeq->dev;
+        struct pci_dev *pdev = to_pci_dev(dev->dev);
+        irqreturn_t ret = IRQ_NONE;
+        unsigned int idle = 0;

-        if (nvme_poll_cq(nvmeq, &iob)) {
-                if (!rq_list_empty(&iob.req_list))
-                        nvme_pci_complete_batch(&iob);
-                return IRQ_HANDLED;
+        for (;;) {
+                bool worked = false;
+                unsigned int i;

drivers/nvme/host/pci.c +34 -0
+
+                for (i = 0; i <= irq_poll_spin; i++) {
+                        int n = nvme_poll_cq(nvmeq, 0);
+
+                        if (n) {
+                                nvmeq->dim_comps += n;
+                                ret = IRQ_HANDLED;
+                                worked = true;
+                                idle = 0;
+                        }
+
+                        if (nvmeq_cq_idle(nvmeq))
+                                goto done;
+                        else if (need_resched())
+                                cond_resched();
+                        else
+                                cpu_relax();
+                }
+
+                if (worked || ++idle < nvmeq->poll_idle_rounds) {
+                        fsleep(nvmeq->poll_sleep_us);
+                        continue;
+                }
+done:
+                clear_bit(NVMEQ_POLLING, &nvmeq->flags);
+                if (!nvme_cqe_pending(nvmeq) ||
+                    test_and_set_bit(NVMEQ_POLLING, &nvmeq->flags))
+                        break;
+
+                if (need_resched())
+                        cond_resched();
+                else
+                        cpu_relax();
+                idle = 0;

         }
-        return IRQ_NONE;
+
+        if (pdev->msi_enabled)
+                writel(BIT(nvmeq->cq_vector), dev->bar + NVME_REG_INTMC);
+        return ret;
 }

 static irqreturn_t nvme_irq_check(int irq, void *data)
 {
         struct nvme_queue *nvmeq = data;
+        int found;
+
+        nvmeq->dim_events++;

-        if (nvme_cqe_pending(nvmeq))
+        if (test_and_set_bit(NVMEQ_POLLING, &nvmeq->flags))
+                return IRQ_HANDLED;

drivers/nvme/host/pci.c +21 -0
+
+        found = nvme_poll_cq(nvmeq, nvmeq->poll_budget);
+        nvmeq->dim_comps += found;
+        nvme_dim(nvmeq);
+
+        if (!found) {
+                clear_bit(NVMEQ_POLLING, &nvmeq->flags);
+                return IRQ_NONE;
+        }
+
+        /*
+         * Hand off to the poll thread when the queue is still deep, or when the
+         * budgeted initial poll left CQEs behind: their interrupt is already
+         * spent, so releasing here would strand them.
+         */
+        if (nvme_cqe_pending(nvmeq) || nvmeq_cq_continue(nvmeq)) {
+                struct nvme_dev *dev = nvmeq->dev;
+                struct pci_dev *pdev = to_pci_dev(dev->dev);
+
+                if (pdev->msi_enabled)
+                        writel(BIT(nvmeq->cq_vector), dev->bar + NVME_REG_INTMS);

                 return IRQ_WAKE_THREAD;
-        return IRQ_NONE;
+        }
+
+        clear_bit(NVMEQ_POLLING, &nvmeq->flags);
+        return IRQ_HANDLED;
 }

 /*

drivers/nvme/host/pci.c +2 -2
@@ -1663,7 +1943,7 @@ static void nvme_poll_irqdisable(struct nvme_queue *nvmeq)
          irq = pci_irq_vector(pdev, nvmeq->cq_vector);
          disable_irq(irq);
          spin_lock(&nvmeq->cq_poll_lock);
-        nvme_poll_cq(nvmeq, NULL);
+        __nvme_poll_cq(nvmeq, NULL, 0);
          spin_unlock(&nvmeq->cq_poll_lock);
          enable_irq(irq);
  }
@@ -1671,14 +1951,14 @@ static void nvme_poll_irqdisable(struct nvme_queue *nvmeq)
  static int nvme_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
  {
          struct nvme_queue *nvmeq = hctx->driver_data;
-        bool found;
+        int found;


         if (!test_bit(NVMEQ_POLLED, &nvmeq->flags) || !nvme_cqe_pending(nvmeq))
                 return 0;

         spin_lock(&nvmeq->cq_poll_lock);
-        found = nvme_poll_cq(nvmeq, iob);
+        found = __nvme_poll_cq(nvmeq, iob, 0); spin_unlock(&nvmeq->cq_poll_lock);

         return found;

drivers/nvme/host/pci.c +0 -0
@@ -2075,7 +2355,7 @@ static void nvme_reap_pending_cqes(struct nvme_dev *dev)


         for (i = dev->ctrl.queue_count - 1; i > 0; i--) { spin_lock(&dev->queues[i].cq_poll_lock);
-                nvme_poll_cq(&dev->queues[i], NULL);
+                __nvme_poll_cq(&dev->queues[i], NULL, 0); spin_unlock(&dev->queues[i].cq_poll_lock); }
 }

drivers/nvme/host/pci.c +0 -0
@@ -2171,13 +2451,8 @@ static int queue_request_irq(struct nvme_queue *nvmeq)
          struct pci_dev *pdev = to_pci_dev(nvmeq->dev->dev);
          int nr = nvmeq->dev->ctrl.instance;


-        if (use_threaded_interrupts) {
-                return pci_request_irq(pdev, nvmeq->cq_vector, nvme_irq_check,
-                                nvme_irq, nvmeq, "nvme%dq%d", nr, nvmeq->qid);
-        } else {
-                return pci_request_irq(pdev, nvmeq->cq_vector, nvme_irq,
-                                NULL, nvmeq, "nvme%dq%d", nr, nvmeq->qid);
-        }
+        return pci_request_irq(pdev, nvmeq->cq_vector, nvme_irq_check,
+                        nvme_irq, nvmeq, "nvme%dq%d", nr, nvmeq->qid); }

 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)

drivers/nvme/host/pci.c +11 -0
@@ -2188,6 +2463,17 @@ static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
          nvmeq->last_sq_tail = 0;
          nvmeq->cq_head = 0;
          nvmeq->cq_phase = 1;
+        nvmeq->poll_thresh = irq_poll_thresh;
+        nvmeq->poll_sleep_us = irq_poll_sleep_us;
+        nvmeq->poll_idle_rounds = irq_poll_idle_rounds;
+        nvmeq->poll_budget = nvme_poll_prof[NVME_DIM_START_PROFILE].budget;
+        memset(&nvmeq->dim, 0, sizeof(nvmeq->dim));
+        nvmeq->dim.priv = nvmeq;
+        nvmeq->dim.profile_ix = NVME_DIM_START_PROFILE;
+        nvmeq->dim.tune_state = DIM_GOING_RIGHT;
+        nvmeq->dim_events = 0;
+        nvmeq->dim_comps = 0;
+        clear_bit(NVMEQ_POLLING, &nvmeq->flags);
          nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
          memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq));
          nvme_dbbuf_init(dev, nvmeq, qid);
drivers/nvme/host/trace.c +0 -0
index ad25ad1e40412..4bdd5abc60880 100644
@@ -498,3 +498,4 @@ const char *nvme_trace_disk_name(struct trace_seq *p, char *name)
  }


 EXPORT_TRACEPOINT_SYMBOL_GPL(nvme_sq);

drivers/nvme/host/trace.c +1 -0
+EXPORT_TRACEPOINT_SYMBOL_GPL(nvme_dim);
drivers/nvme/host/trace.h +0 -0
index 4fb5922ffdac5..b7099b3026079 100644
@@ -161,6 +161,29 @@ TRACE_EVENT(nvme_sq,
          )
  );

drivers/nvme/host/trace.h +23 -0
+TRACE_EVENT(nvme_dim,
+        TP_PROTO(u16 qid, int cpms, int epms, int cpe_ratio, u8 profile),
+        TP_ARGS(qid, cpms, epms, cpe_ratio, profile),
+        TP_STRUCT__entry(
+                __field(u16, qid)
+                __field(int, cpms)
+                __field(int, epms)
+                __field(int, cpe_ratio)
+                __field(u8, profile)
+        ),
+        TP_fast_assign(
+                __entry->qid = qid;
+                __entry->cpms = cpms;
+                __entry->epms = epms;
+                __entry->cpe_ratio = cpe_ratio;
+                __entry->profile = profile;
+        ),
+        TP_printk("qid=%u cpms=%d epms=%d cpe_ratio=%d profile=%u",
+                __entry->qid, __entry->cpms, __entry->epms,
+                __entry->cpe_ratio, __entry->profile
+        )
+);
+

 #endif /* _TRACE_NVME_H */

 #undef TRACE_INCLUDE_PATH
--

maintainer
#3 lore raw
Quoted 5 lines · changfengnan

The code looks much cleaner when using dim, I'll see if I can replace the sample-and-poll logic I wrote myself with the dim library.
I ran a quick test on the POC patch and didn't see any performance improvements; in fact, there were quite a few regressions. Maybe some parameters need to be adjusted.

Yeah, I'm just now testing mid-tier devices and it's also performing a bit worse for high throughput workloads. But I hadn't really tried to tune the settings here, and maybe my criteria is all wrong. I was mainly trying to see if we can utilize the dim library before honing in on the right implementation details.

#4 lore raw
Quoted 12 lines

From: "Keith Busch"<[email protected]>
Date:  Wed, Aug 12, 2026, 04:30
Subject:  Re: [RESEND RFC PATCH v2] nvme-pci: add adaptive interrupt polling
To: "changfengnan"<[email protected]>
Cc: <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, "Guzebing"<[email protected]>

Quoted 5 lines · changfengnan

The code looks much cleaner when using dim, I'll see if I can replace the sample-and-poll logic I wrote myself with the dim library.
I ran a quick test on the POC patch and didn't see any performance improvements; in fact, there were quite a few regressions. Maybe some parameters need to be adjusted.

Quoted 6 lines


Yeah, I'm just now testing mid-tier devices and it's also performing a bit worse for high throughput workloads. But I hadn't really tried to tune the settings here, and maybe my criteria is all wrong. I was mainly trying to see if we can utilize the dim library before honing in on the right implementation details.

I tried modifying the original approach to use DIM, but the results were consistently poor. Using the original approach, my current optimization has managed to keep 4K random read backoff within 2% (tested on 10 different drive models), but when using DIM, the backoff rate is 10–15%. I believe there are several reasons for this:
1. The core of NVMe adaptive polling is determining when polling is more efficient, but DIM cannot answer this question. Although  irq and poll can be disguised as a DIM profile, this is essentially just borrowing the DIM framework—the core decision-making still requires writing your own baseline, thresholds, backoff, and re-baseline, so the code complexity and volume haven’t actually decreased.
2. The DIM state machine is relatively heavy, which reduces performance gains under I/O-intensive workloads.

So I tend to avoid using DIM. Please correct me if I'm wrong.

Quoted 1 line

#5 lore raw
Quoted 33 lines · changfengnan
Quoted 12 lines

From: "Keith Busch"<[email protected]>
Date:  Wed, Aug 12, 2026, 04:30
Subject:  Re: [RESEND RFC PATCH v2] nvme-pci: add adaptive interrupt polling
To: "changfengnan"<[email protected]>
Cc: <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, "Guzebing"<[email protected]>

Quoted 5 lines · changfengnan

The code looks much cleaner when using dim, I'll see if I can replace the sample-and-poll logic I wrote myself with the dim library.
I ran a quick test on the POC patch and didn't see any performance improvements; in fact, there were quite a few regressions. Maybe some parameters need to be adjusted.

Quoted 6 lines


Yeah, I'm just now testing mid-tier devices and it's also performing a bit worse for high throughput workloads. But I hadn't really tried to tune the settings here, and maybe my criteria is all wrong. I was mainly trying to see if we can utilize the dim library before honing in on the right implementation details.

I tried modifying the original approach to use DIM, but the results were consistently poor. Using the original approach, my current optimization has managed to keep 4K random read backoff within 2% (tested on 10 different drive models), but when using DIM, the backoff rate is 10–15%. I believe there are several reasons for this:
1. The core of NVMe adaptive polling is determining when polling is more efficient, but DIM cannot answer this question. Although  irq and poll can be disguised as a DIM profile, this is essentially just borrowing the DIM framework—the core decision-making still requires writing your own baseline, thresholds, backoff, and re-baseline, so the code complexity and volume haven’t actually decreased.
2. The DIM state machine is relatively heavy, which reduces performance gains under I/O-intensive workloads.

Quoted 1 line

So I tend to avoid using DIM. Please correct me if I'm wrong.

I also had a similar assesment on DIM. Emperically, with Keith's POC interrupts per IO drop from ~1.0 to ~0.29 but with a small performance regression (572K -> 557K IOPS). With your original approach they drop to ~0.03 with a 23% performance gain. The DIM machinery overhead maybe outweighing the partial interrupt reduction.

Quoted 3 lines
Quoted 2 lines

maintainer
#6 lore raw
Quoted 6 lines · Anuj Gupta

I also had a similar assesment on DIM. Emperically, with Keith's POC interrupts per IO drop from ~1.0 to ~0.29 but with a small performance regression (572K -> 557K IOPS). With your original approach they drop to ~0.03 with a 23% performance gain. The DIM machinery overhead maybe outweighing the partial interrupt reduction.

I may ultimately adandon this suggestion, but it looks like a major factor in performance loss was from using IRQ_WAKE_THREAD with sleep cycles instead of the softirq hrtimer. Just changing that is getting me back to performance parity, but since it's not any better, perhaps the hill climb is a worse algorithm than trying to reason out the delayed poll time directly.

#7 lore raw
In reply to Fengnan Chang
Quoted 22 lines · Fengnan Chang

Each Solidigm SB5PH27X038T device used for testing can deliver about 3.2M 4 KiB random-read IOPS. Four of them should be good for about 12.8M IOPS, but interrupt-driven completion tops out at 5.59M, only about 44% of that.

Polling gets rid of that cost, but polling every queue all the time burns CPU and hurts the sparse or bursty queues that interrupts handle just fine. So instead of a global switch, let each queue make the call on its own, from how fast it has been completing lately, and re-check often enough that the decision tracks the workload rather than a fixed tunable.

Each queue runs a small loop with three stages. First it samples its completion rate while still on interrupts. Only if that rate is high enough to fill a small batch inside a bounded latency window does it mask its own IRQ and start draining the CQ from a high-resolution timer, with each wait sized to collect roughly one batch. It keeps polling as long as it keeps up with that rate; the moment it stalls or slows down it turns the IRQ back on and backs off, waiting longer the further behind it fell. A queue that doesn't benefit drops back quickly and only gets retried once in a while, so polling stays on the queues that are actually interrupt-bound and everything else keeps running on the untouched IRQ path.

Quoted 7 lines

Measured with 4 KiB random reads on Solidigm SB5PH27X038T, adaptive on versus off:

                                   QD32      QD64      QD128
  one device, one job             +18.44%   +24.35%   +26.38%
  four devices, eight jobs        +83.76%   +99.02%   +96.26%

Did a quick test on single NVMe with QD64, one job, 4K random reads via io_uring, I see ~23% improvement: 569K -> 701K IOPS.

Do you expect the fixed batch size, sample size, maximum delay, episode length, and backoff multiplier to work across devices with different latency profiles and across different workloads, or should these values somehow adapt to observed queue behavior?

Quoted 7 lines

+/*
+ * Stop polling and turn the queue's IRQ back on. @elapsed is how long the
+ * episode ran after it started falling behind, or 0 if it ended cleanly.
+ * The bigger @elapsed is, the more completions we missed, and the longer we
+ * wait before sampling this queue again, so a queue that polling doesn't
+ * help is left alone most of the time.
+ */

@elapsed is the total polling-episode duration, not the time since the queue fell behind. It is then used with the total completion count to estimate cumulative deficit. Could the comment be reworded accordingly?

Quoted 36 lines
drivers/nvme/host/pci.c +36 -0
+/*
+ * Called from the IRQ handler after a reap that found something.  If we're
+ * still in backoff, just count it down.  Otherwise time how long
+ * NVME_ADAPTIVE_SAMPLE_CQES completions take to get the average gap between
+ * them.  If that looks worth polling (see the filter below) mask the IRQ and
+ * switch to poll mode; if not, leave the queue on interrupts.
+ */
+static void nvme_adaptive_sample(struct nvme_queue *nvmeq,
+				 unsigned int completions)
+{
+	struct nvme_adaptive_poll *adaptive = nvmeq->adaptive;
+	unsigned int sample;
+	unsigned long flags;
+	u64 delta, interval, now;
+
+	if (adaptive->retry_completions) {
+		if (adaptive->retry_completions != U64_MAX)
+			adaptive->retry_completions -= min_t(u64, completions,
+							 adaptive->retry_completions);
+		return;
+	}
+	if (!adaptive->start_ns) {
+		adaptive->start_ns = ktime_get_ns();
+		return;
+	}
+	adaptive->completions += completions;
+	if (adaptive->completions < NVME_ADAPTIVE_SAMPLE_CQES)
+		return;
+
+	now = ktime_get_ns();
+	delta = now - adaptive->start_ns;
+	sample = adaptive->completions;
+	adaptive->start_ns = now;
+	adaptive->completions = 0;
+	if (!delta || delta > (u64)NVME_ADAPTIVE_SAMPLE_CQES *
+			       NVME_ADAPTIVE_MAX_DELAY_NS)

drivers/nvme/host/pci.c static inline bool nvme_poll_cq(struct nvme_queue *nvmeq, · line 1897

Quoted 10 lines
drivers/nvme/host/pci.c +10 -0
+		return;
+	/*
+	 * Is this rate worth polling?  The 100/99 factor trims 1% off the gap so
+	 * a queue sitting right on the threshold isn't pulled in.  Skip it if
+	 * it's too slow to fill a batch within MAX_DELAY, and also skip it if
+	 * it's already fast enough to batch by itself.  The hardware's own
+	 * coalescing already handles that case, so leave it on interrupts.
+	 */
+	interval = div64_u64(delta * 100, sample * 99);
+	if (!interval || interval > NVME_ADAPTIVE_MAX_DELAY_NS ||

The comment says this rejects queues that cannot fill a target batch within MAX_DELAY, but this condition only checks whether one completion interval exceeds MAX_DELAY. Should this instead account for TARGET_BATCH or this comment is describing a different policy?

drivers/nvme/host/pci.c static inline bool nvme_poll_cq(struct nvme_queue *nvmeq, · line 1902

Quoted 5 lines
drivers/nvme/host/pci.c +5 -0
+	    (delta > NSEC_PER_MSEC &&
+	     interval <= NVME_ADAPTIVE_MAX_DELAY_NS /
+			 NVME_ADAPTIVE_TARGET_BATCH))
+		return;
+

For a normal 256-CQE sample with an interval of 2us or less, delta will be about 512us or less, so the 1ms condition prevents this exclusion from firing. Is this intended to detect only samples that substantially overshoot 256 CQEs? If so, could the comment make that narrower intent explicit?

#8 lore raw
Quoted 36 lines

From: "Anuj Gupta"<[email protected]>
Date:  Thu, Aug 13, 2026, 01:50
Subject:  Re: [RESEND RFC PATCH v2] nvme-pci: add adaptive interrupt polling
To: "Fengnan Chang"<[email protected]>
Cc: <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, <[email protected]>, "Guzebing"<[email protected]>

Quoted 20 lines · Fengnan Chang

Each Solidigm SB5PH27X038T device used for testing can deliver about 3.2M 4 KiB random-read IOPS.  Four of them should be good for about 12.8M IOPS, but interrupt-driven completion tops out at 5.59M, only about 44% of that.
Polling gets rid of that cost, but polling every queue all the time burns CPU and hurts the sparse or bursty queues that interrupts handle just fine. So instead of a global switch, let each queue make the call on its own, from how fast it has been completing lately, and re-check often enough that the decision tracks the workload rather than a fixed tunable.

Each queue runs a small loop with three stages.  First it samples its completion rate while still on interrupts.  Only if that rate is high enough to fill a small batch inside a bounded latency window does it mask its own IRQ and start draining the CQ from a high-resolution timer, with each wait sized to collect roughly one batch.  It keeps polling as long as it keeps up with that rate; the moment it stalls or slows down it turns the IRQ back on and backs off, waiting longer the further behind it fell. A queue that doesn't benefit drops back quickly and only gets retried once in a while, so polling stays on the queues that are actually interrupt-bound and everything else keeps running on the untouched IRQ

Quoted 9 lines

path.

Measured with 4 KiB random reads on Solidigm SB5PH27X038T, adaptive on versus off:

                                   QD32      QD64      QD128 one device, one job             +18.44%   +24.35%   +26.38% four devices, eight jobs        +83.76%   +99.02%   +96.26%

Quoted 8 lines


Did a quick test on single NVMe with QD64, one job, 4K random reads via io_uring, I see ~23% improvement: 569K -> 701K IOPS.

Do you expect the fixed batch size, sample size, maximum delay, episode length, and backoff multiplier to work across devices with different latency profiles and across different workloads, or should these values somehow adapt to observed queue behavior?

Thank you for sharing the data. My goal is for these parameters to be applicable to all disk and workload scenarios, but more testing is needed in practice.
I’ve made some adjustments to the parameters and logic in the version I’m currently developing, and it looks pretty good so far.

Attached is the version I'm currently developing. If you have time to take a look or test it and offer some feedback, I'd really appreciate it.

Quoted 8 lines

Quoted 7 lines

+/*
+ * Stop polling and turn the queue's IRQ back on.  @elapsed is how long the
+ * episode ran after it started falling behind, or 0 if it ended cleanly.
+ * The bigger @elapsed is, the more completions we missed, and the longer we
+ * wait before sampling this queue again, so a queue that polling doesn't
+ * help is left alone most of the time.
+ */

Quoted 4 lines


@elapsed is the total polling-episode duration, not the time since the queue fell behind. It is then used with the total completion count to estimate cumulative deficit. Could the comment be reworded accordingly?

Sorry, there are some issues with the comments in this version. I'll fix them in the next version.

Quoted 44 lines

Quoted 43 lines
(quoted diff) +43 -0
+/*
+ * Called from the IRQ handler after a reap that found something.  If we're
+ * still in backoff, just count it down.  Otherwise time how long
+ * NVME_ADAPTIVE_SAMPLE_CQES completions take to get the average gap between
+ * them.  If that looks worth polling (see the filter below) mask the IRQ and
+ * switch to poll mode; if not, leave the queue on interrupts.
+ */
+static void nvme_adaptive_sample(struct nvme_queue *nvmeq,
+                                 unsigned int completions)
+{
+        struct nvme_adaptive_poll *adaptive = nvmeq->adaptive;
+        unsigned int sample;
+        unsigned long flags;
+        u64 delta, interval, now;
+
+        if (adaptive->retry_completions) {
+                if (adaptive->retry_completions != U64_MAX)
+                        adaptive->retry_completions -= min_t(u64, completions,
+                                                         adaptive->retry_completions);
+                return;
+        }
+        if (!adaptive->start_ns) {
+                adaptive->start_ns = ktime_get_ns();
+                return;
+        }
+        adaptive->completions += completions;
+        if (adaptive->completions < NVME_ADAPTIVE_SAMPLE_CQES)
+                return;
+
+        now = ktime_get_ns();
+        delta = now - adaptive->start_ns;
+        sample = adaptive->completions;
+        adaptive->start_ns = now;
+        adaptive->completions = 0;
+        if (!delta || delta > (u64)NVME_ADAPTIVE_SAMPLE_CQES *
+                               NVME_ADAPTIVE_MAX_DELAY_NS)
+                return;
+        /*
+         * Is this rate worth polling?  The 100/99 factor trims 1% off the gap so
+         * a queue sitting right on the threshold isn't pulled in.  Skip it if
+         * it's too slow to fill a batch within MAX_DELAY, and also skip it if
+         * it's already fast enough to batch by itself.  The hardware's own
+         * coalescing already handles that case, so leave it on interrupts.
Quoted 8 lines
Quoted 3 lines

+         */
+        interval = div64_u64(delta * 100, sample * 99);
+        if (!interval || interval > NVME_ADAPTIVE_MAX_DELAY_NS ||


The comment says this rejects queues that cannot fill a target batch within MAX_DELAY, but this condition only checks whether one completion interval exceeds MAX_DELAY. Should this instead account for TARGET_BATCH or this comment is describing a different policy?

TARGET_BATCH will no longer be used in the next version.

Quoted 6 lines

Quoted 5 lines

+            (delta > NSEC_PER_MSEC &&
+             interval <= NVME_ADAPTIVE_MAX_DELAY_NS /
+                         NVME_ADAPTIVE_TARGET_BATCH))
+                return;
+

Quoted 6 lines


For a normal 256-CQE sample with an interval of 2us or less, delta will be about 512us or less, so the 1ms condition prevents this exclusion from firing. Is this intended to detect only samples that substantially overshoot 256 CQEs? If so, could the comment make that narrower intent explicit?

I did it that way before because I thought that if the interrupt mode could process a CQE in 2 μs, that would mean the interrupt mode was already very fast. I’ve removed that check from the version I’m currently developing.

Quoted 1 line

From c3d9989d99c901abde1397651801309df3e11347 Mon Sep 17 00:00:00 2001
From: Fengnan Chang <[email protected]>
Date: Tue, 11 Aug 2026 20:22:27 +0800
Subject: [PATCH] nvme-pci: add adaptive interrupt polling

Add opt-in adaptive polling for nvme, measure an IRQ completion-rate baseline over 8192 CQEs, then admit a bounded polling trial only when the observed rate can sustain the fixed 10 us polling period.

---
 Documentation/ABI/testing/sysfs-nvme |  15 +
 drivers/nvme/host/Kconfig            |   1 +
 drivers/nvme/host/pci.c              | 564 +++++++++++++++++++++++++--
 3 files changed, 554 insertions(+), 26 deletions(-)
Documentation/ABI/testing/sysfs-nvme +15 -0
index 499d5f843cd43..309d59dc6b872 100644
@@ -11,3 +11,18 @@ Description:
 		(REPLACETLSPSK) with the target. After a reauthentication
 		the value returned by tls_configured_key will be the new
 		serial.
+
+What:		/sys/class/nvme/nvmeX/adaptive_irq_polling
+Date:		August 2026
+KernelVersion:	7.2
+Contact:	Linux NVMe mailing list <[email protected]>
+Description:
+		Enable (1) or disable (0) adaptive IRQ polling on eligible I/O
+		queues of one PCI NVMe controller.  Changing the mode freezes its
+		namespace request queues and waits for all outstanding namespace I/O
+		to complete before updating the queue IRQ state.  Writes fail with
+		EBUSY unless the controller is live.
+
+		The attribute is not available with threaded NVMe interrupts.  The
+		use_adaptive_irq_polling module parameter supplies only the initial
+		value for newly probed controllers.
drivers/nvme/host/Kconfig +1 -0
index 31974c7dd20c9..22164b901da85 100644
@@ -5,6 +5,7 @@ config NVME_CORE
 config BLK_DEV_NVME
 	tristate "NVM Express block device"
 	depends on PCI && BLOCK
+	select IRQ_POLL
 	select NVME_CORE
 	help
 	  The NVM Express driver is for solid state drives directly
drivers/nvme/host/pci.c +538 -26

741 lines not on this page · raw message

Signature · 1 line
2.39.5 (Apple Git-154)