Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,12 @@

#include "detectthread.h"
#include "monitorusb.h"
#include "DDLog.h"

#include <QDir>
#include <QFileInfo>
#include <QLoggingCategory>

using namespace DDLog;

// 内核把 USB 设备信息填充完成的最长等待时间。
// 纯 sysfs 探测,等待期间几乎不消耗 CPU。
static constexpr int kUsbSettleMaxMs = 1000;
static constexpr int kUsbSettleStepMs = 100;

DetectThread::DetectThread(QObject *parent)
: QThread(parent)
, mp_MonitorUsb(new MonitorUsb())
{
// 连接槽函数
connect(mp_MonitorUsb, SIGNAL(usbChanged()), this, SLOT(slotUsbChanged()), Qt::QueuedConnection);
connect(mp_MonitorUsb, &MonitorUsb::usbChanged, this, &DetectThread::usbChanged, Qt::QueuedConnection);
}

void DetectThread::run()
Expand All @@ -39,51 +26,3 @@ void DetectThread::setWorkingFlag(bool flag)
start();
}
}

void DetectThread::slotUsbChanged()
{
// 当监听到新的usb时,内核需要加载usb信息,而上层应用需要在内核处理之后获取信息。
// 这里只做纯 sysfs 的就绪探测,不再 spawn hwinfo:
// 原实现每秒执行一次 `hwinfo --usb --keyboard --mouse`(单次 300~400ms)
// 直到设备信息变化,最多 10 秒即 11 个进程;在 USB 反复上报事件但设备列表
// 实际未变时会跑满 10 秒,持续占满一个 CPU 核心,播放中的音频因此丢帧。
qint64 begin = QDateTime::currentMSecsSinceEpoch();
const bool ready = waitKernelUsbReady(kUsbSettleMaxMs);
qCInfo(appLog) << " usb settle time:" << QDateTime::currentMSecsSinceEpoch() - begin
<< " ready:" << ready;
emit usbChanged();
}

