Add adaptive NVMe link rate switching function
Subsystems (3)
cover Add adaptive NVMe link rate switching function
From: Liao Xuan <[email protected]>
NVMe devices are commonly left trained at the maximum PCIe link rate even when there is little or no I/O activity, which wastes power in both the device and the surrounding platform.
This series adds adaptive PCIe link rate switching to the NVMe host driver. The link is downgraded to a configurable minimum rate when I/O activity is low to save power, and upgraded back to the maximum supported rate as soon as the workload requires it, so that peak performance is maintained under load.
The amount of transferred data is accumulated on the submission path with per-CPU counters and evaluated by a per-controller timer. The switch threshold is derived from the bandwidth of the minimum and maximum link rates such that the extra time required to transfer the data at the minimum rate does not exceed the estimated link retraining time. The controller queues are frozen while the link is retrained and resumed afterwards, so no I/O is lost or times out during the switch.
The main functions of each patch are as follows:
1. Patch 1 adds the core switching functionality. It uses the target link speed interface of the PCIe bandwidth controller, which is exported for this purpose.
2. Patch 2 adds hysteresis and idle detection to the switching policy. The link is upgraded immediately once the threshold is exceeded, but only downgraded after a number of consecutive below-threshold windows, which prevents excessive rate toggling under fluctuating workloads. Monitoring is stopped after a period of inactivity and re-armed by the next I/O.
3. Patch 3 exposes the switching parameters (enable, monitor_interval, min_speed, up_threshold, down_threshold) via sysfs so that the power/performance trade-off can be tuned at runtime without a reboot.
The feature is currently enabled on Hygon platforms.
Liao Xuan (3):
nvme: Add adaptive PCIe link rate switching function
nvme: Add hysteresis and idle detection to link rate switching
nvme: Expose link rate switching tunables via sysfs
drivers/nvme/host/Kconfig | 10 + drivers/nvme/host/Makefile | 1 + drivers/nvme/host/core.c | 4 + drivers/nvme/host/nvme.h | 50 ++++ drivers/nvme/host/pci.c | 4 + drivers/nvme/host/speed_switch.c | 424 +++++++++++++++++++++++++++++++ drivers/nvme/host/sysfs.c | 143 +++++++++++ drivers/pci/pcie/bwctrl.c | 1 + 8 files changed, 637 insertions(+) create mode 100644 drivers/nvme/host/speed_switch.c
Signature · 1 line
2.43.0
PATCH 1/3 nvme: Add adaptive PCIe link rate switching function
Add support for dynamically adjusting the PCIe link rate of NVMe devices based on I/O activity. The link is downgraded to a configurable minimum rate during periods of low activity to save power, and upgraded to the maximum supported rate as soon as the workload exceeds a computed threshold, so that peak performance is maintained under load.
The amount of transferred data is accumulated on the I/O submission path and aggregated by a per-controller timer. The threshold is derived from the bandwidth of the minimum and maximum rates such that the extra time required to transfer the data at the minimum rate does not exceed the estimated link retraining time.
The feature is currently only supported on Hygon platforms.
Four NVMe devices were tested on the link with this patch. The power benefit was measured by sampling the voltage and current of the power monitor every 1 second, each run lasted 3 minutes and the test was repeated 5 times.
Test run Power Benefit(w) 1 5.3236 2 5.2285 3 5.4176 4 5.4538 5 5.3444 Average 5.3536
The adaptive link rate switching saves about 5.3w of system power on average.
The feature was tested with Gen1 as the minimum link rate. The workload runs 10 seconds of random read followed by 0.5 seconds of idle, repeated 100 times.
Avg IOPS (k) Avg BW (GiB/s) Avg clat (us) With speed switching 2671.2 10.19 378.1 Without speed switching 2681.5 10.23 377.0
The differences are within measurement noise (< 0.5%), which shows that the adaptive link rate switching does not degrade the baseline performance and keeps the I/O stable.
In summary, the adaptive link rate switching keeps the I/O performance essentially unchanged (the differences in IOPS, bandwidth and latency are all within 0.5% measurement noise) while saving about 5w of system power, providing an effective way to reduce the platform power consumption under light I/O without sacrificing throughput or latency.
--- drivers/nvme/host/Kconfig | 10 + drivers/nvme/host/Makefile | 1 + drivers/nvme/host/core.c | 4 + drivers/nvme/host/nvme.h | 42 ++++ drivers/nvme/host/pci.c | 4 + drivers/nvme/host/speed_switch.c | 371 +++++++++++++++++++++++++++++++ drivers/pci/pcie/bwctrl.c | 1 + 7 files changed, 433 insertions(+) create mode 100644 drivers/nvme/host/speed_switch.c
drivers/nvme/host/Kconfig +10 -0
@@ -134,3 +134,13 @@ config NVME_APPLE To compile this driver as a module, choose M here: the module will be called nvme-apple. + +config NVME_SPEED_SWITCH + bool "NVMe adaptive PCIe link rate switching" + depends on BLK_DEV_NVME && X86 + help + This provides support for dynamic PCIe link rate switching for NVMe + devices. When enabled, the NVMe driver can dynamically adjust the + PCIe link speed and width based on workload requirement. + + If unsure, say N.
drivers/nvme/host/Makefile +1 -0
@@ -18,6 +18,7 @@ nvme-core-$(CONFIG_BLK_DEV_ZONED) += zns.o nvme-core-$(CONFIG_FAULT_INJECTION_DEBUG_FS) += fault_inject.o nvme-core-$(CONFIG_NVME_HWMON) += hwmon.o nvme-core-$(CONFIG_NVME_HOST_AUTH) += auth.o +nvme-core-$(CONFIG_NVME_SPEED_SWITCH) += speed_switch.o nvme-y += pci.o
drivers/nvme/host/core.c +4 -0
@@ -4627,6 +4627,7 @@ static void nvme_scan_work(struct work_struct *work)/* Re-read the ANA log page to not miss updates */ queue_work (nvme_wq, &ctrl->ana_work);#endif +nvme_speed_switch_start (ctrl); }/*
@@ -5051,6 +5052,7 @@ EXPORT_SYMBOL_GPL(nvme_remove_io_tag_set);void nvme_stop_ctrl (struct nvme_ctrl *ctrl) { +nvme_speed_switch_exit (ctrl);nvme_mpath_stop (ctrl);nvme_auth_stop (ctrl);nvme_stop_failfast_work (ctrl);
@@ -5266,6 +5268,8 @@ int nvme_add_ctrl(struct nvme_ctrl *ctrl)nvme_fault_inject_init (&ctrl->fault_inject,dev_name (ctrl->device));nvme_get_ctrl (ctrl); +nvme_speed_switch_init (ctrl); +return 0 ; }EXPORT_SYMBOL_GPL (nvme_add_ctrl);
drivers/nvme/host/nvme.h +42 -0
56 lines not on this page · raw message
drivers/nvme/host/pci.c +4 -0
@@ -1455,6 +1455,9 @@ static blk_status_t nvme_queue_rq(struct blk_mq_hw_ctx *hctx, ret =nvme_prep_rq (req);if (unlikely (ret))return ret; + +nvme_update_io_stats (&dev->ctrl, req); +spin_lock (&nvmeq->sq_lock);nvme_sq_copy_cmd (nvmeq, &iod->cmd);nvme_write_sq_db (nvmeq, bd->last);
@@ -1473,6 +1476,7 @@ static void nvme_submit_cmds(struct nvme_queue *nvmeq, struct rq_list *rqlist)while ((req =rq_list_pop (rqlist))) {struct nvme_iod *iod =blk_mq_rq_to_pdu (req); +nvme_update_io_stats (&nvmeq->dev->ctrl, req);nvme_sq_copy_cmd (nvmeq, &iod->cmd); }nvme_write_sq_db (nvmeq, true);
drivers/nvme/host/speed_switch.c new file +371 -0
371 lines not on this page · raw message
drivers/pci/pcie/bwctrl.c +1 -0
@@ -178,6 +178,7 @@ int pcie_set_target_speed(struct pci_dev *port, enum pci_bus_speed speed_req,return ret; } +EXPORT_SYMBOL_GPL (pcie_set_target_speed);static void pcie_bwnotif_enable (struct pcie_device *srv) {
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH 1/3] nvme: Add adaptive PCIe link rate switching function
Thank you for your contribution! Sashiko AI review found 9 potential issue(s) to consider: - [High] nvme: UAF on per-CPU stats and timer re-arming race during teardown - [High] nvme: infinite link…
Thank you for your contribution! Sashiko AI review found 9 potential issue(s) to consider:
- [High] nvme: UAF on per-CPU stats and timer re-arming race during teardown
- [High] nvme: infinite link retrain loop on rollback success
- [High] nvme: TOCTOU data race on sw->target_speed causes link mismatch
- [High] nvme: speed switch timer runs during suspend causing deadlocks
- [High] nvme: missing memalloc_noio_save() around queue freeze
- [High] nvme: nvme_unfreeze clears NVME_CTRL_FROZEN prematurely
- [Medium] nvme: synchronous PCIe config space read on block I/O fast path
- [Medium] nvme: data race when zeroing remote per-CPU statistics
- [Medium] nvme: speed switch permanently disabled after controller reset --
commit 3ad252ce0a89b0f36c40c41b569dd1f1382434b5
Author: Liao Xuan <[email protected]>
nvme: Add adaptive PCIe link rate switching function
This commit introduces dynamic adjustment of the PCIe link rate for NVMe devices based on I/O activity. The link speed is downgraded during periods of low activity to save power and upgraded to maximum when I/O load crosses a calculated threshold.
Quoted 4 lines
drivers/nvme/host/core.c +0
-0
[ ... ]
drivers/nvme/host/core.c EXPORT_SYMBOL_GPL(nvme_remove_io_tag_set); · line 5095
Quoted 7 lines
drivers/nvme/host/core.c +1
-0@@ -5089,6 +5090,7 @@ EXPORT_SYMBOL_GPL(nvme_remove_io_tag_set);void nvme_stop_ctrl (struct nvme_ctrl *ctrl) { +nvme_speed_switch_exit (ctrl);nvme_mpath_stop (ctrl);nvme_auth_stop (ctrl);
[Severity: Medium]
Since nvme_add_ctrl() only initializes the speed switch once during device probe, will calling nvme_speed_switch_exit() during nvme_stop_ctrl() permanently disable the feature after the first controller reset? The reset recovery path does not appear to call nvme_speed_switch_init() again.
[ ... ]
Quoted 5 lines
drivers/nvme/host/speed_switch.c new file +0
-0
[ ... ]
drivers/nvme/host/speed_switch.c line 86
Quoted 11 lines
drivers/nvme/host/speed_switch.c new file +11
-0+static void nvme_speed_switch_work (struct work_struct *work) +{ + struct nvme_speed_switch *sw = container_of(work, struct nvme_speed_switch, work); + struct nvme_ctrl *ctrl = container_of(sw, struct nvme_ctrl, speed_switch); +struct pci_dev *pdev =to_pci_dev (ctrl->dev); +struct pci_dev *bridge = pdev->bus->self; +u8 cur_speed =READ_ONCE (sw->cur_speed); +int ret; + +if (nvme_ctrl_state (ctrl) !=NVME_CTRL_LIVE ) +return ;
[Severity: High]
Is this guard sufficient to prevent operations during host-managed suspend? The controller state remains NVME_CTRL_LIVE during host-managed suspend, which might allow the timer to fire, schedule this work, and attempt to access the PCIe configuration space of a suspended device.
drivers/nvme/host/speed_switch.c line 93
Quoted 7 lines
drivers/nvme/host/speed_switch.c new file +7
-0+ +/* Freeze I/O to avoid timeouts during link retraining. */ +nvme_start_freeze (ctrl); +nvme_wait_freeze (ctrl); + + ret =pcie_set_target_speed (bridge,nvme_speed_to_bus_speed (sw->target_speed), + true);
[Severity: High]
Should this section be protected by memalloc_noio_save() and memalloc_noio_restore()? Code executing while a block queue is frozen typically needs NOIO protection. Otherwise, memory reclaim interrupting this section could attempt to flush dirty pages to the frozen NVMe device, leading to a system deadlock under memory pressure.
[Severity: High]
Could reading sw->target_speed here introduce a TOCTOU data race? This value is read to program the hardware, but read again below to update sw->cur_speed.
Quoted 4 lines
drivers/nvme/host/speed_switch.c new file +4
-0+if (ret) { +dev_warn (ctrl->device, +"failed to set target rate Gen%u (%d), trying rollback to Gen%u\n" , + sw->target_speed, ret, cur_speed);
drivers/nvme/host/speed_switch.c line 107
Quoted 10 lines
drivers/nvme/host/speed_switch.c new file +10
-0+ ret =pcie_set_target_speed (bridge,nvme_speed_to_bus_speed (cur_speed), + true); +if (ret) { +dev_err (ctrl->device, +"rollback to Gen%u failed (%d), disabling speed switch\n" , + cur_speed, ret); +WRITE_ONCE (sw->enabled, false); +nvme_unfreeze (ctrl); +return ; + }
[Severity: High]
If the pcie_set_target_speed() rollback succeeds, the code omits disabling the speed switch. Since the function returns while sw->enabled remains true, won't the timer fire again 100ms later, see a target speed mismatch, and repeatedly fail, freezing the queues continuously?
drivers/nvme/host/speed_switch.c line 110
Quoted 3 lines
drivers/nvme/host/speed_switch.c new file +3
-0+ }else { +WRITE_ONCE (sw->cur_speed, sw->target_speed); + }
[Severity: High]
If the timer concurrently updates sw->target_speed between the hardware programming step and this write, sw->cur_speed will receive the new value while the hardware was programmed to the old value. Will this cause the hardware link speed to become permanently out-of-sync with the software state?
drivers/nvme/host/speed_switch.c
Quoted 2 lines
drivers/nvme/host/speed_switch.c new file +2
-0+ +nvme_unfreeze (ctrl);
[Severity: High]
Is it safe to unconditionally call nvme_unfreeze() here? nvme_unfreeze() explicitly clears the NVME_CTRL_FROZEN bit. If this work finishes while a concurrent controller reset is ongoing, it clears the flag prematurely, which could break the reset state machine and allow namespaces to be added concurrently with the reset.
Quoted 3 lines
drivers/nvme/host/speed_switch.c new file +3
-0+dev_dbg (ctrl->device,"link rate changed to Gen%u\n" , +READ_ONCE (sw->cur_speed)); +}
[ ... ]
Quoted 10 lines
drivers/nvme/host/speed_switch.c new file +10
-0+/* Called on the I/O submission path to accumulate the transferred bytes. */ +void nvme_update_io_stats (struct nvme_ctrl *ctrl,struct request *req) +{ +struct nvme_speed_switch *sw = &ctrl->speed_switch; +struct nvme_speed_switch_stats *stat; +enum req_op op =req_op (req); +unsigned int bytes =blk_rq_bytes (req); + +if (!READ_ONCE (sw->enabled)) +return ;
drivers/nvme/host/speed_switch.c line 193
Quoted 10 lines
drivers/nvme/host/speed_switch.c new file +10
-0+ +if (op !=REQ_OP_READ && op !=REQ_OP_WRITE ) +return ; + +if (!sw->stats) { +dev_dbg (ctrl->device,"I/O statistics not allocated, skip accounting\n" ); +return ; + } + + stat =get_cpu_ptr (sw->stats);
[Severity: High]
Could the I/O thread locklessly dereference sw->stats after it has been freed? If the I/O thread is preempted right after checking sw->enabled, and a concurrent controller reset calls nvme_speed_switch_exit() (which frees sw->stats), the I/O thread would resume and access the freed memory here.
drivers/nvme/host/speed_switch.c line 206
Quoted 13 lines
drivers/nvme/host/speed_switch.c new file +13
-0+if (op ==REQ_OP_READ ) + stat->read_bytes += bytes; +else + stat->write_bytes += bytes; +put_cpu_ptr (sw->stats); + +if (atomic_cmpxchg (&sw->timer_active,NVME_SPEED_TIMER_INACTIVE , +NVME_SPEED_TIMER_ACTIVE ) !=NVME_SPEED_TIMER_INACTIVE ) +return ; + +/* First I/O of the activity period: compute the threshold and arm the timer. */ +WRITE_ONCE (sw->threshold,nvme_calc_speed_threshold (sw, +pcie_get_width_cap (to_pci_dev (ctrl->dev))));
[Severity: Medium]
Does pcie_get_width_cap() perform a synchronous read of the PCIe configuration space? Evaluating this on the first I/O of an activity period within the block I/O submission fast path might introduce severe latency spikes for affected requests.
drivers/nvme/host/speed_switch.c line 214
Quoted 8 lines
drivers/nvme/host/speed_switch.c new file +8
-0+if (!READ_ONCE (sw->threshold)) { +dev_warn (ctrl->device, +"failed to compute speed switch threshold, keeping current rate\n" ); +atomic_set (&sw->timer_active,NVME_SPEED_TIMER_INACTIVE ); +return ; + } +mod_timer (&sw->timer, jiffies +msecs_to_jiffies (READ_ONCE (sw->monitor_interval))); +}
[Severity: High]
Following up on the preemption scenario, if nvme_speed_switch_exit() completes its teardown (including timer_delete_sync()), will this mod_timer() call re-arm the timer after teardown has finished, leading to a delayed use-after-free when the timer fires?
[ ... ]
Quoted 5 lines
drivers/nvme/host/speed_switch.c new file +5
-0+static int nvme_check_io_and_decide_speed (struct nvme_speed_switch *sw) +{ + struct nvme_ctrl *ctrl = container_of(sw, struct nvme_ctrl, speed_switch); +u64 read_bytes =0 , write_bytes =0 ; +unsigned long read_kb, write_kb;
drivers/nvme/host/speed_switch.c line 248
Quoted 10 lines
drivers/nvme/host/speed_switch.c new file +10
-0+int cpu; + +for_each_possible_cpu (cpu) { +struct nvme_speed_switch_stats *stat =per_cpu_ptr (sw->stats, cpu); + + read_bytes += stat->read_bytes; + write_bytes += stat->write_bytes; + stat->read_bytes =0 ; + stat->write_bytes =0 ; + }
[Severity: Medium]
Could zeroing these remote per-CPU statistics lead to a data race? The timer callback iterates over all CPUs and assigns 0 to stat->read_bytes and stat->write_bytes of remote CPUs concurrently while the I/O submission path might be updating these variables. Without atomic operations or synchronization, this could cause incorrect statistics and dropped increments.
[ ... ]
Quoted 5 lines
drivers/nvme/host/speed_switch.c new file +5
-0+void nvme_speed_switch_exit (struct nvme_ctrl *ctrl) +{ +struct nvme_speed_switch *sw = &ctrl->speed_switch; + +if (!sw->initialized)
drivers/nvme/host/speed_switch.c line 371
Quoted 10 lines
drivers/nvme/host/speed_switch.c new file +10
-0+return ; + + sw->initialized = false; +WRITE_ONCE (sw->enabled, false); +timer_delete_sync (&sw->timer); +cancel_work_sync (&sw->work); + +free_percpu (sw->stats); + sw->stats =NULL ; +}
[Severity: High]
This teardown routine frees sw->stats and uses timer_delete_sync(), but does this adequately prevent the timer from being asynchronously re-armed by an I/O thread that had already passed the sw->enabled check?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH 2/3 nvme: Add hysteresis and idle detection to link rate switching
In reply to Liao XuanThe rate switching decision currently toggles the link rate in every monitoring window based on the I/O of that window alone, which can cause excessive rate switching when the workload fluctuates around the threshold.
Add counters that require the threshold to be exceeded for a consecutive number of windows before the rate is upgraded, and to stay below the threshold for a consecutive number of windows before it is downgraded. The upgrade happens immediately (threshold 0 by default) so that latency is not sacrificed, while the downgrade requires 10 consecutive windows.
Monitoring is stopped after 10 seconds of inactivity and is re-armed by the next I/O.
--- drivers/nvme/host/nvme.h | 5 +++ drivers/nvme/host/speed_switch.c | 52 ++++++++++++++++++++++++++++---- 2 files changed, 51 insertions(+), 6 deletions(-)
drivers/nvme/host/nvme.h +5 -0
@@ -346,6 +346,11 @@ struct nvme_speed_switch {u8 min_speed;u32 monitor_interval;/* ms */ u32 threshold;/* KB */ +u32 up_cnt; +u32 down_cnt; +u32 up_threshold; +u32 down_threshold; +u32 idle_cnt;struct timer_list timer;struct work_struct work;struct nvme_speed_switch_stats __percpu *stats;
drivers/nvme/host/speed_switch.c +46 -6
93 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH 2/3] nvme: Add hysteresis and idle detection to link rate switching
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] nvme: data race between timer and worker causes stuck link rate --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] nvme: data race between timer and worker causes stuck link rate
--
commit 281ed4a8d51a45615fb54b154554270a5683089c
Author: Liao Xuan <[email protected]>
nvme: Add hysteresis and idle detection to link rate switching
This patch adds counters to avoid excessive rate switching when the workload fluctuates, requiring consecutive windows above or below a threshold to trigger an upgrade or downgrade. It also stops monitoring after 10 seconds of inactivity.
Quoted 4 lines
drivers/nvme/host/speed_switch.c +0
-0
[ ... ]
Quoted 32 lines
drivers/nvme/host/speed_switch.c +21
-1@@ -247,31 +252,62 @@ static int nvme_check_io_and_decide_speed(struct nvme_speed_switch *sw) stat->write_bytes =0 ; } +if (read_bytes || write_bytes) { + *io_activity = true; + sw->idle_cnt =0 ; + }else { + sw->idle_cnt++; + } + +/* Stop monitoring after 10 seconds of inactivity (100 windows of 100ms). */ +if (sw->idle_cnt >=100 ) + *io_activity = false; + read_kb = read_bytes /1024 ; write_kb = write_bytes /1024 ;dev_dbg (ctrl->device,"I/O in window: read=%lu KB, write=%lu KB, threshold=%u KB\n" , read_kb, write_kb,READ_ONCE (sw->threshold)); -if (read_kb >= sw->threshold || write_kb >= sw->threshold) +if (read_kb >= sw->threshold || write_kb >= sw->threshold) { + sw->up_cnt++; + sw->down_cnt =0 ; + }else { + sw->down_cnt++; + sw->up_cnt =0 ; + } + +if (sw->up_cnt >READ_ONCE (sw->up_threshold)) { + sw->up_cnt =0 ;
drivers/nvme/host/speed_switch.c static int nvme_check_io_and_decide_speed(struct nvme_speed_switch *sw) · line 290
Quoted 10 lines
drivers/nvme/host/speed_switch.c +7
-1return sw->max_speed; + } + +if (sw->down_cnt >READ_ONCE (sw->down_threshold) || !*io_activity) { + sw->down_cnt =0 ; +return sw->min_speed; + } -return sw->min_speed; +return READ_ONCE (sw->cur_speed);
[Severity: High]
Does returning cur_speed here cause a data race between the timer and the worker that leaves the hardware link rate permanently throttled?
If the timer previously returned min_speed and scheduled nvme_speed_switch_work(), the worker will freeze the queues and begin a slow hardware transition via pcie_set_target_speed().
While the worker is blocked on the hardware transition, I/O is 0 because the queues are frozen. The concurrent timer will increment down_cnt, but since it is below down_threshold, it will fall through and return READ_ONCE(sw->cur_speed).
Because the worker hasn't updated sw->cur_speed yet, it's still max_speed. The timer then updates sw->target_speed to max_speed:
drivers/nvme/host/speed_switch.c:nvme_speed_switch_timer_fn() {
...
sw->target_speed = nvme_check_io_and_decide_speed(sw, &io_activity);
...
}When the worker finishes setting the hardware to min_speed, it double-reads sw->target_speed:
drivers/nvme/host/speed_switch.c:nvme_speed_switch_work() {
...
ret = pcie_set_target_speed(bridge, nvme_speed_to_bus_speed(sw->target_speed),
true);
if (ret) {
...
} else {
WRITE_ONCE(sw->cur_speed, sw->target_speed);
}
...
}This overwrites cur_speed with the timer-corrupted value (max_speed).
The hardware is now throttled at min_speed, but software thinks it is at max_speed.
When high I/O resumes, the timer will decide the target is max_speed, but since cur_speed is already max_speed, it won't schedule the worker to restore the link rate, causing a severe performance regression.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH 3/3 nvme: Expose link rate switching tunables via sysfs
In reply to Liao XuanAdd a speed attribute group under /sys/class/nvme/nvmeX/ that exposes the adaptive link rate switching parameters for runtime tuning:
enable - toggle the feature on/off (0/1)
monitor_interval - I/O monitoring window in milliseconds (>= 100)
min_speed - minimum PCIe generation to downgrade to (1-5) up_threshold - windows above the threshold needed to upgrade down_threshold - windows below the threshold needed to downgrade
The attributes are read/write and are removed when the controller is torn down.
--- drivers/nvme/host/nvme.h | 3 + drivers/nvme/host/speed_switch.c | 15 +++- drivers/nvme/host/sysfs.c | 143 +++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+), 1 deletion(-)
drivers/nvme/host/nvme.h +3 -0
@@ -1076,6 +1076,9 @@ extern const struct attribute_group nvme_dev_attrs_group;extern const struct attribute_group nvme_dev_diag_attrs_group;extern const struct attribute_group *nvme_subsys_attrs_groups[];extern const struct attribute_group *nvme_dev_attr_groups[]; +#ifdef CONFIG_NVME_SPEED_SWITCH +extern const struct attribute_group nvme_speed_attr_group; +#endif extern const struct block_device_operations nvme_bdev_ops;void nvme_delete_ctrl_sync (struct nvme_ctrl *ctrl);
drivers/nvme/host/speed_switch.c +14 -1
@@ -325,7 +325,7 @@ void nvme_speed_switch_init(struct nvme_ctrl *ctrl) {struct nvme_speed_switch *sw = &ctrl->speed_switch;struct pci_dev *pdev; -int max_speed; +int max_speed, ret;if (boot_cpu_data.x86_vendor !=X86_VENDOR_HYGON ) { dev_dbg(ctrl->device,
@@ -376,6 +376,18 @@ void nvme_speed_switch_init(struct nvme_ctrl *ctrl)timer_setup (&sw->timer, nvme_speed_switch_timer_fn,0 );atomic_set (&sw->timer_active,NVME_SPEED_TIMER_INACTIVE );WRITE_ONCE (sw->enabled, true); + + ret =sysfs_create_group (&ctrl->device->kobj, &nvme_speed_attr_group); +if (ret) { +dev_err (ctrl->device, +"failed to create link rate switching sysfs group (%d)\n" , + ret); +timer_delete_sync (&sw->timer); +free_percpu (sw->stats); + sw->stats =NULL ; +WRITE_ONCE (sw->enabled, false); +return ; + } sw->initialized = true; dev_info(ctrl->device,
@@ -405,6 +417,7 @@ void nvme_speed_switch_exit(struct nvme_ctrl *ctrl)WRITE_ONCE (sw->enabled, false);timer_delete_sync (&sw->timer);cancel_work_sync (&sw->work); +sysfs_remove_group (&ctrl->device->kobj, &nvme_speed_attr_group);free_percpu (sw->stats); sw->stats =NULL ;
drivers/nvme/host/sysfs.c +143 -0
146 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH 3/3] nvme: Expose link rate switching tunables via sysfs
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] nvme: Use-After-Free in timer teardown due to missing timer_shutdown_sync() - [High] nvme…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] nvme: Use-After-Free in timer teardown due to missing timer_shutdown_sync()
- [High] nvme: Use-After-Free on per-CPU stats due to lack of synchronization during teardown
- [Medium] nvme: sysfs teardown race allows resurrecting feature state and causing UAF
- [Medium] nvme: torn read-modify-write data race on per-CPU I/O statistics
--
commit 923c7df43c12b9f8956632abc24a17d7d85b2d2f
Author: Liao Xuan <[email protected]>
nvme: Expose link rate switching tunables via sysfs
This commit adds a speed attribute group under /sys/class/nvme/nvmeX/ to expose adaptive link rate switching parameters for runtime tuning. The attributes are read/write and are removed when the controller is torn down.
Quoted 4 lines
drivers/nvme/host/speed_switch.c +0
-0
[ ... ]
drivers/nvme/host/speed_switch.c void nvme_speed_switch_exit(struct nvme_ctrl *ctrl) · line 418
Quoted 3 lines
drivers/nvme/host/speed_switch.c +0
-0@@ -405,6 +417,7 @@ void nvme_speed_switch_exit(struct nvme_ctrl *ctrl)WRITE_ONCE (sw->enabled, false);timer_delete_sync (&sw->timer);
[Severity: High]
Is it safe to use timer_delete_sync() for the teardown path?
If a concurrent I/O thread in nvme_update_io_stats() is preempted, could it wait for timer_delete_sync() to complete and then re-arm the timer after the cancellation completes?
nvme_update_io_stats()
mod_timer(&sw->timer, jiffies + msecs_to_jiffies(READ_ONCE(sw->monitor_interval)));
When the parent nvme_ctrl is later freed, the timer will execute and access freed memory. Should this use timer_shutdown_sync() instead?
drivers/nvme/host/speed_switch.c void nvme_speed_switch_exit(struct nvme_ctrl *ctrl) · line 420
Quoted 2 lines
drivers/nvme/host/speed_switch.c +1
-0cancel_work_sync (&sw->work); +sysfs_remove_group (&ctrl->device->kobj, &nvme_speed_attr_group);
[Severity: Medium]
Is this sysfs group removed too late, leaving a race window during teardown?
Since WRITE_ONCE(sw->enabled, false) and timer_delete_sync() are called before sysfs_remove_group(), could a concurrent sysfs write to the enable attribute execute WRITE_ONCE(sw->enabled, val) and set it back to true?
Because sysfs_remove_group() blocks until active writes finish, it will proceed to free sw->stats while sw->enabled remains true, guaranteeing that subsequent I/Os will bypass the guard and access freed memory.
drivers/nvme/host/speed_switch.c void nvme_speed_switch_exit(struct nvme_ctrl *ctrl) · line 422
Quoted 2 lines
drivers/nvme/host/speed_switch.c +0
-0free_percpu (sw->stats);
[Severity: High]
Can this cause a use-after-free when dereferencing sw->stats?
Since there is no synchronization (such as an RCU grace period or queue freeze) before freeing the memory, could a concurrent I/O thread executing nvme_update_io_stats() that has already passed the lockless sw->enabled check resume and call get_cpu_ptr(sw->stats)?
nvme_update_io_stats()
stat = get_cpu_ptr(sw->stats);
This would dereference the per-CPU pointer which may have just been freed by this concurrent teardown.
[Severity: Medium]
Can this also cause a torn read-modify-write data race on the per-CPU I/O statistics?
If nvme_check_io_and_decide_speed() iterates over all CPUs and clears their counters with a remote, non-atomic write:
stat->read_bytes = 0;
stat->write_bytes = 0;And concurrently, the I/O submission path nvme_update_io_stats() executes a non-atomic read-modify-write on its local CPU:
stat->read_bytes += bytes;
Could the remote write of 0 occur between the local load and store, causing the 0 to be overwritten by the local CPU's accumulated total, thereby double counting the transferred bytes and artificially inflating throughput?
Quoted 6 lines
drivers/nvme/host/speed_switch.c +0
-0sw->stats =NULL ; }drivers/nvme/host/sysfs.c +0
-0
[ ... ]
Quoted 1 line
drivers/nvme/host/sysfs.c +0
-0@@ -1310,3 +1310,146 @@ const struct attribute_group *nvme_subsys_attrs_groups[] = {
[ ... ]
Quoted 4 lines
drivers/nvme/host/sysfs.c +4
-0+static ssize_t nvme_speed_attr_store (struct device *dev, +struct device_attribute *attr, +const char *buf,size_t count) +{
[ ... ]
drivers/nvme/host/sysfs.c const struct attribute_group *nvme_subsys_attrs_groups[] = { · line 1383
Quoted 11 lines
drivers/nvme/host/sysfs.c +11
-0+switch (sa->id) { +case NVME_SPEED_ATTR_ENABLE : +if (val >1 ) +return -EINVAL ; +if (!val &&READ_ONCE (sw->enabled)) { +WRITE_ONCE (sw->enabled, false); +timer_delete_sync (&sw->timer); +cancel_work_sync (&sw->work); +atomic_set (&sw->timer_active,NVME_SPEED_TIMER_INACTIVE ); + }else +WRITE_ONCE (sw->enabled, val);
[Severity: Medium]
Can this overwrite the teardown flag without a lock?
If this executes concurrently with nvme_speed_switch_exit() due to late sysfs_remove_group() calling, it could silently reactivate lockless access to memory that is about to be freed.
Quoted 2 lines
drivers/nvme/host/sysfs.c +2
-0+break ; +case NVME_SPEED_ATTR_MONITOR_INTERVAL :
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3