diff --git a/desktop/internal/core/process_memory.go b/desktop/internal/core/process_memory.go index b769dc3766..27f6c3aa69 100644 --- a/desktop/internal/core/process_memory.go +++ b/desktop/internal/core/process_memory.go @@ -13,7 +13,28 @@ type MemoryProcess struct { // read. Core ignores a parent link to a process that started later. StartTime *uint64 `json:"startTime,omitempty"` Name string `json:"name"` - Bytes uint64 `json:"bytes"` + // Bytes is what the process has in memory. + Bytes uint64 `json:"bytes"` + // CompressedBytes is what the system compressed or wrote out to disk, which Bytes does not + // include, nil when it was not read. + CompressedBytes *uint64 `json:"compressedBytes,omitempty"` + // GPUMemoryBytes is graphics memory charged to the process that Bytes does not hold, such as + // dedicated video memory on Windows, nil where it was not read or Bytes holds it. + GPUMemoryBytes *uint64 `json:"gpuMemoryBytes,omitempty"` + // CPUTime is the processor time the process used since it started, user and system, in + // microseconds, nil when it was not read. + CPUTime *uint64 `json:"cpuTime,omitempty"` + // GPUEngines is the busy time of every graphics engine the process used, empty when it used + // none or they were not read. + GPUEngines []GPUEngineTime `json:"gpuEngines,omitempty"` +} + +// GPUEngineTime is the time one graphics engine was busy with a process's work. Engine names the +// same engine in every process and every table; times of one name add up. +type GPUEngineTime struct { + Engine string `json:"engine"` + // BusyTime is in microseconds. + BusyTime uint64 `json:"busyTime"` } // MemoryRole kinds: what the client started a process for. @@ -38,6 +59,30 @@ type MemoryRequest struct { Processes []MemoryProcess `json:"processes"` Roles []MemoryRole `json:"roles,omitempty"` EntryLimit *int `json:"entryLimit,omitempty"` + // SampledAt is when the table was read, in microseconds of a clock that only moves forward. + // Without it the summary has no percentages and no baseline. + SampledAt *uint64 `json:"sampledAt,omitempty"` + // Previous is the Baseline of the previous summary. + Previous *MemoryBaseline `json:"previous,omitempty"` + // LogicalProcessors, when set, makes a processor percentage a share of that many processors, + // as the Windows Task Manager shows it; otherwise 100 is one processor busy. It must be at + // least 1. + LogicalProcessors *int `json:"logicalProcessors,omitempty"` +} + +// MemoryBaseline holds the use counters of the instance's processes at one moment, which the +// next request sends back so Core can measure the use in between. +type MemoryBaseline struct { + SampledAt uint64 `json:"sampledAt"` + Processes []BaselineProcess `json:"processes"` +} + +// BaselineProcess is the use counters of one process in a baseline. +type BaselineProcess struct { + ProcessID int64 `json:"processId"` + StartTime *uint64 `json:"startTime,omitempty"` + CPUTime *uint64 `json:"cpuTime,omitempty"` + GPUEngines []GPUEngineTime `json:"gpuEngines,omitempty"` } // Memory kinds: the part of the instance a process counts in, in the order the summary @@ -50,11 +95,28 @@ const ( MemoryChildProcess = "childProcess" ) +// MemoryUsage is what a group of processes has beyond its memory in memory. Each figure is on +// the summary, every category and every entry, or on none of them: the byte sums when a process +// of the instance reported them, the percentages once a process can be compared with the +// previous baseline. +type MemoryUsage struct { + // CompressedBytes is what the system compressed or wrote out to disk. + CompressedBytes *uint64 `json:"compressedBytes,omitempty"` + // GPUMemoryBytes is graphics memory the bytes in memory do not hold. + GPUMemoryBytes *uint64 `json:"gpuMemoryBytes,omitempty"` + // CPUPercent is the processor use since the previous table, rounded to a tenth. + CPUPercent *float64 `json:"cpuPercent,omitempty"` + // GPUPercent is the use of the busiest graphics engine since the previous table, rounded to + // a tenth and at most 100. + GPUPercent *float64 `json:"gpuPercent,omitempty"` +} + // MemoryCategory is the sum of one part. type MemoryCategory struct { Kind string `json:"kind"` Bytes uint64 `json:"bytes"` ProcessCount int `json:"processCount"` + MemoryUsage } // MemoryEntry is one process of the instance other than the host, with the processes Core @@ -65,6 +127,7 @@ type MemoryEntry struct { ProcessID int64 `json:"processId"` Bytes uint64 `json:"bytes"` ProcessCount int `json:"processCount"` + MemoryUsage } // MemoryOmitted is the count and sum of the entries past the limit. @@ -76,10 +139,14 @@ type MemoryOmitted struct { // MemorySummary is Core's account of what the instance holds: the total, every part in a // fixed order with the empty ones included, and the largest entries. type MemorySummary struct { - TotalBytes uint64 `json:"totalBytes"` + TotalBytes uint64 `json:"totalBytes"` + MemoryUsage Categories []MemoryCategory `json:"categories"` Entries []MemoryEntry `json:"entries"` Omitted MemoryOmitted `json:"omitted"` + // Baseline is what to send as Previous with the next table, nil when the request had no + // SampledAt. + Baseline *MemoryBaseline `json:"baseline,omitempty"` } // SummarizeProcessMemory has Core attribute every process of the table to the instance or diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 6099cd8bca..0f107f5305 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -924,21 +924,32 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.verifying": "Extracting and verifying plugin…", "desktop.memory.belowMegabyte": "< 1 MB", "desktop.memory.childProcesses": "Other child processes", + "desktop.memory.columnCPU": "CPU", + "desktop.memory.columnCompressed": "Swapped out", + "desktop.memory.columnGPU": "GPU", + "desktop.memory.columnInMemory": "In memory", "desktop.memory.gigabytes": "{value} GB", "desktop.memory.help": "Counts the Lithe main process and every process that belongs to it: language servers, plugin services, child processes such as terminals and runs, and the helpers the system starts for Lithe, such as the WebKit processes that show web pages and previews.", - "desktop.memory.helpLinux": "Each figure is the resident memory less its shared pages.", - "desktop.memory.helpMacOS": "Each figure is what the Memory column of Activity Monitor shows.", - "desktop.memory.helpWindows": "Each figure is the private working set, which the Memory column of Task Manager shows.", + "desktop.memory.helpFigures": "“In memory” is the physical memory the processes hold now; the status bar and the total count only this. “Swapped out” is what the system compressed or wrote to disk for them, which “In memory” does not include. CPU and GPU are the use between two readings, GPU being the busiest graphics engine; the GPU is read only while the details are open, so its use shows from the second reading on.", + "desktop.memory.helpLinux": "“In memory” is the resident memory less its shared pages; “Swapped out” is what was moved to swap, zram included. CPU counts one fully busy core as 100%, as top does; GPU comes from the engine times the DRM driver reports.", + "desktop.memory.helpMacOS": "“In memory” and “Swapped out” add up to what the Memory column of Activity Monitor shows; “Swapped out” is its compressed part. CPU counts one fully busy core as 100%, as Activity Monitor does.", + "desktop.memory.helpWindows": "“In memory” is the private working set, which the Memory column of Task Manager shows. Windows does not report how much of a process it compressed, so “Swapped out” is the private commit outside the working set: memory compressed, written to the page file or not yet touched, an upper bound. “GPU memory” is what the Dedicated GPU memory column of Task Manager shows. CPU counts all logical processors fully busy as 100%, as Task Manager does.", "desktop.memory.host": "Lithe main process", "desktop.memory.languageServer": "{plugin} · {language}", "desktop.memory.languageServers": "Language servers", "desktop.memory.megabytes": "{value} MB", "desktop.memory.noOtherProcesses": "Lithe has not started any other process.", "desktop.memory.omitted": "{count} more, {value} in total", + "desktop.memory.percent": "{value}%", "desktop.memory.processCount": "{count} processes", "desktop.memory.processes": "Processes", "desktop.memory.reading": "Reading processes…", "desktop.memory.services": "Plugin services", + "desktop.memory.statCPU": "CPU {value}", + "desktop.memory.statCompressed": "Swapped out {value}", + "desktop.memory.statGPU": "GPU {value}", + "desktop.memory.statGPUMemory": "GPU memory {value}", + "desktop.memory.statSeparator": " · ", "desktop.memory.status": "{total} · Lithe {lithe}", "desktop.memory.systemHelpers": "System helpers", "desktop.memory.title": "Memory", @@ -3483,21 +3494,32 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.verifying": "正在解压并校验插件…", "desktop.memory.belowMegabyte": "< 1 MB", "desktop.memory.childProcesses": "其他子进程", + "desktop.memory.columnCPU": "CPU", + "desktop.memory.columnCompressed": "压缩/换出", + "desktop.memory.columnGPU": "GPU", + "desktop.memory.columnInMemory": "内存中", "desktop.memory.gigabytes": "{value} GB", "desktop.memory.help": "统计 Lithe 主进程和属于它的全部进程:语言服务器、插件服务、终端和运行任务等子进程,以及系统代 Lithe 启动的辅助进程,例如显示网页和预览的 WebKit 进程。", - "desktop.memory.helpLinux": "数值是常驻内存减去共享页。", - "desktop.memory.helpMacOS": "数值与活动监视器“内存”一列显示的一致。", - "desktop.memory.helpWindows": "数值是专用工作集,即任务管理器“内存”一列显示的值。", + "desktop.memory.helpFigures": "“内存中”是进程现在占用的物理内存,状态栏和总计都只算这一项。“压缩/换出”是系统为这些进程压缩或写到磁盘上的内存,不计入“内存中”。CPU 和 GPU 是相邻两次读取之间的占用率,GPU 取最忙的那个图形引擎;面板打开后才读取 GPU,第二次读取起才有 GPU 占用。", + "desktop.memory.helpLinux": "“内存中”是常驻内存减去共享页,“压缩/换出”是换出到交换区(包括 zram)的部分。CPU 以一个核心占满为 100%,与 top 一致;GPU 来自 DRM 驱动报告的引擎时间。", + "desktop.memory.helpMacOS": "“内存中”加“压缩/换出”就是活动监视器“内存”一列的值,“压缩/换出”是其中被压缩的部分。CPU 以一个核心占满为 100%,与活动监视器一致。", + "desktop.memory.helpWindows": "“内存中”是专用工作集,即任务管理器“内存”一列的值。Windows 不单独报告进程被压缩了多少,“压缩/换出”是已提交的专用内存中不在工作集里的部分:被压缩、写入页面文件或尚未用到的内存,所以它是上限。“显存”是任务管理器“专用 GPU 内存”一列的值。CPU 以全部逻辑处理器占满为 100%,与任务管理器一致。", "desktop.memory.host": "Lithe 主进程", "desktop.memory.languageServer": "{plugin} · {language}", "desktop.memory.languageServers": "语言服务器", "desktop.memory.megabytes": "{value} MB", "desktop.memory.noOtherProcesses": "Lithe 目前没有启动其他进程。", "desktop.memory.omitted": "另有 {count} 项,共 {value}", + "desktop.memory.percent": "{value}%", "desktop.memory.processCount": "{count} 个进程", "desktop.memory.processes": "进程", "desktop.memory.reading": "正在读取进程…", "desktop.memory.services": "插件服务", + "desktop.memory.statCPU": "CPU {value}", + "desktop.memory.statCompressed": "压缩/换出 {value}", + "desktop.memory.statGPU": "GPU {value}", + "desktop.memory.statGPUMemory": "显存 {value}", + "desktop.memory.statSeparator": " · ", "desktop.memory.status": "{total} · Lithe {lithe}", "desktop.memory.systemHelpers": "系统辅助进程", "desktop.memory.title": "内存", diff --git a/desktop/internal/sysinfo/gpu_windows.go b/desktop/internal/sysinfo/gpu_windows.go new file mode 100644 index 0000000000..dc1f8cacf3 --- /dev/null +++ b/desktop/internal/sysinfo/gpu_windows.go @@ -0,0 +1,193 @@ +package sysinfo + +import ( + "fmt" + "unsafe" + + "golang.org/x/sys/windows" +) + +// The graphics kernel's statistics, which Task Manager's GPU columns show, are read through +// the D3DKMT functions of gdi32. x/sys/windows declares none of them, so their structures are +// laid out here as d3dkmthk.h declares them. +var ( + gdi32 = windows.NewLazySystemDLL("gdi32.dll") + d3dkmtEnumAdapters2 = gdi32.NewProc("D3DKMTEnumAdapters2") + d3dkmtCloseAdapter = gdi32.NewProc("D3DKMTCloseAdapter") + d3dkmtQueryAdapterInfo = gdi32.NewProc("D3DKMTQueryAdapterInfo") + d3dkmtQueryStatistics = gdi32.NewProc("D3DKMTQueryStatistics") +) + +// D3DKMT_QUERYSTATISTICS_TYPE values. +const ( + statisticsAdapter = 0 + statisticsSegment = 3 + statisticsProcessSegment = 4 + statisticsProcessNode = 6 +) + +// adapterTypeQuery is KMTQAITYPE_ADAPTERTYPE, and softwareDevice its bit for an adapter that +// renders on the processor, as the Microsoft Basic Render Driver. +const ( + adapterTypeQuery = 15 + softwareDevice = 1 << 2 +) + +// d3dkmtAdapterInfo is D3DKMT_ADAPTERINFO. +type d3dkmtAdapterInfo struct { + handle uint32 + luid windows.LUID + sources uint32 + precise int32 +} + +// d3dkmtEnumAdapters is D3DKMT_ENUMADAPTERS2. +type d3dkmtEnumAdapters struct { + count uint32 + adapters *d3dkmtAdapterInfo +} + +// d3dkmtQueryAdapter is D3DKMT_QUERYADAPTERINFO. +type d3dkmtQueryAdapter struct { + handle uint32 + kind uint32 + data unsafe.Pointer + size uint32 +} + +// d3dkmtStatistics is D3DKMT_QUERYSTATISTICS: the query, its result, then the segment or node +// the query is about. +type d3dkmtStatistics struct { + kind uint32 + luid windows.LUID + process windows.Handle + result [776]byte + id uint32 + _ uint32 +} + +// gpuAdapter is a hardware adapter with the facts the process queries need: which of its +// segments are dedicated memory and how many engines it has. +type gpuAdapter struct { + luid windows.LUID + dedicated []uint32 + nodes uint32 +} + +// openGPUAdapters lists the hardware adapters and returns a function that closes them. An +// adapter whose statistics cannot be read is left out; none are listed on a system without +// the functions. +func openGPUAdapters() ([]gpuAdapter, func()) { + if d3dkmtEnumAdapters2.Find() != nil || d3dkmtQueryStatistics.Find() != nil { + return nil, func() {} + } + var enum d3dkmtEnumAdapters + if status, _, _ := d3dkmtEnumAdapters2.Call(uintptr(unsafe.Pointer(&enum))); status != 0 || enum.count == 0 { + return nil, func() {} + } + infos := make([]d3dkmtAdapterInfo, enum.count) + enum.adapters = &infos[0] + if status, _, _ := d3dkmtEnumAdapters2.Call(uintptr(unsafe.Pointer(&enum))); status != 0 { + return nil, func() {} + } + infos = infos[:min(int(enum.count), len(infos))] + close := func() { + for _, info := range infos { + handle := info.handle + _, _, _ = d3dkmtCloseAdapter.Call(uintptr(unsafe.Pointer(&handle))) + } + } + adapters := make([]gpuAdapter, 0, len(infos)) + for _, info := range infos { + if softwareAdapter(info.handle) { + continue + } + if adapter, ok := readGPUAdapter(info.luid); ok { + adapters = append(adapters, adapter) + } + } + return adapters, close +} + +// softwareAdapter says whether the adapter renders on the processor; an adapter whose type +// cannot be read is taken as hardware. +func softwareAdapter(handle uint32) bool { + if d3dkmtQueryAdapterInfo.Find() != nil { + return false + } + var flags uint32 + query := d3dkmtQueryAdapter{handle: handle, kind: adapterTypeQuery, data: unsafe.Pointer(&flags), size: uint32(unsafe.Sizeof(flags))} + status, _, _ := d3dkmtQueryAdapterInfo.Call(uintptr(unsafe.Pointer(&query))) + return status == 0 && flags&softwareDevice != 0 +} + +// readGPUAdapter reads an adapter's segments and engine count. A segment that is an aperture +// maps system memory, which the working set already counts, so only the others are kept. +func readGPUAdapter(luid windows.LUID) (gpuAdapter, bool) { + adapter := gpuAdapter{luid: luid} + query := d3dkmtStatistics{kind: statisticsAdapter, luid: luid} + if !queryStatistics(&query) { + return adapter, false + } + // D3DKMT_QUERYSTATISTICS_ADAPTER_INFORMATION starts with NbSegments and NodeCount. + segments := resultUint32(&query, 0) + adapter.nodes = resultUint32(&query, 4) + for segment := range segments { + query = d3dkmtStatistics{kind: statisticsSegment, luid: luid, id: segment} + // D3DKMT_QUERYSTATISTICS_SEGMENT_INFORMATION has Aperture after three counters and the + // memory statistics. + if queryStatistics(&query) && resultUint32(&query, 40) == 0 { + adapter.dedicated = append(adapter.dedicated, segment) + } + } + return adapter, true +} + +// processGPU reads what the process of handle holds in the adapters' dedicated memory and +// how long each of their engines ran its work, in microseconds. The memory is nil when no +// adapter answered for the process. +func processGPU(handle windows.Handle, adapters []gpuAdapter) (*uint64, []GPUEngine) { + var dedicated uint64 + answered := false + var engines []GPUEngine + for _, adapter := range adapters { + for _, segment := range adapter.dedicated { + query := d3dkmtStatistics{kind: statisticsProcessSegment, luid: adapter.luid, process: handle, id: segment} + if queryStatistics(&query) { + // D3DKMT_QUERYSTATISTICS_PROCESS_SEGMENT_INFORMATION starts with BytesCommitted. + dedicated += resultUint64(&query, 0) + answered = true + } + } + for node := range adapter.nodes { + query := d3dkmtStatistics{kind: statisticsProcessNode, luid: adapter.luid, process: handle, id: node} + if !queryStatistics(&query) { + continue + } + answered = true + // D3DKMT_QUERYSTATISTICS_PROCESS_NODE_INFORMATION starts with RunningTime, in + // 100-nanosecond intervals. + if running := resultUint64(&query, 0); running > 0 { + name := fmt.Sprintf("%08x%08x/%d", uint32(adapter.luid.HighPart), adapter.luid.LowPart, node) + engines = append(engines, GPUEngine{Name: name, BusyTime: running / 10}) + } + } + } + if !answered { + return nil, nil + } + return &dedicated, engines +} + +func queryStatistics(query *d3dkmtStatistics) bool { + status, _, _ := d3dkmtQueryStatistics.Call(uintptr(unsafe.Pointer(query))) + return status == 0 +} + +func resultUint32(query *d3dkmtStatistics, offset int) uint32 { + return *(*uint32)(unsafe.Pointer(&query.result[offset])) +} + +func resultUint64(query *d3dkmtStatistics, offset int) uint64 { + return *(*uint64)(unsafe.Pointer(&query.result[offset])) +} diff --git a/desktop/internal/sysinfo/process.go b/desktop/internal/sysinfo/process.go index 38e60c9b22..5b53806e82 100644 --- a/desktop/internal/sysinfo/process.go +++ b/desktop/internal/sysinfo/process.go @@ -15,13 +15,45 @@ type Process struct { StartTime uint64 // Name is the process's short name. Name string - // MemoryBytes is the memory the system charges to the process: the physical footprint - // Activity Monitor shows on macOS, the private working set Task Manager shows on Windows - // and the resident pages less the shared ones on Linux. It is zero for a process whose + // MemoryBytes is what the process has in memory: on macOS the physical footprint Activity + // Monitor shows less its compressed part, on Windows the private working set Task Manager + // shows, on Linux the resident pages less the shared ones. It is zero for a process whose // memory this user may not read. MemoryBytes uint64 + // CompressedBytes is what the system compressed or wrote out to disk for the process, which + // MemoryBytes does not include, nil when it was not read. macOS reports the compressed + // memory and Linux the swapped-out memory exactly. Windows does not say which part of a + // process's commit charge is compressed, so it is the private commit not in the working + // set: compressed, written to the page file, or committed but never touched. + CompressedBytes *uint64 + // GPUMemoryBytes is graphics memory charged to the process that MemoryBytes does not hold: + // the dedicated video memory Task Manager shows on Windows. It is nil on macOS and Linux, + // where it is not read, and for a process whose graphics use was not read. + GPUMemoryBytes *uint64 + // CPUTime is the processor time the process used since it started, user and system, in + // microseconds; nil when it was not read. + CPUTime *uint64 + // GPUEngines is the busy time of every graphics engine the process used, empty when it + // used none or its graphics use was not read. + GPUEngines []GPUEngine +} + +// GPUEngine is the time one graphics engine spent on a process's work since it started. +type GPUEngine struct { + // Name is the same for one engine in every process and every reading of this run: an + // accelerator on macOS, an adapter and node on Windows, a device and engine on Linux. + Name string + // BusyTime is in microseconds. + BusyTime uint64 +} + +// Options says what Processes reads beyond what every row has. +type Options struct { + // GPU holds the processes whose graphics use is read; reading it for every process of the + // system costs far more than the rest of the table. + GPU map[int]bool } // Processes reads the process table: every process this user can see. A fact the system does -// not give for one process is zero; the error says the table could not be listed at all. -func Processes() ([]Process, error) { return processes() } +// not give for one process is zero or nil; the error says the table could not be listed at all. +func Processes(options Options) ([]Process, error) { return processes(options) } diff --git a/desktop/internal/sysinfo/process_darwin.go b/desktop/internal/sysinfo/process_darwin.go index 94c196846d..c4e02b27f5 100644 --- a/desktop/internal/sysinfo/process_darwin.go +++ b/desktop/internal/sysinfo/process_darwin.go @@ -1,9 +1,16 @@ package sysinfo /* +#cgo LDFLAGS: -framework IOKit -framework CoreFoundation + +#include +#include #include #include +#include +#include #include +#include #include #include #include @@ -15,28 +22,59 @@ typedef struct { int responsible; unsigned long long start; unsigned long long footprint; + // compressed is the compressed part of footprint; has_compressed is zero when the task's + // memory could not be read, as for a process of another user. + unsigned long long compressed; + int has_compressed; + // cpu is the user and system time in microseconds; has_cpu is zero when it was not read. + unsigned long long cpu; + int has_cpu; char name[2 * MAXCOMLEN + 1]; } lithe_process; // responsibility_get_pid_responsible_for_pid is the libsystem function Activity Monitor uses // to put XPC services under the app they work for. It is not declared in the SDK, so it is -// looked up once; without it no process has a responsible process. +// looked up once; without it no process has a responsible process. The mach time base the +// processor times are counted in is read at the same time. typedef pid_t (*lithe_responsible_fn)(pid_t); static lithe_responsible_fn lithe_responsible; -static pthread_once_t lithe_responsible_once = PTHREAD_ONCE_INIT; +static mach_timebase_info_data_t lithe_timebase; +static pthread_once_t lithe_setup_once = PTHREAD_ONCE_INIT; -static void lithe_find_responsible(void) { +static void lithe_setup(void) { lithe_responsible = (lithe_responsible_fn)dlsym(RTLD_DEFAULT, "responsibility_get_pid_responsible_for_pid"); + if (mach_timebase_info(&lithe_timebase) != KERN_SUCCESS || lithe_timebase.denom == 0) { + lithe_timebase.numer = 0; + lithe_timebase.denom = 1; + } } static int lithe_process_count(void) { return proc_listallpids(NULL, 0); } +// lithe_compressed reads the compressed memory of a task, which the physical footprint +// includes. It returns zero when the task cannot be read. +static int lithe_compressed(int pid, unsigned long long *compressed) { + mach_port_t task; + if (task_name_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS) { + return 0; + } + task_vm_info_data_t info; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + kern_return_t result = task_info(task, TASK_VM_INFO, (task_info_t)&info, &count); + mach_port_deallocate(mach_task_self(), task); + if (result != KERN_SUCCESS) { + return 0; + } + *compressed = info.compressed; + return 1; +} + // lithe_read_processes writes up to capacity rows and returns how many it wrote, or -1 when the // process IDs cannot be listed. A process that exits while it is read is left out. static int lithe_read_processes(lithe_process *rows, int capacity) { - pthread_once(&lithe_responsible_once, lithe_find_responsible); + pthread_once(&lithe_setup_once, lithe_setup); int *pids = calloc((size_t)capacity, sizeof(int)); if (pids == NULL) { return -1; @@ -56,24 +94,133 @@ static int lithe_read_processes(lithe_process *rows, int capacity) { continue; } lithe_process *row = &rows[written++]; + memset(row, 0, sizeof(*row)); row->pid = pids[i]; row->ppid = (int)info.pbi_ppid; row->start = (unsigned long long)info.pbi_start_tvsec * 1000000ULL + (unsigned long long)info.pbi_start_tvusec; const char *name = info.pbi_name[0] != '\0' ? info.pbi_name : info.pbi_comm; strlcpy(row->name, name, sizeof(row->name)); struct rusage_info_v4 usage; - row->footprint = proc_pid_rusage(pids[i], RUSAGE_INFO_V4, (rusage_info_t *)&usage) == 0 ? usage.ri_phys_footprint : 0; + if (proc_pid_rusage(pids[i], RUSAGE_INFO_V4, (rusage_info_t *)&usage) == 0) { + row->footprint = usage.ri_phys_footprint; + if (lithe_timebase.numer != 0) { + // Mach time units times numer over denom are nanoseconds. A long double keeps the + // product of a long-running process from overflowing. + long double ticks = (long double)usage.ri_user_time + (long double)usage.ri_system_time; + row->cpu = (unsigned long long)(ticks * lithe_timebase.numer / lithe_timebase.denom / 1000.0L); + row->has_cpu = 1; + } + row->has_compressed = lithe_compressed(pids[i], &row->compressed); + } int responsible = lithe_responsible != NULL ? (int)lithe_responsible(pids[i]) : 0; row->responsible = responsible > 0 ? responsible : 0; } free(pids); return written; } + +typedef struct { + int pid; + unsigned long long accelerator; + // busy is the GPU time of one client of the accelerator, in nanoseconds. + unsigned long long busy; +} lithe_gpu_client; + +// lithe_pid_wanted says whether pid is one of the count IDs in wanted. +static int lithe_pid_wanted(int pid, const int *wanted, int count) { + for (int i = 0; i < count; i++) { + if (wanted[i] == pid) { + return 1; + } + } + return 0; +} + +// lithe_creator_pid reads the process that opened an accelerator client from its creator +// property, which reads "pid 123, name"; it returns -1 when there is none. +static int lithe_creator_pid(io_registry_entry_t client) { + CFTypeRef creator = IORegistryEntryCreateCFProperty(client, CFSTR("IOUserClientCreator"), kCFAllocatorDefault, 0); + int pid = -1; + if (creator != NULL) { + char text[128]; + if (CFGetTypeID(creator) == CFStringGetTypeID() && + CFStringGetCString((CFStringRef)creator, text, sizeof(text), kCFStringEncodingUTF8) && + sscanf(text, "pid %d", &pid) != 1) { + pid = -1; + } + CFRelease(creator); + } + return pid; +} + +// lithe_client_busy sums the GPU time an accelerator client reports in its AppUsage property, +// the counters Activity Monitor reads for its GPU column. +static unsigned long long lithe_client_busy(io_registry_entry_t client) { + CFTypeRef usage = IORegistryEntryCreateCFProperty(client, CFSTR("AppUsage"), kCFAllocatorDefault, 0); + unsigned long long busy = 0; + if (usage != NULL) { + if (CFGetTypeID(usage) == CFArrayGetTypeID()) { + CFIndex count = CFArrayGetCount((CFArrayRef)usage); + for (CFIndex i = 0; i < count; i++) { + CFTypeRef item = CFArrayGetValueAtIndex((CFArrayRef)usage, i); + if (CFGetTypeID(item) != CFDictionaryGetTypeID()) { + continue; + } + CFTypeRef time = CFDictionaryGetValue((CFDictionaryRef)item, CFSTR("accumulatedGPUTime")); + long long value = 0; + if (time != NULL && CFGetTypeID(time) == CFNumberGetTypeID() && + CFNumberGetValue((CFNumberRef)time, kCFNumberSInt64Type, &value) && value > 0) { + busy += (unsigned long long)value; + } + } + } + CFRelease(usage); + } + return busy; +} + +// lithe_read_gpu writes the accelerator clients of the wanted processes, up to capacity rows, +// and returns how many there are, which may exceed capacity; -1 means no accelerator could be +// listed. +static int lithe_read_gpu(const int *wanted, int wanted_count, lithe_gpu_client *rows, int capacity) { + io_iterator_t accelerators; + if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &accelerators) != KERN_SUCCESS) { + return -1; + } + int found = 0; + io_registry_entry_t accelerator; + while ((accelerator = IOIteratorNext(accelerators)) != 0) { + uint64_t id = 0; + io_iterator_t clients; + if (IORegistryEntryGetRegistryEntryID(accelerator, &id) == KERN_SUCCESS && + IORegistryEntryGetChildIterator(accelerator, kIOServicePlane, &clients) == KERN_SUCCESS) { + io_registry_entry_t client; + while ((client = IOIteratorNext(clients)) != 0) { + int pid = lithe_creator_pid(client); + if (pid > 0 && lithe_pid_wanted(pid, wanted, wanted_count)) { + if (found < capacity) { + rows[found].pid = pid; + rows[found].accelerator = id; + rows[found].busy = lithe_client_busy(client); + } + found++; + } + IOObjectRelease(client); + } + IOObjectRelease(clients); + } + IOObjectRelease(accelerator); + } + IOObjectRelease(accelerators); + return found; +} */ import "C" import ( "errors" + "fmt" + "sort" "unsafe" ) @@ -81,7 +228,7 @@ import ( // for, for the processes that start between the two calls. const processSlack = 64 -func processes() ([]Process, error) { +func processes(options Options) ([]Process, error) { listed := int(C.lithe_process_count()) if listed <= 0 { return nil, errors.New("sysinfo: the process IDs cannot be listed") @@ -91,16 +238,74 @@ func processes() ([]Process, error) { if written < 0 { return nil, errors.New("sysinfo: the process IDs cannot be listed") } + engines := gpuEngines(options.GPU) table := make([]Process, written) for i, row := range rows[:written] { - table[i] = Process{ + process := Process{ PID: int(row.pid), ParentPID: int(row.ppid), ResponsiblePID: int(row.responsible), StartTime: uint64(row.start), Name: C.GoString(&row.name[0]), MemoryBytes: uint64(row.footprint), + GPUEngines: engines[int(row.pid)], + } + if row.has_compressed != 0 { + // The footprint holds the compressed memory; what is in memory is the rest. + compressed := min(uint64(row.compressed), process.MemoryBytes) + process.MemoryBytes -= compressed + process.CompressedBytes = &compressed } + if row.has_cpu != 0 { + cpu := uint64(row.cpu) + process.CPUTime = &cpu + } + table[i] = process } return table, nil } + +// gpuClientCapacity is how many accelerator clients the first read makes room for; a process +// holds one for every device it opened, so a few dozen processes rarely hold more. +const gpuClientCapacity = 256 + +// gpuEngines reads the GPU time of the wanted processes, one engine per accelerator, in +// microseconds. A process with no accelerator client, or every process when the accelerators +// cannot be listed, has none. +func gpuEngines(wanted map[int]bool) map[int][]GPUEngine { + if len(wanted) == 0 { + return nil + } + pids := make([]C.int, 0, len(wanted)) + for pid := range wanted { + pids = append(pids, C.int(pid)) + } + clients := make([]C.lithe_gpu_client, gpuClientCapacity) + found := int(C.lithe_read_gpu(&pids[0], C.int(len(pids)), &clients[0], C.int(len(clients)))) + if found > len(clients) { + // Clients opened between two reads are left out of the second. + clients = make([]C.lithe_gpu_client, found+gpuClientCapacity) + found = min(int(C.lithe_read_gpu(&pids[0], C.int(len(pids)), &clients[0], C.int(len(clients)))), len(clients)) + } + if found <= 0 { + return nil + } + busy := map[int]map[uint64]uint64{} + for _, client := range clients[:found] { + pid := int(client.pid) + if busy[pid] == nil { + busy[pid] = map[uint64]uint64{} + } + busy[pid][uint64(client.accelerator)] += uint64(client.busy) + } + engines := make(map[int][]GPUEngine, len(busy)) + for pid, accelerators := range busy { + list := make([]GPUEngine, 0, len(accelerators)) + for id, nanoseconds := range accelerators { + list = append(list, GPUEngine{Name: fmt.Sprintf("accelerator-%x", id), BusyTime: nanoseconds / 1000}) + } + sort.Slice(list, func(i, j int) bool { return list[i].Name < list[j].Name }) + engines[pid] = list + } + return engines +} diff --git a/desktop/internal/sysinfo/process_linux.go b/desktop/internal/sysinfo/process_linux.go index 71b96b4f1e..f43cc01474 100644 --- a/desktop/internal/sysinfo/process_linux.go +++ b/desktop/internal/sysinfo/process_linux.go @@ -1,14 +1,20 @@ package sysinfo import ( + "bufio" "os" + "sort" "strconv" "strings" ) +// userHz is the unit of the processor times in /proc/pid/stat. The kernel reports them in +// USER_HZ, which is 100 on every architecture Lithe is built for. +const userHz = 100 + // processes reads /proc. Linux gives an orphan to init or a subreaper, so the parent IDs are // never stale and the start time is not read. -func processes() ([]Process, error) { +func processes(options Options) ([]Process, error) { entries, err := os.ReadDir("/proc") if err != nil { return nil, err @@ -21,14 +27,18 @@ func processes() ([]Process, error) { continue } if row, ok := readProcess(pid, page); ok { + if options.GPU[pid] { + row.GPUEngines = drmEngines(pid) + } table = append(table, row) } } return table, nil } -// readProcess reads the parent and name from /proc/pid/stat and the memory from -// /proc/pid/statm; false when the process exited while it was read. +// readProcess reads the parent, name and processor time from /proc/pid/stat, the memory +// from /proc/pid/statm and the swapped-out memory from /proc/pid/status; false when the +// process exited while it was read. func readProcess(pid int, page uint64) (Process, bool) { dir := "/proc/" + strconv.Itoa(pid) + "/" stat, err := os.ReadFile(dir + "stat") @@ -50,13 +60,57 @@ func readProcess(pid int, page uint64) (Process, bool) { if err != nil { return Process{}, false } - row := Process{PID: pid, ParentPID: parent, Name: text[open+1 : close]} + row := Process{PID: pid, ParentPID: parent, Name: text[open+1 : close], CPUTime: processorTime(fields)} if statm, err := os.ReadFile(dir + "statm"); err == nil { row.MemoryBytes = privatePages(string(statm)) * page } + if status, err := os.ReadFile(dir + "status"); err == nil { + row.CompressedBytes = swappedOut(string(status)) + } return row, true } +// processorTime is the user and system time of the stat fields after the name, in +// microseconds; nil when the fields do not hold them. +func processorTime(fields []string) *uint64 { + // utime and stime are fields 14 and 15 of the line; the fields here start at the third. + if len(fields) < 13 { + return nil + } + user, err := strconv.ParseUint(fields[11], 10, 64) + if err != nil { + return nil + } + system, err := strconv.ParseUint(fields[12], 10, 64) + if err != nil { + return nil + } + total := (user + system) * (1_000_000 / userHz) + return &total +} + +// swappedOut is the VmSwap line of a status file in bytes, nil when there is none, as for a +// kernel thread. +func swappedOut(status string) *uint64 { + for line := range strings.SplitSeq(status, "\n") { + value, ok := strings.CutPrefix(line, "VmSwap:") + if !ok { + continue + } + fields := strings.Fields(value) + if len(fields) != 2 || fields[1] != "kB" { + return nil + } + kilobytes, err := strconv.ParseUint(fields[0], 10, 64) + if err != nil { + return nil + } + bytes := kilobytes * 1024 + return &bytes + } + return nil +} + // privatePages is the resident pages of a statm line less its shared ones. func privatePages(statm string) uint64 { fields := strings.Fields(statm) @@ -73,3 +127,88 @@ func privatePages(statm string) uint64 { } return resident - shared } + +// drmEngines reads the GPU time of a process from the fdinfo of its open DRM files, which +// the kernel's drm-usage-stats give per engine, and names each engine by its device. Files +// of one DRM client, as a duplicated descriptor, count once. +func drmEngines(pid int) []GPUEngine { + dir := "/proc/" + strconv.Itoa(pid) + "/" + descriptors, err := os.ReadDir(dir + "fd") + if err != nil { + return nil + } + clients := map[string]bool{} + busy := map[string]uint64{} + for _, descriptor := range descriptors { + target, err := os.Readlink(dir + "fd/" + descriptor.Name()) + if err != nil || !strings.HasPrefix(target, "/dev/dri/") { + continue + } + info, err := os.ReadFile(dir + "fdinfo/" + descriptor.Name()) + if err != nil { + continue + } + client, engines := drmUsage(string(info)) + if client == "" || clients[client] { + continue + } + clients[client] = true + for name, nanoseconds := range engines { + busy[name] += nanoseconds + } + } + if len(busy) == 0 { + return nil + } + engines := make([]GPUEngine, 0, len(busy)) + for name, nanoseconds := range busy { + engines = append(engines, GPUEngine{Name: name, BusyTime: nanoseconds / 1000}) + } + sort.Slice(engines, func(i, j int) bool { return engines[i].Name < engines[j].Name }) + return engines +} + +// drmUsage parses one DRM fdinfo: the client, as its device and ID, and the nanoseconds of +// every engine named by device and engine. The client is empty when the file reports no +// client ID. +func drmUsage(info string) (string, map[string]uint64) { + var driver, device, id string + times := map[string]uint64{} + scanner := bufio.NewScanner(strings.NewReader(info)) + for scanner.Scan() { + key, value, ok := strings.Cut(scanner.Text(), ":") + if !ok { + continue + } + value = strings.TrimSpace(value) + switch { + case key == "drm-driver": + driver = value + case key == "drm-pdev": + device = value + case key == "drm-client-id": + id = value + case strings.HasPrefix(key, "drm-engine-") && !strings.HasPrefix(key, "drm-engine-capacity-"): + number, ok := strings.CutSuffix(value, " ns") + if !ok { + continue + } + nanoseconds, err := strconv.ParseUint(strings.TrimSpace(number), 10, 64) + if err != nil { + continue + } + times[strings.TrimPrefix(key, "drm-engine-")] = nanoseconds + } + } + if id == "" { + return "", nil + } + if device == "" { + device = driver + } + engines := make(map[string]uint64, len(times)) + for name, nanoseconds := range times { + engines[device+"/"+name] = nanoseconds + } + return device + "#" + id, engines +} diff --git a/desktop/internal/sysinfo/process_linux_test.go b/desktop/internal/sysinfo/process_linux_test.go new file mode 100644 index 0000000000..3d625f1e5b --- /dev/null +++ b/desktop/internal/sysinfo/process_linux_test.go @@ -0,0 +1,61 @@ +package sysinfo + +import ( + "reflect" + "strings" + "testing" +) + +// TestProcessorTimeReadsUserAndSystemTicks checks that utime and stime, fields 14 and 15 of +// a stat line, are added and turned from USER_HZ ticks into microseconds. +func TestProcessorTimeReadsUserAndSystemTicks(t *testing.T) { + line := "S 1 100 100 0 -1 4194560 2000 0 3 0 150 25 0 0 20 0 4 0 9000 1000000 300" + cpu := processorTime(strings.Fields(line)) + if cpu == nil || *cpu != 1_750_000 { + t.Fatalf("processorTime = %v, want 1750000", cpu) + } + if processorTime(strings.Fields("S 1 100")) != nil { + t.Fatal("a short stat line has a processor time") + } +} + +// TestSwappedOutReadsVmSwap checks that the VmSwap line of a status file is read in bytes and +// that a status without one, as a kernel thread's, has none. +func TestSwappedOutReadsVmSwap(t *testing.T) { + status := "Name:\tnode\nVmRSS:\t 51200 kB\nVmSwap:\t 1536 kB\nThreads:\t11\n" + swapped := swappedOut(status) + if swapped == nil || *swapped != 1536*1024 { + t.Fatalf("swappedOut = %v, want %d", swapped, 1536*1024) + } + if swappedOut("Name:\tkthreadd\nThreads:\t1\n") != nil { + t.Fatal("a status without VmSwap has swapped-out memory") + } +} + +// TestDRMUsageNamesEnginesByDevice checks that the engine times of a DRM fdinfo are named by +// device and engine, that the capacity lines and lines without nanoseconds are skipped, and +// that a file without a client ID reports no client. +func TestDRMUsageNamesEnginesByDevice(t *testing.T) { + info := strings.Join([]string{ + "pos:\t0", + "drm-driver:\tamdgpu", + "drm-pdev:\t0000:03:00.0", + "drm-client-id:\t42", + "drm-engine-gfx:\t1500000 ns", + "drm-engine-capacity-gfx:\t2", + "drm-engine-compute:\t250000 ns", + "drm-memory-vram:\t1024 KiB", + }, "\n") + client, engines := drmUsage(info) + want := map[string]uint64{"0000:03:00.0/gfx": 1500000, "0000:03:00.0/compute": 250000} + if client != "0000:03:00.0#42" || !reflect.DeepEqual(engines, want) { + t.Fatalf("drmUsage = %q %v, want client 0000:03:00.0#42 and %v", client, engines, want) + } + client, engines = drmUsage("drm-driver:\ti915\ndrm-client-id:\t7\ndrm-engine-render:\t30 ns\n") + if client != "i915#7" || !reflect.DeepEqual(engines, map[string]uint64{"i915/render": 30}) { + t.Fatalf("drmUsage without a device = %q %v, want the driver as the device", client, engines) + } + if client, _ := drmUsage("pos:\t0\nflags:\t02\n"); client != "" { + t.Fatalf("a file that is not a DRM client reports client %q", client) + } +} diff --git a/desktop/internal/sysinfo/process_test.go b/desktop/internal/sysinfo/process_test.go index f4adb01e1e..2846271fa8 100644 --- a/desktop/internal/sysinfo/process_test.go +++ b/desktop/internal/sysinfo/process_test.go @@ -22,7 +22,8 @@ func TestProcessHelper(t *testing.T) { } // TestProcessesListsThisProcessAndItsChild checks that the table has this process under its -// parent, with a name and memory, and a child it started under it. +// parent, with a name, memory, compressed memory and processor time, and a child it started +// under it, whose graphics use is not read because the options do not name it. func TestProcessesListsThisProcessAndItsChild(t *testing.T) { switch runtime.GOOS { case "darwin", "linux", "windows": @@ -51,7 +52,7 @@ func TestProcessesListsThisProcessAndItsChild(t *testing.T) { } }) - table, err := Processes() + table, err := Processes(Options{GPU: map[int]bool{os.Getpid(): true}}) if err != nil { t.Fatal(err) } @@ -69,6 +70,9 @@ func TestProcessesListsThisProcessAndItsChild(t *testing.T) { if self.ParentPID != os.Getppid() || self.Name == "" || self.MemoryBytes == 0 { t.Fatalf("this process = %+v, want parent %d, a name and memory", self, os.Getppid()) } + if self.CPUTime == nil || self.CompressedBytes == nil { + t.Fatalf("this process = %+v, want its processor time and compressed memory", self) + } started, ok := rows[child.Process.Pid] if !ok { t.Fatalf("the child %d is not in the table", child.Process.Pid) @@ -76,6 +80,9 @@ func TestProcessesListsThisProcessAndItsChild(t *testing.T) { if started.ParentPID != os.Getpid() { t.Fatalf("the child = %+v, want parent %d", started, os.Getpid()) } + if started.GPUMemoryBytes != nil || len(started.GPUEngines) != 0 { + t.Fatalf("the child = %+v, want no graphics use read", started) + } if self.StartTime != 0 && started.StartTime != 0 && started.StartTime < self.StartTime { t.Fatalf("the child started at %d, before this process at %d", started.StartTime, self.StartTime) } diff --git a/desktop/internal/sysinfo/process_windows.go b/desktop/internal/sysinfo/process_windows.go index 803427d1df..18ede794c3 100644 --- a/desktop/internal/sysinfo/process_windows.go +++ b/desktop/internal/sysinfo/process_windows.go @@ -15,14 +15,21 @@ type processMemoryCountersEx2 struct { sharedCommitUsage uint64 } -// processes reads a Toolhelp snapshot, then each process's start time and memory. A process -// this user may not open keeps a zero start time and memory. -func processes() ([]Process, error) { +// processes reads a Toolhelp snapshot, then each process's start time, processor time and +// memory, and the graphics use of the processes options name. A process this user may not +// open keeps a zero start time and memory and no other facts. +func processes(options Options) ([]Process, error) { snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) if err != nil { return nil, err } defer windows.CloseHandle(snapshot) + var adapters []gpuAdapter + if len(options.GPU) > 0 { + var close func() + adapters, close = openGPUAdapters() + defer close() + } var entry windows.ProcessEntry32 entry.Size = uint32(unsafe.Sizeof(entry)) var table []Process @@ -32,7 +39,11 @@ func processes() ([]Process, error) { ParentPID: int(entry.ParentProcessID), Name: windows.UTF16ToString(entry.ExeFile[:]), } - row.StartTime, row.MemoryBytes = processFacts(entry.ProcessID) + var gpu []gpuAdapter + if options.GPU[row.PID] { + gpu = adapters + } + readFacts(&row, gpu) table = append(table, row) } if !errors.Is(err, windows.ERROR_NO_MORE_FILES) { @@ -41,47 +52,64 @@ func processes() ([]Process, error) { return table, nil } -// processFacts is when the process of pid started, in microseconds since 1970, and its private -// working set; zero for what cannot be read. -func processFacts(pid uint32) (start, memory uint64) { - if pid == 0 { +// readFacts fills what the process of row says about itself: when it started, its processor +// time, its memory, and its use of the adapters given; what cannot be read is left zero or nil. +func readFacts(row *Process, adapters []gpuAdapter) { + if row.PID == 0 { // The System Idle Process cannot be opened. - return 0, 0 + return } - // Reading the memory counters needs PROCESS_VM_READ as well; without it the start time - // is still read. + // Reading the memory counters needs PROCESS_VM_READ as well; without it the times are + // still read. + pid := uint32(row.PID) handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_VM_READ, false, pid) readMemory := err == nil if !readMemory { if handle, err = windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid); err != nil { - return 0, 0 + return } } defer windows.CloseHandle(handle) var creation, exit, kernel, user windows.Filetime if windows.GetProcessTimes(handle, &creation, &exit, &kernel, &user) == nil { - start = uint64(max(0, creation.Nanoseconds()/1000)) + row.StartTime = uint64(max(0, creation.Nanoseconds()/1000)) + // Kernel and user times count 100-nanosecond intervals. + cpu := (filetimeTicks(kernel) + filetimeTicks(user)) / 10 + row.CPUTime = &cpu } if readMemory { - memory = privateWorkingSet(handle) + row.MemoryBytes, row.CompressedBytes = privateMemory(handle) + } + if len(adapters) > 0 { + dedicated, engines := processGPU(handle, adapters) + row.GPUMemoryBytes = dedicated + row.GPUEngines = engines } - return start, memory } -// privateWorkingSet is what Task Manager's Memory column shows for the process of handle. On -// a system older than Windows 10 1809 it is the whole working set. -func privateWorkingSet(handle windows.Handle) uint64 { +// filetimeTicks is a duration FILETIME as its count of 100-nanosecond intervals. +func filetimeTicks(time windows.Filetime) uint64 { + return uint64(time.HighDateTime)<<32 | uint64(time.LowDateTime) +} + +// privateMemory is what Task Manager's Memory column shows for the process of handle, its +// private working set, and the private commit outside it, which holds what Windows compressed +// or wrote to the page file. On a system older than Windows 10 1809 the memory is the whole +// working set and the rest is not read. +func privateMemory(handle windows.Handle) (uint64, *uint64) { if getProcessMemoryInfo.Find() != nil { - return 0 + return 0, nil } var counters processMemoryCountersEx2 counters.cb = uint32(unsafe.Sizeof(counters)) if ok, _, _ := getProcessMemoryInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&counters)), uintptr(counters.cb)); ok != 0 { - return uint64(counters.privateWorkingSetSize) + resident := uint64(counters.privateWorkingSetSize) + outside := uint64(counters.privateUsage) - min(uint64(counters.privateUsage), resident) + return resident, &outside } counters.cb = uint32(unsafe.Sizeof(counters.processMemoryCounters)) if ok, _, _ := getProcessMemoryInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&counters)), uintptr(counters.cb)); ok != 0 { - return uint64(counters.workingSetSize) + return uint64(counters.workingSetSize), nil } - return 0 + return 0, nil } diff --git a/desktop/internal/sysinfo/sysinfo_other.go b/desktop/internal/sysinfo/sysinfo_other.go index c99ccc204b..03d6428d14 100644 --- a/desktop/internal/sysinfo/sysinfo_other.go +++ b/desktop/internal/sysinfo/sysinfo_other.go @@ -16,4 +16,4 @@ func residentBytes() uint64 { return 0 } func diskFree(string) uint64 { return 0 } -func processes() ([]Process, error) { return nil, errors.ErrUnsupported } +func processes(Options) ([]Process, error) { return nil, errors.ErrUnsupported } diff --git a/desktop/internal/workbench/memory_monitor.go b/desktop/internal/workbench/memory_monitor.go index 8fc2ff4e65..a780f3f7d7 100644 --- a/desktop/internal/workbench/memory_monitor.go +++ b/desktop/internal/workbench/memory_monitor.go @@ -25,6 +25,12 @@ import ( // on macOS it is only a chip icon, as the earlier client had, with the figures in its tooltip. // A click opens the details, which are read more often while they are shown. Reading runs in // the background and a failure only leaves the figures out: it never holds up the window. +// +// Every platform reports memory the same way: what is in memory, and apart from it what the +// system compressed or wrote out to disk. The processor and graphics use are the change of +// the processes' counters since the previous reading, which Core keeps in the baseline it +// returns and the next request sends back. Graphics use is read only while the details are +// shown, for the processes of the last baseline, as reading it costs more than the table. const ( // memorySampleInterval is how often the processes are read while the details are shut, @@ -34,7 +40,7 @@ const ( memoryDetailInterval = 2 * time.Second memorySampleTimeout = 5 * time.Second - memoryPanelWidth = 340 + memoryPanelWidth = 540 memoryListHeight = 220 memoryBarHeight = 6 memoryBarGap = 2 @@ -42,8 +48,18 @@ const ( memoryRowHeight = 22 memoryHeaderGap = 6 memorySectionGap = 10 + // memoryPercentWidth and memorySizeWidth are the widths of the figure columns, which line + // the legend and the list up under their headings; with them the panel leaves a part's name + // and process count, as "Language servers 2 processes", room to show in full. + memoryPercentWidth = 44 + memorySizeWidth = 80 + memoryColumnGap = 6 ) +// memoryEpoch starts the clock the readings are timed by, which only moves forward, so a +// change of the wall clock does not skew a percentage. +var memoryEpoch = time.Now() + // processMemoryKernel is the Core command the memory monitor asks. type processMemoryKernel interface { SummarizeProcessMemory(ctx context.Context, request core.MemoryRequest) (core.MemorySummary, error) @@ -153,15 +169,38 @@ func (a *App) sampleMemory(now time.Time) { return } m.sampling, m.sampledAt = true, now - roles := a.memoryRoles() - host := int64(os.Getpid()) + reading := memoryReading{host: int64(os.Getpid()), roles: a.memoryRoles(), previous: m.summary.Baseline} + if m.open { + reading.gpu = map[int]bool{int(reading.host): true} + if reading.previous != nil { + for _, process := range reading.previous.Processes { + reading.gpu[int(process.ProcessID)] = true + } + } + } + if runtime.GOOS == "windows" { + // Task Manager shows a process's processor use as a share of every logical processor. + reading.logicalProcessors = runtime.NumCPU() + } kernel := a.kernel a.background(nil, memorySampleTimeout, func(ctx context.Context) func(*App) { - summary, err := readProcessMemory(ctx, kernel, host, roles) + summary, err := readProcessMemory(ctx, kernel, reading) return func(a *App) { a.memorySampled(summary, err) } }) } +// memoryReading is what one reading sends Core besides the table: the host, the roles of the +// processes the window started, the baseline of the last reading, the processes whose +// graphics use is read, and the logical processors a processor percentage is a share of, or +// zero for one processor. +type memoryReading struct { + host int64 + roles []core.MemoryRole + previous *core.MemoryBaseline + gpu map[int]bool + logicalProcessors int +} + // memorySampled keeps a reading. Only the first failure after a reading is logged, so a // table that cannot be read is not logged every few seconds. func (a *App) memorySampled(summary core.MemorySummary, err error) { @@ -177,12 +216,16 @@ func (a *App) memorySampled(summary core.MemorySummary, err error) { m.summary, m.read, m.failed = summary, true, false } -// readProcessMemory reads the process table and has Core sum what the instance of host holds. -func readProcessMemory(ctx context.Context, kernel processMemoryKernel, host int64, roles []core.MemoryRole) (core.MemorySummary, error) { - table, err := sysinfo.Processes() +// readProcessMemory reads the process table and has Core sum what the instance of the host +// holds and how much it used since the previous reading. +func readProcessMemory(ctx context.Context, kernel processMemoryKernel, reading memoryReading) (core.MemorySummary, error) { + before := time.Since(memoryEpoch) + table, err := sysinfo.Processes(sysinfo.Options{GPU: reading.gpu}) if err != nil { return core.MemorySummary{}, err } + // The table is timed by the middle of its reading, which takes some milliseconds. + sampledAt := uint64((before + (time.Since(memoryEpoch)-before)/2) / time.Microsecond) processes := make([]core.MemoryProcess, 0, len(table)) for _, row := range table { process := core.MemoryProcess{ @@ -190,6 +233,12 @@ func readProcessMemory(ctx context.Context, kernel processMemoryKernel, host int ParentProcessID: int64(row.ParentPID), Name: row.Name, Bytes: row.MemoryBytes, + CompressedBytes: row.CompressedBytes, + GPUMemoryBytes: row.GPUMemoryBytes, + CPUTime: row.CPUTime, + } + for _, engine := range row.GPUEngines { + process.GPUEngines = append(process.GPUEngines, core.GPUEngineTime{Engine: engine.Name, BusyTime: engine.BusyTime}) } // A zero is a fact the system did not give, which the request leaves out. if row.ResponsiblePID != 0 { @@ -202,7 +251,17 @@ func readProcessMemory(ctx context.Context, kernel processMemoryKernel, host int } processes = append(processes, process) } - return kernel.SummarizeProcessMemory(ctx, core.MemoryRequest{HostProcessID: host, Processes: processes, Roles: roles}) + request := core.MemoryRequest{ + HostProcessID: reading.host, + Processes: processes, + Roles: reading.roles, + SampledAt: &sampledAt, + Previous: reading.previous, + } + if reading.logicalProcessors > 0 { + request.LogicalProcessors = &reading.logicalProcessors + } + return kernel.SummarizeProcessMemory(ctx, request) } // memoryRoles names the processes this window started: each language server and each plugin @@ -339,7 +398,7 @@ func (a *App) memoryColor(kind string) gfx.Color { // memoryHelp is the explanation behind the details' ⓘ: what is counted, and which figure the // system gives for each process. func memoryHelp(language i18n.Language) string { - help := i18n.Shared(language, "desktop.memory.help") + help := i18n.Shared(language, "desktop.memory.help") + "\n\n" + i18n.Shared(language, "desktop.memory.helpFigures") switch runtime.GOOS { case "darwin": help += "\n\n" + i18n.Shared(language, "desktop.memory.helpMacOS") @@ -384,10 +443,12 @@ func (a *App) memoryDetails(c ui.C, anchor ui.Box) { ui.Text(c, i18n.Shared(language, "desktop.memory.reading")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) default: parts := m.parts() + columns := m.columns() + a.memoryStats(c.Part("stats"), language) a.memoryBar(c.Part("bar"), parts) - a.memoryLegend(c.Part("legend"), language, parts) + a.memoryLegend(c.Part("legend"), language, parts, columns) ui.Divider(c) - a.memoryEntries(c.Part("entries"), language) + a.memoryEntries(c.Part("entries"), language, columns) } }) }) @@ -421,18 +482,88 @@ func (a *App) memoryBar(c ui.C, parts []core.MemoryCategory) { }) } -// memoryLegend declares one row per part: its color, name, process count and sum. -func (a *App) memoryLegend(c ui.C, language i18n.Language, parts []core.MemoryCategory) { +// memoryColumns are the figure columns the legend and the list show besides what is in +// memory. Core gives a figure for every part and entry or for none, so one summary decides. +type memoryColumns struct { + cpu, gpu, compressed bool +} + +// columns are the columns of the last reading's figures. +func (m *memoryState) columns() memoryColumns { + usage := m.summary.MemoryUsage + return memoryColumns{cpu: usage.CPUPercent != nil, gpu: usage.GPUPercent != nil, compressed: usage.CompressedBytes != nil} +} + +// memoryPercent writes a use with its tenth, as Activity Monitor and Task Manager show it. +func memoryPercent(language i18n.Language, value *float64) string { + if value == nil { + return "" + } + return i18n.SharedFormat(language, "desktop.memory.percent", map[string]string{"value": strconv.FormatFloat(*value, 'f', 1, 64)}) +} + +// memoryStats declares the instance's figures beyond what is in memory, the total of which the +// header shows: what is compressed or swapped out, graphics memory, and the processor and +// graphics use. A figure the reading does not have is left out, and the line with all of them. +func (a *App) memoryStats(c ui.C, language i18n.Language) { + usage := a.memory.summary.MemoryUsage + var stats []string + if usage.CompressedBytes != nil { + stats = append(stats, i18n.SharedFormat(language, "desktop.memory.statCompressed", map[string]string{"value": memorySize(language, *usage.CompressedBytes)})) + } + if usage.GPUMemoryBytes != nil && *usage.GPUMemoryBytes > 0 { + stats = append(stats, i18n.SharedFormat(language, "desktop.memory.statGPUMemory", map[string]string{"value": memorySize(language, *usage.GPUMemoryBytes)})) + } + if usage.CPUPercent != nil { + stats = append(stats, i18n.SharedFormat(language, "desktop.memory.statCPU", map[string]string{"value": memoryPercent(language, usage.CPUPercent)})) + } + if usage.GPUPercent != nil { + stats = append(stats, i18n.SharedFormat(language, "desktop.memory.statGPU", map[string]string{"value": memoryPercent(language, usage.GPUPercent)})) + } + if len(stats) == 0 { + return + } + ui.Text(c, strings.Join(stats, i18n.Shared(language, "desktop.memory.statSeparator"))).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().FillWidth() +} + +// memoryHeadings declares the names of the figure columns above the legend, right-aligned over +// the figures they name. +func (a *App) memoryHeadings(c ui.C, language i18n.Language, columns memoryColumns) { + small := a.theme.Metrics.FontSizeS + heading := func(text string, width float32) { + ui.Text(c, text).FontSize(small).Color(a.colors.Subtle).Width(width).Shrink(0).TextEnd().Ellipsis() + } + ui.Row(c).FillWidth().Height(memoryRowHeight).Shrink(0).Items(ui.Center).Gap(memoryColumnGap).Children(func() { + ui.Row(c).Grow(1) + if columns.cpu { + heading(i18n.Shared(language, "desktop.memory.columnCPU"), memoryPercentWidth) + } + if columns.gpu { + heading(i18n.Shared(language, "desktop.memory.columnGPU"), memoryPercentWidth) + } + heading(i18n.Shared(language, "desktop.memory.columnInMemory"), memorySizeWidth) + if columns.compressed { + heading(i18n.Shared(language, "desktop.memory.columnCompressed"), memorySizeWidth) + } + }) +} + +// memoryLegend declares the column headings, then one row per part: its color, name, process +// count and figures. +func (a *App) memoryLegend(c ui.C, language i18n.Language, parts []core.MemoryCategory, columns memoryColumns) { ui.Column(c).FillWidth().Children(func() { + a.memoryHeadings(c.Part("headings"), language, columns) for i, part := range parts { - a.memoryRow(c.KeyInt(i), language, part.Kind, memoryKindLabel(language, part.Kind), part.ProcessCount, part.Bytes) + a.memoryRow(c.KeyInt(i), language, memoryLine{ + kind: part.Kind, name: memoryKindLabel(language, part.Kind), processes: part.ProcessCount, bytes: part.Bytes, usage: part.MemoryUsage, + }, columns) } }) } // memoryEntries declares the largest processes of the instance other than the main one, each // with what Core counts under it, and the sum of the ones past the list. -func (a *App) memoryEntries(c ui.C, language i18n.Language) { +func (a *App) memoryEntries(c ui.C, language i18n.Language, columns memoryColumns) { summary := &a.memory.summary ui.Text(c, i18n.Shared(language, "desktop.memory.processes")).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).Color(a.colors.Subtle) if len(summary.Entries) == 0 { @@ -441,7 +572,9 @@ func (a *App) memoryEntries(c ui.C, language i18n.Language) { } ui.Scroll(c.Part("list")).FillWidth().MaxHeight(memoryListHeight).Children(func() { for i, entry := range summary.Entries { - a.memoryRow(c.KeyInt(i), language, entry.Kind, entry.Name, entry.ProcessCount, entry.Bytes) + a.memoryRow(c.KeyInt(i), language, memoryLine{ + kind: entry.Kind, name: entry.Name, processes: entry.ProcessCount, bytes: entry.Bytes, usage: entry.MemoryUsage, + }, columns) } }) if summary.Omitted.Count > 0 { @@ -451,18 +584,43 @@ func (a *App) memoryEntries(c ui.C, language i18n.Language) { } } +// memoryLine is what a row of the legend or the list shows. +type memoryLine struct { + kind, name string + processes int + bytes uint64 + usage core.MemoryUsage +} + // memoryRow declares a row of the legend or the list: the part's dot, the name, how many -// processes it sums when more than one, and the size at the end. -func (a *App) memoryRow(k ui.C, language i18n.Language, kind, name string, processes int, bytes uint64) { +// processes it sums when more than one, then the figures of the columns, right-aligned. +func (a *App) memoryRow(k ui.C, language i18n.Language, line memoryLine, columns memoryColumns) { small := a.theme.Metrics.FontSizeS - ui.Row(k).FillWidth().Height(memoryRowHeight).Shrink(0).Items(ui.Center).Gap(8).Children(func() { - ui.Row(k).Size(memoryDotSize, memoryDotSize).Shrink(0).Radius(memoryDotSize / 2).Background(a.memoryColor(kind)) - ui.Text(k, name).FontSize(small).Shrink(1).MinWidth(0).Ellipsis() - if processes > 1 { - ui.Text(k, i18n.SharedFormat(language, "desktop.memory.processCount", map[string]string{"count": strconv.Itoa(processes)})). - FontSize(small).Color(a.colors.Subtle).Shrink(0) + figure := func(text string, width float32) { + ui.Text(k, text).FontSize(small).Width(width).Shrink(0).TextEnd() + } + ui.Row(k).FillWidth().Height(memoryRowHeight).Shrink(0).Items(ui.Center).Gap(memoryColumnGap).Children(func() { + ui.Row(k).Grow(1).MinWidth(0).Items(ui.Center).Gap(8).Children(func() { + ui.Row(k).Size(memoryDotSize, memoryDotSize).Shrink(0).Radius(memoryDotSize / 2).Background(a.memoryColor(line.kind)) + ui.Text(k, line.name).FontSize(small).Shrink(1).MinWidth(0).Ellipsis() + if line.processes > 1 { + ui.Text(k, i18n.SharedFormat(language, "desktop.memory.processCount", map[string]string{"count": strconv.Itoa(line.processes)})). + FontSize(small).Color(a.colors.Subtle).Shrink(0) + } + }) + if columns.cpu { + figure(memoryPercent(language, line.usage.CPUPercent), memoryPercentWidth) + } + if columns.gpu { + figure(memoryPercent(language, line.usage.GPUPercent), memoryPercentWidth) + } + figure(memorySize(language, line.bytes), memorySizeWidth) + if columns.compressed { + compressed := "" + if line.usage.CompressedBytes != nil { + compressed = memorySize(language, *line.usage.CompressedBytes) + } + figure(compressed, memorySizeWidth) } - ui.Row(k).Grow(1) - ui.Text(k, memorySize(language, bytes)).FontSize(small).Shrink(0) }) } diff --git a/desktop/internal/workbench/memory_monitor_test.go b/desktop/internal/workbench/memory_monitor_test.go index a4e2906716..f22055b740 100644 --- a/desktop/internal/workbench/memory_monitor_test.go +++ b/desktop/internal/workbench/memory_monitor_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "os" + "reflect" "sync" "testing" "time" @@ -49,25 +50,44 @@ func (k *memoryKernel) last() (core.MemoryRequest, int) { const mib = 1 << 20 +func pointerTo[T any](value T) *T { return &value } + +// memoryUsage is a figure set of the fixture: what is compressed or swapped out, in mebibytes, +// and the processor and graphics use. +func memoryUsage(compressed uint64, cpu, gpu float64) core.MemoryUsage { + return core.MemoryUsage{CompressedBytes: pointerTo(compressed * mib), CPUPercent: pointerTo(cpu), GPUPercent: pointerTo(gpu)} +} + // memorySummaryFixture is an instance with a main process, two language-server processes, // three system helpers and no plugin service, of which the list shows three entries and sums -// two more. +// two more. Every part and entry has its compressed memory and its processor and graphics use, +// and the main process holds graphics memory. func memorySummaryFixture() core.MemorySummary { + total := memoryUsage(640, 12.5, 3) + total.GPUMemoryBytes = pointerTo(uint64(96 * mib)) + host := memoryUsage(120, 8, 3) + host.GPUMemoryBytes = total.GPUMemoryBytes return core.MemorySummary{ - TotalBytes: 1536 * mib, + TotalBytes: 1536 * mib, + MemoryUsage: total, Categories: []core.MemoryCategory{ - {Kind: core.MemoryHost, Bytes: 302 * mib, ProcessCount: 1}, - {Kind: core.MemoryLanguageServer, Bytes: 1012 * mib, ProcessCount: 2}, - {Kind: core.MemoryPluginService}, - {Kind: core.MemorySystemHelper, Bytes: 210 * mib, ProcessCount: 3}, - {Kind: core.MemoryChildProcess, Bytes: 12 * mib, ProcessCount: 2}, + {Kind: core.MemoryHost, Bytes: 302 * mib, ProcessCount: 1, MemoryUsage: host}, + {Kind: core.MemoryLanguageServer, Bytes: 1012 * mib, ProcessCount: 2, MemoryUsage: memoryUsage(500, 4, 0)}, + {Kind: core.MemoryPluginService, MemoryUsage: memoryUsage(0, 0, 0)}, + {Kind: core.MemorySystemHelper, Bytes: 210 * mib, ProcessCount: 3, MemoryUsage: memoryUsage(24, 0.5, 0)}, + {Kind: core.MemoryChildProcess, Bytes: 12 * mib, ProcessCount: 2, MemoryUsage: memoryUsage(0, 0, 0)}, }, Entries: []core.MemoryEntry{ - {Kind: core.MemoryLanguageServer, Name: "Quill Tools · Quill", ProcessID: 41, Bytes: 1012 * mib, ProcessCount: 2}, - {Kind: core.MemorySystemHelper, Name: "PageRenderer", ProcessID: 52, Bytes: 180 * mib, ProcessCount: 1}, - {Kind: core.MemorySystemHelper, Name: "PageNetwork", ProcessID: 53, Bytes: 30 * mib, ProcessCount: 2}, + {Kind: core.MemoryLanguageServer, Name: "Quill Tools · Quill", ProcessID: 41, Bytes: 1012 * mib, ProcessCount: 2, MemoryUsage: memoryUsage(500, 4, 0)}, + {Kind: core.MemorySystemHelper, Name: "PageRenderer", ProcessID: 52, Bytes: 180 * mib, ProcessCount: 1, MemoryUsage: memoryUsage(15, 0.4, 0)}, + {Kind: core.MemorySystemHelper, Name: "PageNetwork", ProcessID: 53, Bytes: 30 * mib, ProcessCount: 2, MemoryUsage: memoryUsage(5, 0.1, 0)}, }, Omitted: core.MemoryOmitted{Count: 2, Bytes: 12 * mib}, + Baseline: &core.MemoryBaseline{SampledAt: 2_000_000, Processes: []core.BaselineProcess{ + {ProcessID: int64(os.Getpid()), StartTime: pointerTo(uint64(1_000)), CPUTime: pointerTo(uint64(250_000)), + GPUEngines: []core.GPUEngineTime{{Engine: "accelerator-1", BusyTime: 30_000}}}, + {ProcessID: 41, StartTime: pointerTo(uint64(1_500)), CPUTime: pointerTo(uint64(90_000))}, + }}, } } @@ -82,10 +102,13 @@ func openMemoryDetails(h *harness, want string) { } // TestMemoryDetailsShowTheSummaryOfTheWholeInstance checks that the window sends Core the -// process table with itself as the host, and that the details show Core's sums: the total, every -// part that holds something with its process count, the largest entries and the rest summed. +// process table with itself as the host, timed and with the host's processor time, and sends +// back the baseline of the reading before; and that the details show Core's sums: the total +// with the instance's other figures, every part that holds something with its process count, +// the largest entries and the rest summed, each with its use and compressed memory. func TestMemoryDetailsShowTheSummaryOfTheWholeInstance(t *testing.T) { - kernel := &memoryKernel{Client: core.NewClient(), summary: memorySummaryFixture()} + fixture := memorySummaryFixture() + kernel := &memoryKernel{Client: core.NewClient(), summary: fixture} h := newHarness(t, kernel) h.open(t.TempDir()) h.await("the first reading", func() bool { return h.app.memory.read }) @@ -97,14 +120,20 @@ func TestMemoryDetailsShowTheSummaryOfTheWholeInstance(t *testing.T) { if request.HostProcessID != int64(os.Getpid()) { t.Fatalf("host = %d, want this process %d", request.HostProcessID, os.Getpid()) } + if request.SampledAt == nil { + t.Fatal("the request does not say when the table was read") + } + if sent == 1 && request.Previous != nil { + t.Fatalf("the first request sends a baseline %+v though there was no reading before", request.Previous) + } host := false for _, process := range request.Processes { if process.ProcessID == request.HostProcessID { - host = process.Bytes > 0 && process.Name != "" + host = process.Bytes > 0 && process.Name != "" && process.CPUTime != nil } } if !host { - t.Fatalf("the table of %d processes has no named row with memory for the host", len(request.Processes)) + t.Fatalf("the table of %d processes has no named row with memory and processor time for the host", len(request.Processes)) } if got, want := h.app.memoryTooltip(), "内存:共 1.50 GB,其中 Lithe 主进程 302 MB。"; got != want { t.Fatalf("tooltip = %q, want %q", got, want) @@ -112,8 +141,11 @@ func TestMemoryDetailsShowTheSummaryOfTheWholeInstance(t *testing.T) { openMemoryDetails(h, "Quill Tools · Quill") for _, want := range []string{ - "1.50 GB", "Lithe 主进程", "302 MB", "语言服务器", "1012 MB", "系统辅助进程", "3 个进程", "210 MB", - "其他子进程", "PageRenderer", "180 MB", "PageNetwork", "另有 2 项,共 12 MB", + "1.50 GB", "压缩/换出 640 MB · 显存 96 MB · CPU 12.5% · GPU 3.0%", + "内存中", "压缩/换出", "CPU", "GPU", + "Lithe 主进程", "302 MB", "8.0%", "120 MB", "语言服务器", "1012 MB", "4.0%", "500 MB", + "系统辅助进程", "3 个进程", "210 MB", "0.5%", "24 MB", + "其他子进程", "PageRenderer", "180 MB", "0.4%", "15 MB", "PageNetwork", "0.1%", "另有 2 项,共 12 MB", } { if !h.shows(want) { t.Errorf("the details do not show %q", want) @@ -122,13 +154,36 @@ func TestMemoryDetailsShowTheSummaryOfTheWholeInstance(t *testing.T) { if h.shows("插件服务") { t.Error("the details show the plugin services, which hold nothing") } - if _, after := kernel.last(); after <= sent { + request, after := kernel.last() + if after <= sent { t.Fatalf("opening the details sent %d requests in all, want a reading beyond the first %d", after, sent) } + if !reflect.DeepEqual(request.Previous, fixture.Baseline) { + t.Fatalf("the request after a reading sends baseline %+v, want the one Core returned %+v", request.Previous, fixture.Baseline) + } +} + +// TestMemoryPercentWritesATenth checks that a use is written with its tenth and that a use the +// reading does not have is left blank. +func TestMemoryPercentWritesATenth(t *testing.T) { + for _, test := range []struct { + value *float64 + want string + }{ + {nil, ""}, + {pointerTo(0.0), "0.0%"}, + {pointerTo(12.345), "12.3%"}, + {pointerTo(100.0), "100.0%"}, + } { + if got := memoryPercent(i18n.English, test.value); got != test.want { + t.Errorf("memoryPercent(%v) = %q, want %q", test.value, got, test.want) + } + } } // TestMemoryDetailsHideTheFiguresWhileTheReadingFails checks that a failed reading hides the -// figures instead of keeping stale ones, and that the next reading shows them again. +// figures instead of keeping stale ones, and that the next reading shows them again, with only +// the columns it has figures for. func TestMemoryDetailsHideTheFiguresWhileTheReadingFails(t *testing.T) { kernel := &memoryKernel{Client: core.NewClient(), err: errors.New("the table could not be read")} h := newHarness(t, kernel) @@ -146,9 +201,12 @@ func TestMemoryDetailsHideTheFiguresWhileTheReadingFails(t *testing.T) { // The next paint reads again without waiting for the interval. h.app.post(func(a *App) { a.memory.sampledAt = time.Time{} }) h.await("a reading after the failure", func() bool { return h.shows("Lithe 目前没有启动其他进程。") }) - if h.shows("无法读取进程内存。") || !h.shows("302 MB") { + if h.shows("无法读取进程内存。") || !h.shows("302 MB") || !h.shows("内存中") { t.Fatal("the details do not show the reading that followed the failure") } + if h.shows("压缩/换出") || h.shows("%") { + t.Fatal("the details show a column the reading has no figures for") + } } // TestMemorySizeWritesWholeMegabytesThenGigabytes checks the units: a process that holds a little diff --git a/docs/assets/memory-details/README.md b/docs/assets/memory-details/README.md index b71ad1c796..996e1aeb63 100644 --- a/docs/assets/memory-details/README.md +++ b/docs/assets/memory-details/README.md @@ -6,8 +6,8 @@ Quill Tools 语言服务器和系统辅助进程),不代表真实进程的 | 场景 | 深色中文 | 浅色英文 | | --- | --- | --- | -| 实例启动了语言服务器、系统辅助进程和其他子进程:顶部是总量和 ⓘ 说明,下面是按类别堆叠的条、各类别图例(多个进程时显示进程数),以及占用最多的进程和其余项的合计 | [截图](memory-details-dark.png) | [截图](memory-details-light.png) | -| 只有 Lithe 主进程:只显示主进程一类,进程列表给出说明,不列 0 MB 的类别 | [截图](memory-details-host-only-dark.png) | [截图](memory-details-host-only-light.png) | +| 实例启动了语言服务器、系统辅助进程和其他子进程:顶部是总量(只算“内存中”)和 ⓘ 说明,下一行是整个实例的压缩/换出、显存、CPU 和 GPU;然后是按类别堆叠的条、各类别图例(多个进程时显示进程数),以及占用最多的进程和其余项的合计。图例和进程列表右侧依次是 CPU、GPU、内存中、压缩/换出四列,列标题与数值右对齐 | [截图](memory-details-dark.png) | [截图](memory-details-light.png) | +| 只有 Lithe 主进程,且读数不含压缩、CPU、GPU 等数据:只显示主进程一类和“内存中”一列,没有数据的列和统计行不显示,进程列表给出说明,不列 0 MB 的类别 | [截图](memory-details-host-only-dark.png) | [截图](memory-details-host-only-light.png) | 复验:设置 `LITHE_VISUAL_OUTPUT_DIR`,通过 `scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/workbench -run '^TestVisualMemoryDetails$' diff --git a/docs/assets/memory-details/memory-details-dark.png b/docs/assets/memory-details/memory-details-dark.png index e7cb06f58c..ebbb3264c1 100644 Binary files a/docs/assets/memory-details/memory-details-dark.png and b/docs/assets/memory-details/memory-details-dark.png differ diff --git a/docs/assets/memory-details/memory-details-host-only-dark.png b/docs/assets/memory-details/memory-details-host-only-dark.png index 86d91b0879..a914523d87 100644 Binary files a/docs/assets/memory-details/memory-details-host-only-dark.png and b/docs/assets/memory-details/memory-details-host-only-dark.png differ diff --git a/docs/assets/memory-details/memory-details-host-only-light.png b/docs/assets/memory-details/memory-details-host-only-light.png index c1965d5bf2..75c0a9e429 100644 Binary files a/docs/assets/memory-details/memory-details-host-only-light.png and b/docs/assets/memory-details/memory-details-host-only-light.png differ diff --git a/docs/assets/memory-details/memory-details-light.png b/docs/assets/memory-details/memory-details-light.png index 15a2459c5b..652f5d5223 100644 Binary files a/docs/assets/memory-details/memory-details-light.png and b/docs/assets/memory-details/memory-details-light.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 8a679a8569..2bcc433ea4 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,10 +28,12 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" -# Lithe-core-rust #44 (branch feat/console-ansi-style, not yet merged): outputStyle.decode turns -# console output with ANSI escapes into plain lines and styled ranges, carrying each console's -# state from chunk to chunk, for the colors of the Run, Build and Test consoles. It is on top of -# #43, squash-merged into main: processMemory.summarize +# Lithe-core-rust #45, squash-merged into main: processMemory.summarize also sums the memory the +# system compressed or swapped out, graphics memory, and the processor and graphics use between +# two tables, which the host sends back as a baseline. It is on top of #44, squash-merged into +# main: outputStyle.decode turns console output with ANSI escapes into plain lines and styled +# ranges, carrying each console's state from chunk to chunk, for the colors of the Run, Build and +# Test consoles. It is on top of #43, squash-merged into main: processMemory.summarize # sorts the native process table into the parts of a Lithe instance (main process, language # servers, plugin services, their child processes and the system helpers macOS holds the main # process responsible for) for the memory details of the status bar. It is on top of #42, @@ -88,7 +90,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="cdc025851e0b291f00415d9d4e43ce9079e1e83e" +PINNED_CORE_REVISION="40711b146dc387fa6148ad2d0a4b758fc8e89909" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 3c55c07219..836eb088bd 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11003,9 +11003,20 @@ "desktop.memory.unavailable": "Process memory could not be read.", "desktop.memory.noOtherProcesses": "Lithe has not started any other process.", "desktop.memory.help": "Counts the Lithe main process and every process that belongs to it: language servers, plugin services, child processes such as terminals and runs, and the helpers the system starts for Lithe, such as the WebKit processes that show web pages and previews.", - "desktop.memory.helpMacOS": "Each figure is what the Memory column of Activity Monitor shows.", - "desktop.memory.helpWindows": "Each figure is the private working set, which the Memory column of Task Manager shows.", - "desktop.memory.helpLinux": "Each figure is the resident memory less its shared pages.", + "desktop.memory.helpMacOS": "“In memory” and “Swapped out” add up to what the Memory column of Activity Monitor shows; “Swapped out” is its compressed part. CPU counts one fully busy core as 100%, as Activity Monitor does.", + "desktop.memory.helpWindows": "“In memory” is the private working set, which the Memory column of Task Manager shows. Windows does not report how much of a process it compressed, so “Swapped out” is the private commit outside the working set: memory compressed, written to the page file or not yet touched, an upper bound. “GPU memory” is what the Dedicated GPU memory column of Task Manager shows. CPU counts all logical processors fully busy as 100%, as Task Manager does.", + "desktop.memory.helpLinux": "“In memory” is the resident memory less its shared pages; “Swapped out” is what was moved to swap, zram included. CPU counts one fully busy core as 100%, as top does; GPU comes from the engine times the DRM driver reports.", + "desktop.memory.helpFigures": "“In memory” is the physical memory the processes hold now; the status bar and the total count only this. “Swapped out” is what the system compressed or wrote to disk for them, which “In memory” does not include. CPU and GPU are the use between two readings, GPU being the busiest graphics engine; the GPU is read only while the details are open, so its use shows from the second reading on.", + "desktop.memory.percent": "{value}%", + "desktop.memory.columnCPU": "CPU", + "desktop.memory.columnGPU": "GPU", + "desktop.memory.columnInMemory": "In memory", + "desktop.memory.columnCompressed": "Swapped out", + "desktop.memory.statCompressed": "Swapped out {value}", + "desktop.memory.statGPUMemory": "GPU memory {value}", + "desktop.memory.statCPU": "CPU {value}", + "desktop.memory.statGPU": "GPU {value}", + "desktop.memory.statSeparator": " · ", "desktop.command.fold": "Fold", "desktop.command.unfold": "Unfold", "desktop.command.foldAll": "Fold All", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index b99682ff26..3ec7f38721 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11003,9 +11003,20 @@ "desktop.memory.unavailable": "无法读取进程内存。", "desktop.memory.noOtherProcesses": "Lithe 目前没有启动其他进程。", "desktop.memory.help": "统计 Lithe 主进程和属于它的全部进程:语言服务器、插件服务、终端和运行任务等子进程,以及系统代 Lithe 启动的辅助进程,例如显示网页和预览的 WebKit 进程。", - "desktop.memory.helpMacOS": "数值与活动监视器“内存”一列显示的一致。", - "desktop.memory.helpWindows": "数值是专用工作集,即任务管理器“内存”一列显示的值。", - "desktop.memory.helpLinux": "数值是常驻内存减去共享页。", + "desktop.memory.helpMacOS": "“内存中”加“压缩/换出”就是活动监视器“内存”一列的值,“压缩/换出”是其中被压缩的部分。CPU 以一个核心占满为 100%,与活动监视器一致。", + "desktop.memory.helpWindows": "“内存中”是专用工作集,即任务管理器“内存”一列的值。Windows 不单独报告进程被压缩了多少,“压缩/换出”是已提交的专用内存中不在工作集里的部分:被压缩、写入页面文件或尚未用到的内存,所以它是上限。“显存”是任务管理器“专用 GPU 内存”一列的值。CPU 以全部逻辑处理器占满为 100%,与任务管理器一致。", + "desktop.memory.helpLinux": "“内存中”是常驻内存减去共享页,“压缩/换出”是换出到交换区(包括 zram)的部分。CPU 以一个核心占满为 100%,与 top 一致;GPU 来自 DRM 驱动报告的引擎时间。", + "desktop.memory.helpFigures": "“内存中”是进程现在占用的物理内存,状态栏和总计都只算这一项。“压缩/换出”是系统为这些进程压缩或写到磁盘上的内存,不计入“内存中”。CPU 和 GPU 是相邻两次读取之间的占用率,GPU 取最忙的那个图形引擎;面板打开后才读取 GPU,第二次读取起才有 GPU 占用。", + "desktop.memory.percent": "{value}%", + "desktop.memory.columnCPU": "CPU", + "desktop.memory.columnGPU": "GPU", + "desktop.memory.columnInMemory": "内存中", + "desktop.memory.columnCompressed": "压缩/换出", + "desktop.memory.statCompressed": "压缩/换出 {value}", + "desktop.memory.statGPUMemory": "显存 {value}", + "desktop.memory.statCPU": "CPU {value}", + "desktop.memory.statGPU": "GPU {value}", + "desktop.memory.statSeparator": " · ", "desktop.command.fold": "折叠", "desktop.command.unfold": "展开", "desktop.command.foldAll": "全部折叠", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 6ce2aa952a..bf7a224026 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -12330,6 +12330,34 @@ "desktop" ] }, + { + "id": "desktop.memory.columnCPU", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.columnCompressed", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.columnGPU", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.columnInMemory", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.memory.gigabytes", "description": "Memory monitor in the status bar.", @@ -12347,6 +12375,13 @@ "desktop" ] }, + { + "id": "desktop.memory.helpFigures", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.memory.helpLinux", "description": "Memory monitor in the status bar.", @@ -12421,6 +12456,16 @@ "value": "string" } }, + { + "id": "desktop.memory.percent", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, { "id": "desktop.memory.processCount", "description": "Memory monitor in the status bar.", @@ -12452,6 +12497,53 @@ "desktop" ] }, + { + "id": "desktop.memory.statCPU", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.memory.statCompressed", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.memory.statGPU", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.memory.statGPUMemory", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.memory.statSeparator", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.memory.status", "description": "Memory monitor in the status bar.", diff --git a/shared/platform-feature-matrix/features/memory-monitor.json b/shared/platform-feature-matrix/features/memory-monitor.json index b99567b22f..70304c08a0 100644 --- a/shared/platform-feature-matrix/features/memory-monitor.json +++ b/shared/platform-feature-matrix/features/memory-monitor.json @@ -22,11 +22,12 @@ "desktop/internal/workbench/memory_monitor_test.go", "desktop/internal/core/process_memory.go", "desktop/internal/sysinfo/process.go", - "desktop/internal/sysinfo/process_windows.go" + "desktop/internal/sysinfo/process_windows.go", + "desktop/internal/sysinfo/gpu_windows.go" ] }, "owner": "Workbench", - "verification": "运行带语言服务器、终端和 Markdown/HTML 预览的项目,点击状态栏内存项打开详情:顶部总计等于各类别之和,按类别堆叠的条与图例显示 Lithe 主进程、语言服务器(插件名 · 语言)、插件服务、系统辅助进程(macOS 的 WebKit 进程)和其他子进程,0 字节的类别不显示;进程列表按占用从大到小,超过上限的合计为“另有 N 项”。macOS 对照活动监视器“内存”列,Windows 对照任务管理器“内存”列(专用工作集),数值一致。弹窗内容不被截断;关闭详情后每 10 秒采样一次,打开时每 2 秒;读取失败时隐藏数字并显示无法读取,恢复后重新显示。从终端启动时 macOS 把 WebKit 进程归给终端,系统辅助进程不计入,应从 Finder 或 Dock 启动验证。macOS 状态栏只显示内存图标,悬停提示显示总计和 Lithe 主进程;Windows 状态栏显示总计与 Lithe 主进程数值。", + "verification": "运行带语言服务器、终端和 Markdown/HTML 预览的项目,点击状态栏内存项打开详情:顶部总计只算“内存中”且等于各类别之和,下一行是整个实例的压缩/换出、显存(仅 Windows)、CPU 和 GPU,没有数据的项不显示;按类别堆叠的条与图例显示 Lithe 主进程、语言服务器(插件名 · 语言)、插件服务、系统辅助进程(macOS 的 WebKit 进程)和其他子进程,0 字节的类别不显示;图例和进程列表右侧依次是 CPU、GPU、内存中、压缩/换出四列,列标题与数值右对齐,进程列表按内存中从大到小,超过上限的合计为“另有 N 项”。macOS 对照活动监视器:内存中 + 压缩/换出等于“内存”列,压缩/换出等于“压缩内存”列,CPU 对照“% CPU”(按单核计);Windows 对照任务管理器“详细信息”页:内存中等于“内存(专用工作集)”,显存对照“专用 GPU 内存”,CPU 对照“CPU”(占全部核心的比例),GPU 对照“GPU”(最忙引擎)。CPU 与 GPU 要打开详情后第二次采样才出现。弹窗内容不被截断;关闭详情后每 10 秒采样一次,打开时每 2 秒;读取失败时隐藏数字并显示无法读取,恢复后重新显示。从终端启动时 macOS 把 WebKit 进程归给终端,系统辅助进程不计入,应从 Finder 或 Dock 启动验证。macOS 状态栏只显示内存图标,悬停提示显示总计和 Lithe 主进程;Windows 状态栏显示总计与 Lithe 主进程数值。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -46,5 +47,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:进程表由 sysinfo 原生读取(macOS proc_pid_rusage 物理占用与 responsible PID、Windows 专用工作集、Linux 常驻内存减共享页),Core 的 processMemory.summarize 把进程归到实例的各类别并求和;工作台只负责采样、命名与呈现。Linux 只有组件实现,不在矩阵平台范围内。" + "notes": "Viva:进程表由 sysinfo 原生读取,三端统一为“内存中”和“压缩/换出”两个量:macOS 用 proc_pid_rusage 物理占用减 TASK_VM_INFO 压缩量、压缩/换出为压缩量,并按 responsible PID 归属;Windows 内存中为专用工作集、压缩/换出为私有提交减专用工作集(上限值,含尚未触碰的已提交页),显存为 D3DKMT 专用显存段;Linux 内存中为常驻内存减共享页、压缩/换出为 VmSwap。CPU 与 GPU 由两次采样的累计时间差得出:macOS、Linux 按单核计,Windows 按全部核心计;GPU 取最忙引擎,只在详情打开时读取主进程和上次读数里的进程。Core 的 processMemory.summarize 把进程归到实例的各类别并求和,并返回下次采样所需的基线;工作台只负责采样、命名与呈现。原生窗口验收保持 pending。Linux 只有组件实现,不在矩阵平台范围内,读数尚未在真实 Linux 上核对。" }