bool DetectThread::waitKernelUsbReady(int maxWaitMs)
{
const qint64 begin = QDateTime::currentMSecsSinceEpoch();
while (true) {
bool ready = true;

QDir dir("/sys/bus/usb/devices");
const QFileInfoList entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
for (const QFileInfo &entry : entries) {
const QString path = entry.absoluteFilePath();
if (entry.fileName().contains(':')) {
// usb_interface:还没有 driver 符号链接说明驱动仍在 probe
if (!QFileInfo::exists(path + "/driver")) {
ready = false;
break;
}
} else if (QFileInfo::exists(path + "/idVendor")) {
// usb_device:已枚举
continue;
} else {
ready = false;
break;
}
}

if (ready)
return true;
if (QDateTime::currentMSecsSinceEpoch() - begin >= maxWaitMs)
return false;

msleep(kUsbSettleStepMs);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
#ifndef DETECTTHREAD_H
#define DETECTTHREAD_H

#include <QThread>

Check warning on line 8 in deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/detectthread.h

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QThread> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QDateTime>

class MonitorUsb;

/**
* @brief The DetectThread class
*
* 只负责运行 udev 监控线程并转发 usbChanged 通知。
*/
class DetectThread : public QThread
{
Expand All @@ -31,33 +32,10 @@

signals:
/**
* @brief usbChanged
* @brief usbChanged usb/蓝牙设备发生变化
*/
void usbChanged();

private slots:
/**
* @brief slotUsbChanged usb发生变化时的曹函数处理
*/
void slotUsbChanged();

private:
/**
* @brief waitKernelUsbReady 等待内核把 USB 设备信息填充完成
*
* 原实现通过反复执行 `hwinfo --usb --keyboard --mouse`(单次 300~400ms)
* 并比对输出来判断"插拔是否处理完",最多循环 10 秒,即最多 spawn 11 个
* hwinfo 进程。在"USB 反复上报事件、但设备列表实际没变"的场景下会跑满
* 10 秒,持续占满一个 CPU 核心,正在播放的音频因此丢帧(表现为"滋滋"声)。
*
* 这里改为纯 sysfs 探测:usb_device 都已有 idVendor、且 usb_interface 都已
* 绑定驱动,说明内核已处理完毕。全程只读文件,不产生任何子进程。
*
* @param maxWaitMs 最长等待毫秒数
* @return true 表示已经就绪
*/
bool waitKernelUsbReady(int maxWaitMs);

private:
MonitorUsb *mp_MonitorUsb; //<! udev检测任务
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
#include "mainjob.h"

#include <QLoggingCategory>
#include <QProcess>

Check warning on line 10 in deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QProcess> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QFile>

Check warning on line 11 in deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QFile> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QDateTime>

Check warning on line 12 in deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QDateTime> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QDebug>

Check warning on line 13 in deepin-devicemanager-server/deepin-deviceinfo/src/hotplug/monitorusb.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QDebug> not found. Please note: Cppcheck does not need standard library headers to get proper results.

// 一批 udev 事件平息多久之后才执行合并的 hwinfo --usb
static constexpr qint64 kEventSettleMs = 500;
// 单次 hwinfo --usb 的等待上限。
static constexpr int kUsbInfoTimeoutMs = 8000;

MonitorUsb::MonitorUsb()
: m_workingFlag(true)
Expand Down Expand Up @@ -106,7 +109,12 @@

QProcess process;
process.start("hwinfo --usb");
process.waitForFinished(-1);
if (!process.waitForFinished(kUsbInfoTimeoutMs)) {
process.kill();
process.waitForFinished(1000);
qWarning() << "hwinfo --usb timeout, skip usb control/wakeup update";
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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`.

}
const QString info = process.readAllStandardOutput();

if (needControl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,15 @@
#include "deviceinfomanager.h"

#include <QObjectCleanupHandler>
#include <QDir>

Check warning on line 10 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpool.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QDir> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QLoggingCategory>

Check warning on line 11 in deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/threadpool.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QLoggingCategory> not found. Please note: Cppcheck does not need standard library headers to get proper results.

static constexpr int kFastCmdTimeoutMs = 5000; // 毫秒级完成的命令
static constexpr int kLshwTimeoutMs = 10000; // lshw 要遍历整机设备树
static constexpr int kHwinfoTimeoutMs = 15000; // 9 类探测,最容易被硬件拖慢
static constexpr int kHwinfoMonitorTimeoutMs = 10000;
static constexpr int kBluetoothCtlTimeoutMs = 500; // bluetoothctl 可能连不上守护进程

ThreadPool::ThreadPool(QObject *parent)
: QThreadPool(parent)
{
Expand All @@ -31,25 +37,13 @@
updateInfo(m_ListUpdate);
}

void ThreadPool::updateHotplugInfo()
{
// 只刷新与 USB 插拔相关、开销可控的信息
updateInfo(m_ListHotplug);
}

void ThreadPool::updateInfo(const QList<Cmd> &cmds)
{
for (const Cmd &cmd : cmds) {
ThreadPoolTask *task = new ThreadPoolTask(cmd.cmd, cmd.file, cmd.canNotReplace, cmd.waitingTime);
task->setAutoDelete(true);
start(task);
}

// 等待所有任务执行完毕,最多 10 秒。
// 原实现是 while (true) + activeThreadCount() 的忙等自旋,不 sleep,
// 会白占一个 CPU 核心最多 10 秒;音频等实时线程正好被它挤掉时间片。
// QThreadPool::waitForDone() 内部用条件变量等待,不消耗 CPU。
waitForDone(10000);
}

void ThreadPool::initCmd()
Expand All @@ -59,6 +53,7 @@
cmdLshw.cmd = QString("%1 %2%3").arg("lshw > ").arg(PATH).arg("lshw.txt");
cmdLshw.file = "lshw.txt";
cmdLshw.canNotReplace = false;
cmdLshw.waitingTime = kLshwTimeoutMs;
m_ListCmd.append(cmdLshw);
m_ListUpdate.append(cmdLshw);

Expand Down Expand Up @@ -130,6 +125,7 @@
cmdUpower.cmd = QString("%1 %2%3").arg("upower --dump > ").arg(PATH).arg("upower_dump.txt");
cmdUpower.file = "upower_dump.txt";
cmdUpower.canNotReplace = true;
cmdUpower.waitingTime = kFastCmdTimeoutMs;
m_ListCmd.append(cmdUpower);
m_ListUpdate.append(cmdUpower);

Expand All @@ -146,6 +142,7 @@
cmdLsblk.cmd = QString("%1 %2%3").arg("lsblk -d -o name,rota > ").arg(PATH).arg("lsblk_d.txt");
cmdLsblk.file = "lsblk_d.txt";
cmdLsblk.canNotReplace = false;
cmdLsblk.waitingTime = kFastCmdTimeoutMs;
m_ListCmd.append(cmdLsblk);
m_ListUpdate.append(cmdLsblk);

Expand All @@ -154,6 +151,7 @@
cmdLssg.cmd = QString("%1 %2%3").arg("ls /dev/sg* > ").arg(PATH).arg("ls_sg.txt");
cmdLssg.file = "ls_sg.txt";
cmdLssg.canNotReplace = false;
cmdLssg.waitingTime = kFastCmdTimeoutMs;
m_ListCmd.append(cmdLssg);
m_ListUpdate.append(cmdLssg);

Expand All @@ -162,6 +160,7 @@
cmdLspci.cmd = QString("%1 %2%3").arg("lspci > ").arg(PATH).arg("lspci.txt");
cmdLspci.file = "lspci.txt";
cmdLspci.canNotReplace = false;
cmdLspci.waitingTime = kFastCmdTimeoutMs;
m_ListCmd.append(cmdLspci);
m_ListUpdate.append(cmdLspci);

Expand All @@ -170,6 +169,7 @@
cmdLpstate.cmd = QString("%1 %2%3").arg("lpstat -a > ").arg(PATH).arg("lpstat.txt");
cmdLpstate.file = "lpstat.txt";
cmdLpstate.canNotReplace = false;
cmdLpstate.waitingTime = kFastCmdTimeoutMs;
m_ListCmd.append(cmdLpstate);
m_ListUpdate.append(cmdLpstate);

Expand All @@ -178,6 +178,7 @@
cmdDmesg.cmd = QString("%1 %2%3").arg("dmesg > ").arg(PATH).arg("dmesg.txt");
cmdDmesg.file = "dmesg.txt";
cmdDmesg.canNotReplace = true;
cmdDmesg.waitingTime = kFastCmdTimeoutMs;
m_ListCmd.append(cmdDmesg);
m_ListUpdate.append(cmdDmesg);

Expand All @@ -186,6 +187,7 @@
cmdHciconfig.cmd = QString("%1 %2%3").arg("hciconfig -a > ").arg(PATH).arg("hciconfig.txt");
cmdHciconfig.file = "hciconfig.txt";
cmdHciconfig.canNotReplace = false;
cmdHciconfig.waitingTime = kFastCmdTimeoutMs;
m_ListCmd.append(cmdHciconfig);
m_ListUpdate.append(cmdHciconfig);

Expand All @@ -194,7 +196,7 @@
cmdBluetooth.cmd = QString("%1 %2%3").arg("bluetoothctl paired-devices > ").arg(PATH).arg("bt_device.txt");
cmdBluetooth.file = "bt_device.txt";
cmdBluetooth.canNotReplace = false;
cmdBluetooth.waitingTime = 500;
cmdBluetooth.waitingTime = kBluetoothCtlTimeoutMs;
m_ListCmd.append(cmdBluetooth);
m_ListUpdate.append(cmdBluetooth);

Expand All @@ -209,26 +211,15 @@
cmdHwinfo.cmd = QString("%1 %2%3").arg("hwinfo --sound --netcard --keyboard --cdrom --disk --display --mouse --usb --fingerprint > ").arg(PATH).arg("hwinfo.txt");
cmdHwinfo.file = "hwinfo.txt";
cmdHwinfo.canNotReplace = false;
cmdHwinfo.waitingTime = kHwinfoTimeoutMs;
m_ListCmd.append(cmdHwinfo);
m_ListUpdate.append(cmdHwinfo);

Cmd cmdHwinfoMonitor; //hwinfo --framebuffer --monitor
cmdHwinfoMonitor.cmd = QString("%1 %2%3").arg("hwinfo --monitor > ").arg(PATH).arg("hwinfo_monitor.txt");
cmdHwinfoMonitor.file = "hwinfo_monitor.txt";
cmdHwinfoMonitor.canNotReplace = false;
cmdHwinfoMonitor.waitingTime = kHwinfoMonitorTimeoutMs;
m_ListCmd.append(cmdHwinfoMonitor);
m_ListUpdate.append(cmdHwinfoMonitor);

// ---------------------------------------------------------------------
// 热插拔(USB)刷新列表
//
// 一次插拔只需要更新"会变"的信息。lshw / upower / lscpu / lspci /
// lpstat / bluetoothctl / hwinfo --framebuffer 与插拔无关,却要跑数百
// 毫秒到数秒,并发执行时会把 CPU 占满,正在播放的音频因此丢帧(滋滋声)。
// 未列入的命令不执行,其缓存保持上一次的值,不会丢失数据。
// ---------------------------------------------------------------------
m_ListHotplug.append(cmdLsblk); // 新增/移除磁盘
m_ListHotplug.append(cmdLssg); // 新增/移除 SCSI 通用设备
m_ListHotplug.append(cmdHciconfig); // 蓝牙适配器状态
m_ListHotplug.append(cmdHwinfo); // 含 --sound:声卡拓扑也可能变化
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
* @brief The Cmd struct
*/
struct Cmd {
Cmd(): cmd(""), file(""), canNotReplace(false), waitingTime(-1)
// waitingTime 不能默认 -1(QProcess 永久等待):单条命令卡住会把整批刷新拖死。
// 实测常规命令均在毫秒级,5s 已足够宽松;慢命令在 initCmd() 里单独放大。
Cmd(): cmd(""), file(""), canNotReplace(false), waitingTime(5000)
{}

QString cmd; //<! the cmd
QString file; //<! the file
bool canNotReplace; //<! mark can replace or not
int waitingTime; //<! waiting time
int waitingTime; //<! 单条命令的等待上限(ms),必须为正数
};

/**
Expand All @@ -42,19 +44,12 @@ class ThreadPool : public QThreadPool
*/
void updateDeviceInfo();

/**
* @brief updateHotplugInfo 热插拔时的局部刷新
*
* USB 插拔很频繁,没有必要每次都把整机信息重新采集一遍:lshw、upower、
* lscpu、lspci、lpstat、bluetoothctl、hwinfo --framebuffer 等命令与插拔
* 无关,却会把 CPU 占满数百毫秒到数秒,正在播放的音频因此丢帧。
* 未列入 m_ListHotplug 的命令不会执行,其缓存保持上一次的值,不会丢失数据。
*/
void updateHotplugInfo();

private:
/**
* @brief updateInfo 并发执行一组命令并等待结束
* @brief updateInfo 并发执行一组命令
*
* 只负责派发任务,不等待完成;超时由调用方通过 waitForDone(ms) 决定,
* 避免库和调用方各设一个超时、叠加后超出对外承诺的上限。
* @param cmds 命令列表
*/
void updateInfo(const QList<Cmd> &cmds);
Expand All @@ -67,7 +62,6 @@ class ThreadPool : public QThreadPool
private:
QList<Cmd> m_ListCmd; // all cmd
QList<Cmd> m_ListUpdate; // update cmd
QList<Cmd> m_ListHotplug; // hotplug(usb) cmd
};

#endif // THREADPOOL_H
Loading
Loading