From c5c9132fa39be57dd5a1aea1bb7dc6fd869975a4 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 28 Nov 2026 01:05:39 +0100 Subject: [PATCH 1/2] =?UTF-8?q?=E5=A4=A7=E5=B0=8F=E6=A0=B8=E5=A4=84?= =?UTF-8?q?=E7=90=86=E5=99=A8=E4=B8=8A=E5=85=B3=E6=8E=89=E6=A8=A1=E6=8B=9F?= =?UTF-8?q?=E5=99=A8=E7=9A=84=E8=BF=9B=E7=A8=8B=E8=8A=82=E6=B5=81=EF=BC=8C?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E5=92=8C=E9=97=AE=E9=A2=98=E5=8C=85=E8=AE=B0?= =?UTF-8?q?=E4=B8=8B=E6=A0=B8=E7=9A=84=E6=95=88=E7=8E=87=E7=AD=89=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 开机后的宿主调度调优多做一步:对实例的 qemu 进程调用 SetProcessInformation(ProcessPowerThrottling),ControlMask 设 EXECUTION_SPEED、StateMask 清零,告诉 Windows 不要按后台任务降速(大小核 上会优先排到大核)。系统不支持(没有这个调用或返回 ERROR_INVALID_PARAMETER 之类)时记一句跳过,不算失败。MODAVD_QOS_BOOST=off 时跳过这一步,照 MODAVD_SYNC_IO、MODAVD_DL_DISK 的写法。结果进「宿主调度」那一行。 开机日志另记一行「宿主处理器核」,问题包加一节「处理器核的效率等级(大小核)」: GetLogicalProcessorInformationEx(RelationProcessorCore) 里各效率等级各有几个 核、几个逻辑处理器。处理器型号问题包「本机」一节已经有,不重复。 不改优先级、X3D 绑核,也不用处理器集合限制 vCPU(等数据)。 Refs ModAVD/ModAVD#290 --- changelog.d/290-qos-hybrid.change.md | 2 + internal/emu/affinity_test.go | 28 +++++ internal/emu/afterboot.go | 27 +++++ internal/host/coreclass.go | 23 ++++ internal/host/coreclass_test.go | 21 ++++ internal/host/unsupported_other.go | 13 +++ internal/host/windows.go | 7 ++ internal/i18n/locales/en/emu.json | 5 + internal/i18n/locales/en/host.json | 6 +- internal/i18n/locales/en/report.json | 1 + internal/i18n/locales/en/win.json | 7 ++ internal/report/collect.go | 1 + internal/report/extra.go | 16 ++- internal/report/extra_windows_test.go | 34 ++++++ internal/report/parity_windows_test.go | 2 +- internal/win/host.go | 141 ++++++++++++++++++++++++- internal/win/win.go | 2 + internal/win/win_test.go | 114 ++++++++++++++++++++ 18 files changed, 444 insertions(+), 6 deletions(-) create mode 100644 changelog.d/290-qos-hybrid.change.md create mode 100644 internal/host/coreclass.go create mode 100644 internal/host/coreclass_test.go diff --git a/changelog.d/290-qos-hybrid.change.md b/changelog.d/290-qos-hybrid.change.md new file mode 100644 index 00000000..25a7ab8a --- /dev/null +++ b/changelog.d/290-qos-hybrid.change.md @@ -0,0 +1,2 @@ +大小核处理器上,无头或在后台运行的模拟器不再被 Windows 降速 (ModAVD/ModAVD#290) +On CPUs with efficiency cores, Windows no longer slows down emulators that run headless or in the background diff --git a/internal/emu/affinity_test.go b/internal/emu/affinity_test.go index 5500ec9d..299028e3 100644 --- a/internal/emu/affinity_test.go +++ b/internal/emu/affinity_test.go @@ -4,6 +4,7 @@ import ( "slices" "testing" + "modavd/internal/errs" "modavd/internal/host" "modavd/internal/root" ) @@ -236,3 +237,30 @@ func TestQemuCoresCommandLine(t *testing.T) { } } } + +// The QoS boost (ModAVD/ModAVD#290): MODAVD_QOS_BOOST=off skips the call; a Windows without the switch is a skip, +// not a failure; any other error is named. +func TestQoSBoostNote(t *testing.T) { + cases := []struct { + name, env string + err error + called bool + want string + }{ + {"default", "", nil, true, "已关进程节流"}, + {"on", "on", nil, true, "已关进程节流"}, + {"off", "off", nil, false, "按 MODAVD_QOS_BOOST=off 不关进程节流"}, + {"OFF spaced", " OFF ", nil, false, "按 MODAVD_QOS_BOOST=off 不关进程节流"}, + {"unsupported", "", errs.New(errs.Unsupported, "x"), true, "系统不支持关进程节流,跳过"}, + {"wrapped unsupported", "", errs.Wrap(errs.Internal, errs.New(errs.Unsupported, "x"), "y"), true, + "系统不支持关进程节流,跳过"}, + {"failed", "", errs.New(errs.Internal, "拒绝访问"), true, "关进程节流失败(拒绝访问)"}, + } + for _, c := range cases { + called := false + got := qosBoostNote(c.env, func() error { called = true; return c.err }) + if got != c.want || called != c.called { + t.Errorf("%s: %q called %v, want %q called %v", c.name, got, called, c.want, c.called) + } + } +} diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index c50dcd00..78f8a896 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -14,6 +14,7 @@ import ( "modavd/internal/adb" "modavd/internal/avd" + "modavd/internal/errs" "modavd/internal/guest" "modavd/internal/host" "modavd/internal/jsonord" @@ -140,6 +141,10 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe note, plan := m.tuneHostScheduling(p, cores) spare = plan.Spare m.Log.Infof("实例 %d 宿主调度: %s", i, note) + if root.CurrentPlatform().Windows() { + // hybrid cores or not (ModAVD/ModAVD#290): whether the line above matters on this host + m.Log.Infof("实例 %d 宿主处理器核: %s", i, host.CoreClassesText(host.CoreClasses())) + } }, func() { if !root.CurrentPlatform().Windows() { @@ -295,6 +300,7 @@ func (m *Manager) tuneHostScheduling(p host.Process, cores int) (string, hostPla } else { notes = append(notes, "优先级高于正常") } + notes = append(notes, qosBoostNote(os.Getenv(envQoSBoost), func() error { return host.DisableExecutionThrottling(p) })) groups := host.L3Groups() if hasBigL3(groups) { lock, ok, err := host.Lock(affinityLockPath(), affinityLockWait) @@ -323,6 +329,27 @@ func (m *Manager) tuneHostScheduling(p host.Process, cores int) (string, hostPla return strings.Join(notes, ","), plan } +// envQoSBoost set to "off" leaves the execution speed throttling of qemu to Windows (A/B runs, and the way back). +// By default it is turned off (ModAVD/ModAVD#290): a headless or background instance is otherwise an EcoQoS candidate, +// which on hybrid processors means the efficiency cores and lower clocks for the translated game's main thread. +const envQoSBoost = "MODAVD_QOS_BOOST" + +// qosBoostNote runs disable (host.DisableExecutionThrottling) unless env (the value of envQoSBoost) is "off", and says +// what came of it for the scheduling line. A Windows without the switch is no failure. +func qosBoostNote(env string, disable func() error) string { + if strings.EqualFold(strings.TrimSpace(env), "off") { + return "按 " + envQoSBoost + "=off 不关进程节流" + } + switch err := disable(); { + case err == nil: + return "已关进程节流" + case errs.CodeOf(err) == errs.Unsupported: + return "系统不支持关进程节流,跳过" + default: + return fmt.Sprintf("关进程节流失败(%v)", err) + } +} + // hostCPUs is the logical processor count: those under an L3 group, at least runtime.NumCPU. func hostCPUs(groups []host.L3Group) int { var all uint64 diff --git a/internal/host/coreclass.go b/internal/host/coreclass.go new file mode 100644 index 00000000..8dde9d71 --- /dev/null +++ b/internal/host/coreclass.go @@ -0,0 +1,23 @@ +package host + +import ( + "fmt" + "strings" +) + +// CoreClassesText describes the host's cores by efficiency class for the boot log and the problem report (Chinese, +// as both of them): one class is a processor without hybrid cores; several are listed slowest first. +func CoreClassesText(classes []CoreClass) string { + switch len(classes) { + case 0: + return "读不到" + case 1: + return fmt.Sprintf("没有大小核(%d 核 %d 个逻辑处理器,效率等级都是 %d)", classes[0].Cores, classes[0].Logical, + classes[0].Class) + } + parts := make([]string, len(classes)) + for k, c := range classes { + parts[k] = fmt.Sprintf("等级 %d:%d 核 %d 个逻辑处理器", c.Class, c.Cores, c.Logical) + } + return "有大小核(效率等级越高越快):" + strings.Join(parts, ";") +} diff --git a/internal/host/coreclass_test.go b/internal/host/coreclass_test.go new file mode 100644 index 00000000..f0a76d42 --- /dev/null +++ b/internal/host/coreclass_test.go @@ -0,0 +1,21 @@ +package host + +import "testing" + +func TestCoreClassesText(t *testing.T) { + cases := []struct { + name string + classes []CoreClass + want string + }{ + {"unreadable", nil, "读不到"}, + {"uniform", []CoreClass{{Class: 0, Cores: 16, Logical: 32}}, "没有大小核(16 核 32 个逻辑处理器,效率等级都是 0)"}, + {"hybrid", []CoreClass{{Class: 0, Cores: 8, Logical: 8}, {Class: 1, Cores: 8, Logical: 16}}, + "有大小核(效率等级越高越快):等级 0:8 核 8 个逻辑处理器;等级 1:8 核 16 个逻辑处理器"}, + } + for _, c := range cases { + if got := CoreClassesText(c.classes); got != c.want { + t.Errorf("%s: %q, want %q", c.name, got, c.want) + } + } +} diff --git a/internal/host/unsupported_other.go b/internal/host/unsupported_other.go index fda89144..d3aa37ad 100644 --- a/internal/host/unsupported_other.go +++ b/internal/host/unsupported_other.go @@ -40,6 +40,19 @@ func GetSystemMemory() (SystemMemory, error) { return SystemMemory{}, errUnsuppo // L3Groups lists the L3 caches of the host. func L3Groups() []L3Group { return nil } +// CoreClass is one efficiency class of the host's cores (Windows EfficiencyClass). +type CoreClass struct { + Class uint8 + Cores int + Logical int +} + +// CoreClasses lists the efficiency classes of the host's cores on Windows. +func CoreClasses() []CoreClass { return nil } + +// DisableExecutionThrottling calls SetProcessInformation(ProcessPowerThrottling) on Windows. +func DisableExecutionThrottling(Process) error { return errUnsupported } + // SharedMemoryExists calls OpenFileMappingW for the Windows named mapping. func SharedMemoryExists(string) bool { return false } diff --git a/internal/host/windows.go b/internal/host/windows.go index cda726cf..61af2c88 100644 --- a/internal/host/windows.go +++ b/internal/host/windows.go @@ -17,6 +17,7 @@ type Listener = win.Listener type StartOptions = win.StartOptions type FileLock = win.FileLock type L3Group = win.L3Group +type CoreClass = win.CoreClass const SpawnHelperArg = win.SpawnHelperArg const HideConsole = win.HideConsole @@ -97,5 +98,11 @@ func FileChangeStamp(f *os.File) string { return win.FileChange func TerminateRefused(p Process) bool { return win.TerminateRefused(p) } +// CoreClasses are the efficiency classes of the host's cores, nil when unreadable. +func CoreClasses() []CoreClass { return win.CoreClasses() } + +// DisableExecutionThrottling turns EcoQoS off for p; errs.Unsupported on a Windows without the switch. +func DisableExecutionThrottling(p Process) error { return win.DisableExecutionThrottling(p) } + // InfoBox displays an informational message with the Windows backend. func InfoBox(message string) error { return win.InfoBox(message) } diff --git a/internal/i18n/locales/en/emu.json b/internal/i18n/locales/en/emu.json index ddf7037d..28988ec1 100644 --- a/internal/i18n/locales/en/emu.json +++ b/internal/i18n/locales/en/emu.json @@ -203,6 +203,7 @@ "关掉占用这些文件的程序后再运行一次 modavd delete %d --yes,会接着删": "Close the programs using these files, then run modavd delete %d --yes again; it will continue deleting", "关掉应用后": "after closing the app", "关机命令自己返回了,安卓没有开始关机: %s": "The shutdown command returned by itself and Android did not start shutting down: %s", + "关进程节流失败(%v)": "Turning off power throttling failed (%v)", "其他": "Other", "内测包 %s 低于 %s": "Beta package %s is lower than %s", "内测包 %s(%s)": "Beta package %s (%s)", @@ -321,6 +322,7 @@ "实例 %d 客体时钟源: %s(可选 %s,客体 %s)": "Instance %d guest clock source: %s (available %s, guest %s)", "实例 %d 客体时钟源是 %s,不是 tsc(可选 %s,客体 %s):这次开机读时钟都要退出到模拟器,整体会慢,关机再开才恢复": "Instance %d: the guest clock source is %s, not tsc (available %s, guest %s): every clock read in this boot has to exit to the emulator, so everything is slower until you shut down and start again", "实例 %d 客体重启后的开机后调优已补做(%.1f 秒,%d 条警告)": "Instance %d: post-boot tuning was redone after the guest restarted (%.1f s, %d warnings)", + "实例 %d 宿主处理器核: %s": "Instance %d host processor cores: %s", "实例 %d 宿主调度: %s": "Instance %d host scheduling: %s", "实例 %d 宿主输入法": "Instance %d host IME", "实例 %d 宿主输入法: %s %s,默认 %s%s(%.1f 秒)": "Instance %d host IME: %s %s, default %s%s (%.1f s)", @@ -539,6 +541,7 @@ "导入 %s 时跳过了 %d 个符号链接或特殊文件(例如 %s)": "Skipped %[2]d symbolic links or special files while importing %[1]s (for example %[3]s)", "导入需要 %d MiB,请检查目标数据盘和电脑磁盘的剩余空间": "Import requires %d MiB. Check the available space on the target data disk and host drive", "少建几台,或者先删掉不用的实例": "Create fewer, or delete instances you no longer use first", + "已关进程节流": "power throttling off", "已写入 ModAVD 实例 %d 的设置: %s": "Wrote settings of ModAVD instance %d: %s", "已写入实例 %d 的按应用走代理:%s": "Wrote per-app proxy of instance %d: %s", "已删除 ModAVD 实例 %d": "Deleted ModAVD instance %d", @@ -594,6 +597,7 @@ "拿着它的程序:%v": "Programs holding it: %v", "挂补丁会重启安卓框架,装到一半会失败;等它挂完(start 返回)再装": "Mounting the patch restarts the Android framework and an install in progress would fail; wait until the mount is done (start returns), then install", "挂这些补丁要重启 zygote,只在前台没有应用、也没有安装正在进行时才挂(不然就留到之后再启动一次,或下次开机)": "Mounting these patches needs a zygote restart, so it only happens when no app is in the foreground and no install is in progress (otherwise it waits for another start later, or the next start)", + "按 %v=off 不关进程节流": "power throttling left on by %v=off", "探测超时(%.0f 秒)": "Probe timed out (%.0f s)", "探测进程退出码 %d,没有结果": "The probe process exited with code %d and gave no result", "接着做设置的期限 %v 已过": "The deadline %v for continuing the setup has passed", @@ -742,6 +746,7 @@ "签名不同,卸载旧版 %d 失败(%s)": "Signature differs; uninstalling the old version %d failed (%s)", "算不出 %v 的相对路径": "Cannot work out the relative path of %v", "算不出已分配和可回收的大小:%v": "Cannot calculate the allocated and reclaimable sizes: %v", + "系统不支持关进程节流,跳过": "power throttling switch not supported by Windows, skipped", "系统镜像 API 为 %s,当前平台需要 %s": "The system image API is %s; this platform needs %s", "系统镜像架构为 %s,Apple Silicon 需要 %s": "The system image architecture is %s; Apple Silicon needs %s", "组件": "Components", diff --git a/internal/i18n/locales/en/host.json b/internal/i18n/locales/en/host.json index 2db978f4..8efb6097 100644 --- a/internal/i18n/locales/en/host.json +++ b/internal/i18n/locales/en/host.json @@ -1,4 +1,8 @@ { "当前平台暂不支持此操作": "This operation is not supported on this platform yet", - "当前平台暂不支持消息框": "Message boxes are not supported on this platform yet" + "当前平台暂不支持消息框": "Message boxes are not supported on this platform yet", + "有大小核(效率等级越高越快):%v": "hybrid cores (a higher efficiency class is faster): %v", + "没有大小核(%d 核 %d 个逻辑处理器,效率等级都是 %d)": "no hybrid cores (%d cores, %d logical processors, all of efficiency class %d)", + "等级 %d:%d 核 %d 个逻辑处理器": "class %d: %d cores, %d logical processors", + "读不到": "unreadable" } diff --git a/internal/i18n/locales/en/report.json b/internal/i18n/locales/en/report.json index 8ee78c0e..a49bdd6a 100644 --- a/internal/i18n/locales/en/report.json +++ b/internal/i18n/locales/en/report.json @@ -163,6 +163,7 @@ "启动卡死线程转储(startup-*-hang-threads.txt):没有": null, "命令行一直在变长": null, "图形说明:宿主 Metal 支持不代表模拟器 Vulkan 或游戏兼容性已通过验证": null, + "处理器核的效率等级(大小核)": null, "复制 %v 失败:%v": null, "复制 mas-avd.json 失败:%v": null, "复制到剪贴板": "Copying to the clipboard", diff --git a/internal/i18n/locales/en/win.json b/internal/i18n/locales/en/win.json index cc6ba425..658e3d24 100644 --- a/internal/i18n/locales/en/win.json +++ b/internal/i18n/locales/en/win.json @@ -6,6 +6,8 @@ "中转进程的参数不是合法的 JSON: %v": "The relay process arguments are not valid JSON: %v", "中转进程的参数里没有要启动的程序": "The relay process arguments do not name a program to start", "中转进程要一个 JSON 参数,收到 %d 个": "The relay process needs one JSON argument, got %d", + "关闭%s的进程节流失败: %v": "Failed to turn off power throttling of %s: %v", + "关闭进程节流": "turn off power throttling", "切换 Edge 窗口失败: %w": "Failed to switch the Edge window: %w", "启动 %s 失败: %v": "Failed to start %s: %v", "启动 %s 失败:中转进程 %.0f 秒内没有回报": "Failed to start %s: the relay process did not report back within %.0f seconds", @@ -46,12 +48,17 @@ "读不到系统的 TCP(IPv6)监听表: %v": "Cannot read the system TCP (IPv6) listener table: %v", "读不到进程列表: %v": "Cannot read the process list: %v", "读取%s的绑核失败: %v": "Failed to read the CPU affinity of %s: %v", + "读取%s的进程节流失败: %v": "Failed to read power throttling of %s: %v", "读取绑核": "read CPU affinity", + "读取进程节流": "read power throttling", "读命令行": "read the command line", "读程序路径": "read the program path", "调整%s的优先级失败: %v": "Failed to change the priority of %s: %v", "调整优先级": "change priority", "路径 %s 不可用: %v": "Path %s is unavailable: %v", + "这个 Windows 版本不支持关闭进程节流: %v": "This Windows version cannot turn off power throttling: %v", + "这个 Windows 版本没有 GetProcessInformation": "This Windows version has no GetProcessInformation", + "这个 Windows 版本没有 SetProcessInformation": "This Windows version has no SetProcessInformation", "这台电脑上用不了窗口操作: %v": "Window operations are not available on this computer: %v", "进程 %d": "process %d", "退出": "Exit", diff --git a/internal/report/collect.go b/internal/report/collect.go index 65f4502f..ba9ee51d 100644 --- a/internal/report/collect.go +++ b/internal/report/collect.go @@ -261,6 +261,7 @@ func collect(ctx context.Context, rootDir string, h Host, opt CollectOptions) (r } c.step("ModAVD 目录与版本", c.rootAndVersions) c.step("Windows / CPU / 内存 / 显卡", c.computer) + c.extra(sectionCoreClasses, c.coreClasses) c.step("虚拟化功能", c.features) c.step("加速检查(emulator -accel-check)", c.accelCheck) c.step("杀毒软件", c.antivirus) diff --git a/internal/report/extra.go b/internal/report/extra.go index cedb78d1..bbadda16 100644 --- a/internal/report/extra.go +++ b/internal/report/extra.go @@ -10,18 +10,23 @@ import ( "time" "modavd/internal/adb" + "modavd/internal/host" "modavd/internal/root" ) // Sections collect-info.ps1 never had, so that whoever sends the problem package is not asked for these separately: // what the manager and the boot watch logged, every adb.exe with the adb server's own log, and the TCP ports Windows -// keeps for itself. The parity tests leave these sections and their files out (goOnlySections, goOnlyEntry). +// keeps for itself, and whether the processor has hybrid cores (ModAVD/ModAVD#290). The parity tests leave these sections and their files out (goOnlySections, goOnlyEntry). const ( sectionManagerLogs = "管理器日志" sectionAdbProcesses = "adb.exe 进程与 adb server 日志" sectionPortExcluded = "Windows 保留的 TCP 端口(netsh)" + sectionCoreClasses = "处理器核的效率等级(大小核)" ) +// hostCoreClasses reads the host's core efficiency classes (a variable so tests can give their own). +var hostCoreClasses = host.CoreClasses + var ( // managerLogTailBytes: modavd-ui.log starts over at 5 MB (one .1 backup), the boot watch's log at 4 MB. managerLogTailBytes int64 = 5 << 20 @@ -227,3 +232,12 @@ func (c *collector) portExclusions() error { } return nil } + +// coreClasses says whether the host has cores of different efficiency classes (Intel's performance and efficiency +// cores) and how many logical processors each has: whether Windows may put a background emulator on the slow ones. +// The processor model is in the 本机 section. +func (c *collector) coreClasses() error { + c.section(sectionCoreClasses) + c.L(host.CoreClassesText(hostCoreClasses())) + return nil +} diff --git a/internal/report/extra_windows_test.go b/internal/report/extra_windows_test.go index aef4c8aa..816743bf 100644 --- a/internal/report/extra_windows_test.go +++ b/internal/report/extra_windows_test.go @@ -6,6 +6,8 @@ import ( "path/filepath" "strings" "testing" + + "modavd/internal/host" ) // setNetsh makes netsh.exe answer stdout, or fail to start with startErr. @@ -118,3 +120,35 @@ func TestCollectPortExclusions(t *testing.T) { t.Errorf("problems %q, summary:\n%s", res.Problems, s) } } + +// Hybrid cores or not (ModAVD/ModAVD#290): a Go-only section right after 本机, from the host's core topology. +func TestCollectCoreClasses(t *testing.T) { + useGoldenZone(t, "full") + old := hostCoreClasses + t.Cleanup(func() { hostCoreClasses = old }) + hostCoreClasses = func() []host.CoreClass { + return []host.CoreClass{{Class: 0, Cores: 8, Logical: 8}, {Class: 1, Cores: 8, Logical: 16}} + } + f := newFixture(t, "full", testTempDir(t), "") + guardDials(t, f.adbPort) + res, _, files := runCollect(t, f) + s := summaryOf(t, files) + want := "\r\n== 处理器核的效率等级(大小核) ==\r\n有大小核(效率等级越高越快):等级 0:8 核 8 个逻辑处理器;等级 1:8 核 16 个逻辑处理器\r\n" + if !strings.Contains(s, want) { + t.Errorf("want %q in:\n%s", want, s) + } + if strings.Index(s, "== 本机 ==") > strings.Index(s, "== 处理器核的效率等级(大小核) ==") { + t.Error("the section comes before 本机") + } + if strings.Contains(strings.Join(res.Problems, "\n"), sectionCoreClasses) { + t.Errorf("problems %q", res.Problems) + } + + hostCoreClasses = func() []host.CoreClass { return nil } + f = newFixture(t, "full", testTempDir(t), "") + guardDials(t, f.adbPort) + _, _, files = runCollect(t, f) + if s := summaryOf(t, files); !strings.Contains(s, "\r\n== 处理器核的效率等级(大小核) ==\r\n读不到\r\n") { + t.Errorf("unreadable:\n%s", s) + } +} diff --git a/internal/report/parity_windows_test.go b/internal/report/parity_windows_test.go index 455264f2..3611b5c0 100644 --- a/internal/report/parity_windows_test.go +++ b/internal/report/parity_windows_test.go @@ -429,7 +429,7 @@ func TestCollectMatchesScript(t *testing.T) { // goOnlySections are the summary sections collect-info.ps1 does not have (extra.go). var goOnlySections = map[string]bool{sectionManagerLogs: true, sectionAdbProcesses: true, sectionPortExcluded: true, - sectionFrameRate: true} + sectionFrameRate: true, sectionCoreClasses: true} // withoutGoOnly drops goOnlySections from summary lines: each with the empty line before its header and its lines. func withoutGoOnly(ls []string) []string { diff --git a/internal/win/host.go b/internal/win/host.go index 125c7d83..9eff6a0e 100644 --- a/internal/win/host.go +++ b/internal/win/host.go @@ -5,8 +5,10 @@ package win import ( "encoding/binary" "fmt" + "math/bits" "os" "path/filepath" + "slices" "strings" "syscall" "unsafe" @@ -16,10 +18,139 @@ import ( const ( aboveNormalPriorityClass = 0x00008000 + relationProcessorCore = 0 // LOGICAL_PROCESSOR_RELATIONSHIP RelationProcessorCore (winnt.h) relationCache = 2 // LOGICAL_PROCESSOR_RELATIONSHIP RelationCache fileMapRead = 0x0004 + + // processthreadsapi.h (Windows SDK 10.0.26100.0): ProcessPowerThrottling is the fifth PROCESS_INFORMATION_CLASS + // (after ProcessMemoryPriority, ProcessMemoryExhaustionInfo, ProcessAppMemoryInfo, ProcessInPrivateInfo). + processPowerThrottling = 4 + processPowerThrottlingCurrentVersion = 1 // PROCESS_POWER_THROTTLING_CURRENT_VERSION + processPowerThrottlingExecutionSpeed = 0x1 // PROCESS_POWER_THROTTLING_EXECUTION_SPEED ) +// powerThrottlingState is PROCESS_POWER_THROTTLING_STATE: three ULONGs, Version, ControlMask, StateMask. +type powerThrottlingState struct { + Version uint32 + ControlMask uint32 + StateMask uint32 +} + +// DisableExecutionThrottling tells Windows never to throttle the execution speed of p (EcoQoS), visible or not: +// SetProcessInformation(ProcessPowerThrottling) with EXECUTION_SPEED in the control mask and cleared in the state +// mask. On hybrid processors the process is then scheduled as high QoS, which prefers the performance cores. An +// errs.Unsupported error when this Windows has no such switch (no SetProcessInformation before Windows 8, the +// information class rejected before Windows 10 1709). +func DisableExecutionThrottling(p Process) error { + if procSetProcessInformation.Find() != nil { + return errs.New(errs.Unsupported, "这个 Windows 版本没有 SetProcessInformation") + } + h, err := p.openRunning(processSetInformation, "关闭进程节流") + if err != nil { + return err + } + defer syscall.CloseHandle(h) + st := powerThrottlingState{Version: processPowerThrottlingCurrentVersion, + ControlMask: processPowerThrottlingExecutionSpeed, StateMask: 0} + if r, err := call(procSetProcessInformation, uintptr(h), processPowerThrottling, uintptr(unsafe.Pointer(&st)), + unsafe.Sizeof(st)); r == 0 { + if throttlingUnsupported(err) { + return errs.Wrap(errs.Unsupported, err, "这个 Windows 版本不支持关闭进程节流: "+err.Error()) + } + return errs.Wrap(errs.Internal, err, fmt.Sprintf("关闭%s的进程节流失败: %v", p.label(), err)) + } + return nil +} + +// throttlingUnsupported: the error of a Windows that does not know the information class or the structure. +func throttlingUnsupported(err error) bool { + const ( + errorInvalidFunction = 1 // ERROR_INVALID_FUNCTION + errorNotSupported = 50 // ERROR_NOT_SUPPORTED + errorInvalidParameter = 87 // ERROR_INVALID_PARAMETER + errorCallNotImplemented = 120 // ERROR_CALL_NOT_IMPLEMENTED + ) + en, ok := err.(syscall.Errno) + return ok && (en == errorInvalidParameter || en == errorNotSupported || en == errorCallNotImplemented || + en == errorInvalidFunction) +} + +// ExecutionThrottling reads p's PROCESS_POWER_THROTTLING_STATE back (GetProcessInformation): controlled is true +// when the process decides its execution speed throttling itself, throttled when it asked for it. Not controlled +// means Windows decides (the default). +func ExecutionThrottling(p Process) (controlled, throttled bool, err error) { + if procGetProcessInformation.Find() != nil { + return false, false, errs.New(errs.Unsupported, "这个 Windows 版本没有 GetProcessInformation") + } + h, err := p.openRunning(processQueryLimitedInformation, "读取进程节流") + if err != nil { + return false, false, err + } + defer syscall.CloseHandle(h) + st := powerThrottlingState{Version: processPowerThrottlingCurrentVersion} + if r, err := call(procGetProcessInformation, uintptr(h), processPowerThrottling, uintptr(unsafe.Pointer(&st)), + unsafe.Sizeof(st)); r == 0 { + code := errs.Internal + if throttlingUnsupported(err) { + code = errs.Unsupported + } + return false, false, errs.Wrap(code, err, fmt.Sprintf("读取%s的进程节流失败: %v", p.label(), err)) + } + return st.ControlMask&processPowerThrottlingExecutionSpeed != 0, + st.StateMask&processPowerThrottlingExecutionSpeed != 0, nil +} + +// CoreClass is one EfficiencyClass of the host's cores: how many cores and logical processors have it. A higher +// class is a faster core; a host without hybrid cores has a single class 0. +type CoreClass struct { + Class uint8 + Cores int + Logical int +} + +// CoreClasses are the efficiency classes of the host's cores, lowest first (every processor group); nil when the +// topology is unreadable. +func CoreClasses() []CoreClass { return parseCoreClasses(processorTopology(relationProcessorCore)) } + +// parseCoreClasses walks SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX entries of RelationProcessorCore (winnt.h): +// Relationship at +0, Size at +4, then PROCESSOR_RELATIONSHIP: Flags +8, EfficiencyClass +9, Reserved[20], +// GroupCount (WORD) +30, GroupMask[GroupCount] from +32, 16 bytes each (GROUP_AFFINITY: KAFFINITY Mask, WORD Group, +// WORD Reserved[3]). An entry that is cut short ends the walk. +func parseCoreClasses(raw []byte) []CoreClass { + byClass := map[uint8]*CoreClass{} + for off := 0; off+8 <= len(raw); { + size := int(binary.LittleEndian.Uint32(raw[off+4:])) + if size <= 0 || off+size > len(raw) { + break + } + if binary.LittleEndian.Uint32(raw[off:]) == relationProcessorCore && size >= 32 { + class := raw[off+9] + n := int(binary.LittleEndian.Uint16(raw[off+30:])) + logical := 0 + for g := 0; g < n && off+32+16*(g+1) <= off+size; g++ { + logical += bits.OnesCount64(binary.LittleEndian.Uint64(raw[off+32+16*g:])) + } + c := byClass[class] + if c == nil { + c = &CoreClass{Class: class} + byClass[class] = c + } + c.Cores++ + c.Logical += logical + } + off += size + } + if len(byClass) == 0 { + return nil + } + out := make([]CoreClass, 0, len(byClass)) + for _, c := range byClass { + out = append(out, *c) + } + slices.SortFunc(out, func(a, b CoreClass) int { return int(a.Class) - int(b.Class) }) + return out +} + // SetAboveNormalPriority sets ABOVE_NORMAL_PRIORITY_CLASS. func SetAboveNormalPriority(p Process) error { h, err := p.openRunning(processSetInformation, "调整优先级") @@ -86,17 +217,21 @@ type l3Group struct { // cacheTopology is the raw GetLogicalProcessorInformationEx(RelationCache) buffer, nil when unreadable (AUTO-MAS // emulator_native.cpu_cache_topology). -func cacheTopology() []byte { +func cacheTopology() []byte { return processorTopology(relationCache) } + +// processorTopology is the raw GetLogicalProcessorInformationEx buffer of one LOGICAL_PROCESSOR_RELATIONSHIP, nil +// when unreadable. +func processorTopology(relation uintptr) []byte { if procGetLogicalProcessorInformationEx.Find() != nil { return nil } var n uint32 - procGetLogicalProcessorInformationEx.Call(relationCache, 0, uintptr(unsafe.Pointer(&n))) + procGetLogicalProcessorInformationEx.Call(relation, 0, uintptr(unsafe.Pointer(&n))) if n == 0 { return nil } buf := make([]byte, n) - r, _, _ := procGetLogicalProcessorInformationEx.Call(relationCache, uintptr(unsafe.Pointer(&buf[0])), + r, _, _ := procGetLogicalProcessorInformationEx.Call(relation, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n))) if r == 0 || int(n) > len(buf) { return nil diff --git a/internal/win/win.go b/internal/win/win.go index 9f017c12..f53dc798 100644 --- a/internal/win/win.go +++ b/internal/win/win.go @@ -70,6 +70,8 @@ var ( procSetPriorityClass = modkernel32.NewProc("SetPriorityClass") procSetProcessAffinityMask = modkernel32.NewProc("SetProcessAffinityMask") procGetProcessAffinityMask = modkernel32.NewProc("GetProcessAffinityMask") + procSetProcessInformation = modkernel32.NewProc("SetProcessInformation") + procGetProcessInformation = modkernel32.NewProc("GetProcessInformation") procOpenFileMappingW = modkernel32.NewProc("OpenFileMappingW") procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW") procGetVolumePathNameW = modkernel32.NewProc("GetVolumePathNameW") diff --git a/internal/win/win_test.go b/internal/win/win_test.go index b145a5ae..c1847666 100644 --- a/internal/win/win_test.go +++ b/internal/win/win_test.go @@ -5,6 +5,7 @@ package win import ( "encoding/binary" "encoding/json" + "errors" "fmt" "net" "os" @@ -823,6 +824,119 @@ func TestL3Parse(t *testing.T) { } } +func TestCoreClasses(t *testing.T) { + raw := processorTopology(relationProcessorCore) + classes := CoreClasses() + t.Logf("core topology %d bytes, classes %+v", len(raw), classes) + if len(classes) == 0 { + t.Fatal("no core classes") + } + logical := 0 + for _, c := range classes { + logical += c.Logical + } + if logical < runtime.NumCPU() { + t.Errorf("%d logical processors in the classes, runtime.NumCPU %d", logical, runtime.NumCPU()) + } +} + +func TestCoreClassParse(t *testing.T) { + // core is one RelationProcessorCore entry: Flags, EfficiencyClass, then one GROUP_AFFINITY per mask. + core := func(class byte, masks ...uint64) []byte { + b := make([]byte, 32+16*len(masks)) + binary.LittleEndian.PutUint32(b[0:], relationProcessorCore) + binary.LittleEndian.PutUint32(b[4:], uint32(len(b))) + b[9] = class + binary.LittleEndian.PutUint16(b[30:], uint16(len(masks))) + for g, m := range masks { + binary.LittleEndian.PutUint64(b[32+16*g:], m) + binary.LittleEndian.PutUint16(b[40+16*g:], uint16(g)) + } + return b + } + other := make([]byte, 48) // an entry of another relationship is skipped + binary.LittleEndian.PutUint32(other[0:], relationCache) + binary.LittleEndian.PutUint32(other[4:], 48) + other[9] = 7 + + // Intel 12th gen like: 2 P-cores with SMT (class 1), 4 E-cores (class 0), listed P first + hybrid := slices.Concat(core(1, 0b11), core(1, 0b1100), other, core(0, 1<<4), core(0, 1<<5), core(0, 1<<6), + core(0, 1<<7)) + got := parseCoreClasses(hybrid) + want := []CoreClass{{Class: 0, Cores: 4, Logical: 4}, {Class: 1, Cores: 2, Logical: 4}} + if !slices.Equal(got, want) { + t.Errorf("hybrid: %+v, want %+v", got, want) + } + // one class; a core spread over two groups counts both masks + if got := parseCoreClasses(slices.Concat(core(0, 0b11), core(0, 0b1, 0b1))); !slices.Equal(got, + []CoreClass{{Class: 0, Cores: 2, Logical: 4}}) { + t.Errorf("uniform: %+v", got) + } + if got := parseCoreClasses(nil); got != nil { + t.Errorf("empty: %+v", got) + } + // a zero size stops the walk, a truncated last entry is left out + broken := core(1, 0b11) + binary.LittleEndian.PutUint32(broken[4:], 0) + if got := parseCoreClasses(slices.Concat(core(0, 1), broken, core(1, 0b11))); !slices.Equal(got, + []CoreClass{{Class: 0, Cores: 1, Logical: 1}}) { + t.Errorf("zero size: %+v", got) + } + if got := parseCoreClasses(slices.Concat(core(0, 1), core(1, 0b11)[:40])); !slices.Equal(got, + []CoreClass{{Class: 0, Cores: 1, Logical: 1}}) { + t.Errorf("truncated: %+v", got) + } + // GroupCount larger than the entry: only the masks inside it count + lying := core(2, 0b111) + binary.LittleEndian.PutUint16(lying[30:], 5) + if got := parseCoreClasses(lying); !slices.Equal(got, []CoreClass{{Class: 2, Cores: 1, Logical: 3}}) { + t.Errorf("group count past the entry: %+v", got) + } +} + +// The switch on a child of the test: Windows decides before, the child stays unthrottled after; a killed process is +// an error that is not "unsupported". +func TestDisableExecutionThrottling(t *testing.T) { + p := startChild(t, StartOptions{}, "60") + controlled, throttled, err := ExecutionThrottling(p) + if errs.CodeOf(err) == errs.Unsupported { + t.Skipf("GetProcessInformation(ProcessPowerThrottling) not supported here: %v", err) + } + if err != nil { + t.Fatal(err) + } + t.Logf("before: controlled %v throttled %v", controlled, throttled) + if err := DisableExecutionThrottling(p); err != nil { + t.Fatal(err) + } + controlled, throttled, err = ExecutionThrottling(p) + if err != nil || !controlled || throttled { + t.Errorf("after: controlled %v throttled %v %v, want controlled and not throttled", controlled, throttled, err) + } + if err := DisableExecutionThrottling(p); err != nil { // again: nothing changes + t.Errorf("second call: %v", err) + } + p.Kill() + p.Wait(5 * time.Second) + if err := DisableExecutionThrottling(p); err == nil || errs.CodeOf(err) == errs.Unsupported { + t.Errorf("on a killed process: %v", err) + } +} + +func TestThrottlingUnsupported(t *testing.T) { + for _, c := range []struct { + err error + want bool + }{ + {syscall.Errno(87), true}, {syscall.Errno(50), true}, {syscall.Errno(120), true}, {syscall.Errno(1), true}, + {syscall.ERROR_ACCESS_DENIED, false}, {syscall.EINVAL, false}, {errors.New("x"), false}, {nil, false}, + } { + if got := throttlingUnsupported(c.err); got != c.want { + t.Errorf("%v: %v, want %v", c.err, got, c.want) + } + } +} + var procGetPriorityClass = modkernel32.NewProc("GetPriorityClass") func TestPriorityAndAffinity(t *testing.T) { From 41ebe512e4cc218db37919a3ca21d6c3afe239f6 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 28 Nov 2026 01:59:01 +0100 Subject: [PATCH 2/2] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E6=94=B9=E6=88=90=E5=8F=AA=E5=86=99=E5=81=9A=E4=BA=86=E4=BB=80?= =?UTF-8?q?=E4=B9=88=EF=BC=88=E6=95=88=E6=9E=9C=E8=BF=98=E6=B2=A1=E5=9C=A8?= =?UTF-8?q?=E5=A4=A7=E5=B0=8F=E6=A0=B8=E6=9C=BA=E5=99=A8=E4=B8=8A=E5=AE=9E?= =?UTF-8?q?=E6=B5=8B=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs ModAVD/ModAVD#290 --- changelog.d/290-qos-hybrid.change.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/changelog.d/290-qos-hybrid.change.md b/changelog.d/290-qos-hybrid.change.md index 25a7ab8a..4b10ba3b 100644 --- a/changelog.d/290-qos-hybrid.change.md +++ b/changelog.d/290-qos-hybrid.change.md @@ -1,2 +1,2 @@ -大小核处理器上,无头或在后台运行的模拟器不再被 Windows 降速 (ModAVD/ModAVD#290) -On CPUs with efficiency cores, Windows no longer slows down emulators that run headless or in the background +模拟器开机后要求 Windows 不对它做后台降速,大小核处理器上更不容易被排到小核 (ModAVD/ModAVD#290) +The emulator now opts out of Windows background throttling, making efficiency-core placement less likely on hybrid CPUs