Repository navigation
fix: 优化USB热插拔处理避免音频卡顿 - #980
deepin-bot[bot] merged 1 commit into
Conversation
|
Warning
详情 {
"lshw": {
"deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpool.cpp": [
"static constexpr int kLshwTimeoutMs = 10000; // lshw \u8981\u904d\u5386\u6574\u673a\u8bbe\u5907\u6811"
]
},
"dmidecode": {
"deepin-devicemanager/src/GenerateDevice/LoadInfoThread.cpp": [
" readDataFlag = !DeviceManager::instance()->cmdInfo(\"dmidecode4\").isEmpty();"
]
}
} |
Reviewer's GuideData structuresDefine per-command timeout defaults and the ThreadPoolTask timeout parameters that its callers rely on.
APIUpdate the client-side DBusInterface getInfo signature and implement its bounded synchronous D-Bus call.
Uses of the APICoordinate client cache reads with server refresh completion and use the updated D-Bus interface to request and poll refreshes.
ImplementationForward USB change notifications directly from DetectThread, removing the previous sysfs readiness polling.
Bound USB hwinfo execution so a stalled command skips the control and wakeup update instead of blocking indefinitely.
Set individual refresh-command timeouts, dispatch refresh tasks without waiting inside updateInfo, and remove the separate hotplug command list.
Apply command timeouts throughout task execution, including wildcard helpers, smartctl, and lspci probes.
Guard server policy hwinfo and full refresh waits, and report running status while refresh tasks remain active.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 8 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp" line_range="76" />
<code_context>
+
+ if (mp_DetectThread) {
+ mp_DetectThread->setWorkingFlag(false);
+ mp_DetectThread->wait(2000);
+ }
+}
</code_context>
<issue_to_address>
**Shutdown aborts the service**
When the service shuts down while the monitor thread is waiting for `hwinfo --usb`, `MainJob::~MainJob()` waits only two seconds, but `DetectThread` can remain blocked in `applyUsbControl()` for up to nine seconds; the destructor then destroys the child thread while it is running, causing Qt to abort the service.
Wait for `DetectThread` to stop before destroying it, including while `applyUsbControl()` is blocked.
Also at `deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp:112`, `deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp:77`.
</issue_to_address>
### Comment 2
<location path="deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp" line_range="170" />
<code_context>
m_pool->updateDeviceInfo();
- m_pool->waitForDone(60000);
+ // 整个刷新(命令派发 + 全部任务结束)只在这里限时一次。
+ if (!m_pool->waitForDone(kFullRefreshTimeoutMs)) {
+ qCWarning(appLog) << "device info refresh timed out after"
+ << kFullRefreshTimeoutMs << "ms, tasks still running:"
</code_context>
<issue_to_address>
**Older refreshes overwrite newer data**
When a refresh exceeds the 20-second pool wait and another refresh starts before its tasks finish, `updateAllDevice()` returns while the old tasks remain in the shared pool, so a later refresh dispatches another batch for the same cache keys; whichever task finishes last leaves callers with stale or mixed device data.
Prevent a new refresh batch from starting until all tasks from the previous batch have finished.
</issue_to_address>
### Comment 3
<location path="deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp" line_range="170-175" />
<code_context>
m_pool->updateDeviceInfo();
- m_pool->waitForDone(60000);
+ // 整个刷新(命令派发 + 全部任务结束)只在这里限时一次。
+ if (!m_pool->waitForDone(kFullRefreshTimeoutMs)) {
+ qCWarning(appLog) << "device info refresh timed out after"
+ << kFullRefreshTimeoutMs << "ms, tasks still running:"
+ << m_pool->activeThreadCount();
+ }
+ s_ServerIsUpdating = false;
PERF_PRINT_END("POINT-01");
m_firstUpdate = false;
</code_context>
<issue_to_address>
**Cache read before refresh finishes**
When a full refresh takes longer than the client's 40-second wait budget, `updateAllDevice()` returns after 20 seconds while its tasks continue, and `waitServerRefreshFinished()` gives up after 40 seconds and proceeds to read the cache. A refresh with enough slow per-device work (for example, many disks each taking up to 8 seconds in `smartctl`) therefore exposes partially updated data to the client.
Keep the client from reading until outstanding refresh tasks finish, or cancel/otherwise make timed-out refreshes unable to write to the cache.
Also at `deepin-devicemanager/src/GenerateDevice/LoadInfoThread.cpp:122-145`.
</issue_to_address>
### Comment 4
<location path="deepin-devicemanager/src/GenerateDevice/LoadInfoThread.cpp" line_range="26-37" />
<code_context>
+using namespace DDLog;
+
+static constexpr int kServerIdlePollMs = 100; // 轮询间隔
+static constexpr int kMaxWaitServerIdleMs = 40000; // 整体等待上限,按真实耗时计算
+static constexpr int kServerStatusTimeoutMs = 30000; // 单次查询超时,需大于服务端刷新上限
+static constexpr int kPollStartGraceMs = 300; // 留给 refreshInfo 消息派发的时间
</code_context>
<issue_to_address>
**Client reads a partial device snapshot**
When the server is still refreshing when the client's 40-second wait expires, `waitServerRefreshFinished()` returns at its deadline and `LoadInfoThread::run()` reads cache files while server tasks continue writing them, so the client displays a mixed or incomplete snapshot.
Keep the client from reading cache until the server refresh has completed, or load a consistent snapshot.
</issue_to_address>
### Comment 5
<location path="deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp" line_range="146" />
<code_context>
- // lspci / lpstat / bluetoothctl / hwinfo --framebuffer)。
- // 客户端主动刷新与驱动操作完成走 slotRefreshRequest(),那里是全量刷新。
- executeClientInstruction("HOTPLUG");
+ qCInfo(appLog) << "usb/bluetooth changed, cache refresh deferred to client request";
}
</code_context>
<issue_to_address>
**Device changes remain invisible**
When a USB or Bluetooth device changes while the manager is open and no separate refresh is requested, `MainJob::slotUsbChanged()` only logs the event and neither refreshes the cache nor notifies the client, so the device list and details remain stale.
Request a cache refresh or notify the client to refresh when a USB or Bluetooth change event arrives.
</issue_to_address>
### Comment 6
<location path="deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp" line_range="116" />
<code_context>
+ process.kill();
+ process.waitForFinished(1000);
+ qWarning() << "hwinfo --usb timeout, skip usb control/wakeup update";
+ return;
+ }
const QString info = process.readAllStandardOutput();
</code_context>
<issue_to_address>
**Timed-out probes drop policy updates**
When `hwinfo --usb` times out while a USB event has queued a control or wakeup update, `applyUsbControl()` has already cleared `m_NeedControl` and `m_NeedWakeup`, so the timeout return skips the pending updates and the monitor marks the batch done; the device's control or wake policy remains unsynchronized until another event.
Preserve or requeue the pending flags on timeout and retry the control and wakeup updates.
Also at `deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp:117`.
</issue_to_address>
### Comment 7
<location path="deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp" line_range="215" />
<code_context>
- runCmd(smartCmd, sInfo);
+ // 每个盘单独限时:机械盘刚唤醒、USB 桥接的盘响应很慢,个别盘甚至不响应。
+ // 不能沿用 lsblk 任务的 waitingTime,否则一块坏盘就能拖死整批刷新。
+ runCmd(smartCmd, sInfo, kSmartctlTimeoutMs);
// 在使用smartctl的时候会出现对 /dev/sda 出现判断错误的情况,此时可以对/dev/sda1进行处理
if (sInfo.contains("Read Device Identity failed:")) {
</code_context>
<issue_to_address>
**Timed-out probes erase cached details**
When a SMART or PCI detail probe times out after its cache entry has been populated, `runCmd()` clears the output, but the detail probe passes the empty result to `DeviceInfoManager::addInfo()`, which replaces the cached value; previously available device details disappear.
Skip `addInfo()` for empty output from timed-out detail probes so the existing cached value is preserved.
Also at `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:96`, `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:254`, `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:270`.
</issue_to_address>
### Comment 8
<location path="deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp" line_range="97-98" />
<code_context>
+ process.kill();
+ process.waitForFinished(1000);
+ qWarning() << "hwinfo --usb timeout, skip usb control/wakeup update";
+ return;
+ }
const QString info = process.readAllStandardOutput();
</code_context>
<issue_to_address>
**Timed-out inventory keeps stale results**
When an inventory command times out after its cache entry has a successful result, `runCmd()` clears the output and `runCmdToCache()` skips `addInfo()`, leaving the previous cache entry in place; removed devices or changed inventory continue to be reported.
Invalidate or replace the previous cache entry when an inventory command times out instead of leaving its old result.
</issue_to_address>|
|
||
| if (mp_DetectThread) { | ||
| mp_DetectThread->setWorkingFlag(false); | ||
| mp_DetectThread->wait(2000); |
There was a problem hiding this comment.
🟠 High · Shutdown aborts the service
When the service shuts down while the monitor thread is waiting for hwinfo --usb, MainJob::~MainJob() waits only two seconds, but DetectThread can remain blocked in applyUsbControl() for up to nine seconds; the destructor then destroys the child thread while it is running, causing Qt to abort the service.
Wait for DetectThread to stop before destroying it, including while applyUsbControl() is blocked.
Also at deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp:112, deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp:77.
Prompt for AI agents
In `deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp` at line 76:
**Shutdown aborts the service**
When the service shuts down while the monitor thread is waiting for `hwinfo --usb`, `MainJob::~MainJob()` waits only two seconds, but `DetectThread` can remain blocked in `applyUsbControl()` for up to nine seconds; the destructor then destroys the child thread while it is running, causing Qt to abort the service.
Wait for `DetectThread` to stop before destroying it, including while `applyUsbControl()` is blocked.
Also at `deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp:112`, `deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp:77`.| m_pool->updateDeviceInfo(); | ||
| m_pool->waitForDone(60000); | ||
| // 整个刷新(命令派发 + 全部任务结束)只在这里限时一次。 | ||
| if (!m_pool->waitForDone(kFullRefreshTimeoutMs)) { |
There was a problem hiding this comment.
🟡 Medium · Older refreshes overwrite newer data
When a refresh exceeds the 20-second pool wait and another refresh starts before its tasks finish, updateAllDevice() returns while the old tasks remain in the shared pool, so a later refresh dispatches another batch for the same cache keys; whichever task finishes last leaves callers with stale or mixed device data.
Prevent a new refresh batch from starting until all tasks from the previous batch have finished.
Prompt for AI agents
In `deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp` at line 170:
**Older refreshes overwrite newer data**
When a refresh exceeds the 20-second pool wait and another refresh starts before its tasks finish, `updateAllDevice()` returns while the old tasks remain in the shared pool, so a later refresh dispatches another batch for the same cache keys; whichever task finishes last leaves callers with stale or mixed device data.
Prevent a new refresh batch from starting until all tasks from the previous batch have finished.| if (!m_pool->waitForDone(kFullRefreshTimeoutMs)) { | ||
| qCWarning(appLog) << "device info refresh timed out after" | ||
| << kFullRefreshTimeoutMs << "ms, tasks still running:" | ||
| << m_pool->activeThreadCount(); | ||
| } | ||
| s_ServerIsUpdating = false; |
There was a problem hiding this comment.
🟡 Medium · Cache read before refresh finishes
When a full refresh takes longer than the client's 40-second wait budget, updateAllDevice() returns after 20 seconds while its tasks continue, and waitServerRefreshFinished() gives up after 40 seconds and proceeds to read the cache. A refresh with enough slow per-device work (for example, many disks each taking up to 8 seconds in smartctl) therefore exposes partially updated data to the client.
Keep the client from reading until outstanding refresh tasks finish, or cancel/otherwise make timed-out refreshes unable to write to the cache.
Also at deepin-devicemanager/src/GenerateDevice/LoadInfoThread.cpp:122-145.
Prompt for AI agents
In `deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp` at lines 170-175:
**Cache read before refresh finishes**
When a full refresh takes longer than the client's 40-second wait budget, `updateAllDevice()` returns after 20 seconds while its tasks continue, and `waitServerRefreshFinished()` gives up after 40 seconds and proceeds to read the cache. A refresh with enough slow per-device work (for example, many disks each taking up to 8 seconds in `smartctl`) therefore exposes partially updated data to the client.
Keep the client from reading until outstanding refresh tasks finish, or cancel/otherwise make timed-out refreshes unable to write to the cache.
Also at `deepin-devicemanager/src/GenerateDevice/LoadInfoThread.cpp:122-145`.| static constexpr int kMaxWaitServerIdleMs = 40000; // 整体等待上限,按真实耗时计算 | ||
| static constexpr int kServerStatusTimeoutMs = 30000; // 单次查询超时,需大于服务端刷新上限 | ||
| static constexpr int kPollStartGraceMs = 300; // 留给 refreshInfo 消息派发的时间 | ||
| static constexpr int kServerProbeRetryMs = 200; // 查询失败(服务未就绪)时的重试间隔 | ||
| static constexpr int kServerProbeRetryCount = 5; // 查询失败时的重试次数 | ||
|
|
||
| LoadInfoThread::LoadInfoThread() | ||
| : mp_ReadFilePool() | ||
| , mp_GenerateDevicePool() | ||
| , m_Running(false) | ||
| , m_FinishedReadFilePool(false) | ||
| , m_Start(true) | ||
| { | ||
| connect(&mp_ReadFilePool, &GetInfoPool::finishedAll, this, &LoadInfoThread::slotFinishedReadFilePool); | ||
| } |
There was a problem hiding this comment.
🟡 Medium · Client reads a partial device snapshot
When the server is still refreshing when the client's 40-second wait expires, waitServerRefreshFinished() returns at its deadline and LoadInfoThread::run() reads cache files while server tasks continue writing them, so the client displays a mixed or incomplete snapshot.
Keep the client from reading cache until the server refresh has completed, or load a consistent snapshot.
Prompt for AI agents
In `deepin-devicemanager/src/GenerateDevice/LoadInfoThread.cpp` at lines 26-143:
**Client reads a partial device snapshot**
When the server is still refreshing when the client's 40-second wait expires, `waitServerRefreshFinished()` returns at its deadline and `LoadInfoThread::run()` reads cache files while server tasks continue writing them, so the client displays a mixed or incomplete snapshot.
Keep the client from reading cache until the server refresh has completed, or load a consistent snapshot.| // lspci / lpstat / bluetoothctl / hwinfo --framebuffer)。 | ||
| // 客户端主动刷新与驱动操作完成走 slotRefreshRequest(),那里是全量刷新。 | ||
| executeClientInstruction("HOTPLUG"); | ||
| qCInfo(appLog) << "usb/bluetooth changed, cache refresh deferred to client request"; |
There was a problem hiding this comment.
🟠 High · Device changes remain invisible
When a USB or Bluetooth device changes while the manager is open and no separate refresh is requested, MainJob::slotUsbChanged() only logs the event and neither refreshes the cache nor notifies the client, so the device list and details remain stale.
Request a cache refresh or notify the client to refresh when a USB or Bluetooth change event arrives.
Prompt for AI agents
In `deepin-devicemanager-server/deepin-deviceinfo/src/mainjob.cpp` at line 146:
**Device changes remain invisible**
When a USB or Bluetooth device changes while the manager is open and no separate refresh is requested, `MainJob::slotUsbChanged()` only logs the event and neither refreshes the cache nor notifies the client, so the device list and details remain stale.
Request a cache refresh or notify the client to refresh when a USB or Bluetooth change event arrives.| process.kill(); | ||
| process.waitForFinished(1000); | ||
| qWarning() << "hwinfo --usb timeout, skip usb control/wakeup update"; | ||
| return; |
There was a problem hiding this comment.
🟡 Medium · Timed-out probes drop policy updates
When hwinfo --usb times out while a USB event has queued a control or wakeup update, applyUsbControl() has already cleared m_NeedControl and m_NeedWakeup, so the timeout return skips the pending updates and the monitor marks the batch done; the device's control or wake policy remains unsynchronized until another event.
Preserve or requeue the pending flags on timeout and retry the control and wakeup updates.
Also at deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp:117.
Prompt for AI agents
In `deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp` at line 116:
**Timed-out probes drop policy updates**
When `hwinfo --usb` times out while a USB event has queued a control or wakeup update, `applyUsbControl()` has already cleared `m_NeedControl` and `m_NeedWakeup`, so the timeout return skips the pending updates and the monitor marks the batch done; the device's control or wake policy remains unsynchronized until another event.
Preserve or requeue the pending flags on timeout and retry the control and wakeup updates.
Also at `deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp:117`.| runCmd(smartCmd, sInfo); | ||
| // 每个盘单独限时:机械盘刚唤醒、USB 桥接的盘响应很慢,个别盘甚至不响应。 | ||
| // 不能沿用 lsblk 任务的 waitingTime,否则一块坏盘就能拖死整批刷新。 | ||
| runCmd(smartCmd, sInfo, kSmartctlTimeoutMs); |
There was a problem hiding this comment.
🟡 Medium · Timed-out probes erase cached details
When a SMART or PCI detail probe times out after its cache entry has been populated, runCmd() clears the output, but the detail probe passes the empty result to DeviceInfoManager::addInfo(), which replaces the cached value; previously available device details disappear.
Skip addInfo() for empty output from timed-out detail probes so the existing cached value is preserved.
Also at deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:96, deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:254, deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:270.
Prompt for AI agents
In `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp` at line 215:
**Timed-out probes erase cached details**
When a SMART or PCI detail probe times out after its cache entry has been populated, `runCmd()` clears the output, but the detail probe passes the empty result to `DeviceInfoManager::addInfo()`, which replaces the cached value; previously available device details disappear.
Skip `addInfo()` for empty output from timed-out detail probes so the existing cached value is preserved.
Also at `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:96`, `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:254`, `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp:270`.| return; | ||
| } |
There was a problem hiding this comment.
🟡 Medium · Timed-out inventory keeps stale results
When an inventory command times out after its cache entry has a successful result, runCmd() clears the output and runCmdToCache() skips addInfo(), leaving the previous cache entry in place; removed devices or changed inventory continue to be reported.
Invalidate or replace the previous cache entry when an inventory command times out instead of leaving its old result.
Prompt for AI agents
In `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpooltask.cpp` at lines 97-98:
**Timed-out inventory keeps stale results**
When an inventory command times out after its cache entry has a successful result, `runCmd()` clears the output and `runCmdToCache()` skips `addInfo()`, leaving the previous cache entry in place; removed devices or changed inventory continue to be reported.
Invalidate or replace the previous cache entry when an inventory command times out instead of leaving its old result.1. 简化DetectThread,移除sysfs轮询逻辑,直接转发usbChanged信号; 2. 为hwinfo、lshw、lspci、smartctl、bluetoothctl等外部命令添加超时保护; 3. 移除updateHotplugInfo独立路径,统一使用updateInfo并按命令设置超时; 4. ThreadPoolTask的runCmd增加timeoutMs参数,防止命令无限阻塞; 5. 更新LoadInfoThread和MainWindow适配新的超时机制; 6. 更新DBusInterface接口适配; ===================================== 1. simplified DetectThread by removing sysfs polling logic and forwarding usbChanged signal directly; 2. added timeout protection for external commands (hwinfo, lshw, lspci, smartctl, bluetoothctl); 3. removed separate updateHotplugInfo path, unified into updateInfo with per-command timeouts; 4. added timeoutMs parameter to ThreadPoolTask::runCmd to prevent indefinite blocking; 5. updated LoadInfoThread and MainWindow to adapt to the new timeout mechanism; 6. updated DBusInterface to match the new interface; Log: 通过为所有外部命令添加超时保护并简化USB热插拔处理流程,避免设备管理器在USB插拔时长时间占用CPU导致音频卡顿 Task: https://pms.uniontech.com/task-view-398371.html
5672225 to
e04dc84
Compare
|
Warning
详情 {
"lshw": {
"deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpool.cpp": [
"static constexpr int kLshwTimeoutMs = 10000; // lshw \u8981\u904d\u5386\u6574\u673a\u8bbe\u5907\u6811"
]
},
"dmidecode": {
"deepin-devicemanager/src/GenerateDevice/LoadInfoThread.cpp": [
" readDataFlag = !DeviceManager::instance()->cmdInfo(\"dmidecode4\").isEmpty();"
]
}
} |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: GongHeng2017, max-lvs, wyu71 The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
/forcemerge |
|
This pr force merged! (status: unstable) |
4d29ce4
into
linuxdeepin:develop/eagle
背景
PMS Task: https://pms.uniontech.com/task-view-398371.html
播放音频时插拔U盘会导致音频卡顿。
改动内容
编译验证
Summary by Sourcery
Optimize USB hot-plug device refreshes by bounding blocking operations and coordinating client/server updates to prevent audio stutter.
Bug Fixes:
Enhancements:
Chores: