// // DisplayAgent.swift — the display agent's model: what the driver reports // about the GPU's outputs (selector 84, dext/sources/session_state.h), each // connected monitor's EDID, and the macOS virtual display that would stand // for it (docs/macos-displays.md). No IOKit, no ScreenCaptureKit and only // CoreGraphics geometry types, so it builds and is tested on its own // (scripts/test-display-agent.sh); DisplayAgentRuntime.swift drives it // over the observer client. // import Foundation import CoreGraphics // struct rt_display_report / rt_display_modes (linuxu/headers/rt/display.h), // version 1. let kDisplayReportBytes = 72 + 8 * 80 let kDisplayModesBytes = 24 + 56 * 16 enum DisplayOp: UInt64 { case probe = 0, show = 1, off = 2, status = 3, modes = 4 case importSurface = 5, verify = 6, release = 7, output = 8, present = 9, result = 10 } let displayPatterns: [String: UInt64] = ["bars": 0, "white": 1, "gradient": 2] private func le32(_ bytes: [UInt8], _ at: Int) -> UInt32 { UInt32(bytes[at]) | UInt32(bytes[at + 1]) << 8 | UInt32(bytes[at + 2]) << 16 | UInt32(bytes[at + 3]) << 24 } struct DisplayConnector { let name: String let id, status, modes, edidBytes: UInt32 let preferredWidth, preferredHeight, preferredRefresh: UInt32 let lit: Bool let litWidth, litHeight, litRefresh, crtc: UInt32 var connected: Bool { status == 1 } } struct DisplayReport { let showing: Bool let pattern, fbWidth, fbHeight, fbPitch, crtcs: UInt32 let fbGPUAddress, fillNs, commitNs: UInt64 let probeStatus, commitStatus, restoreStatus: Int32 let hotplugEpoch: UInt32 let connectors: [DisplayConnector] init?(_ data: Data) { guard data.count >= kDisplayReportBytes else { return nil } let bytes = [UInt8](data) func u32(_ at: Int) -> UInt32 { le32(bytes, at) } func u64(_ at: Int) -> UInt64 { UInt64(u32(at)) | UInt64(u32(at + 4)) << 32 } guard u32(0) == 1, u32(4) <= 8 else { return nil } showing = u32(8) != 0 pattern = u32(12); fbWidth = u32(16); fbHeight = u32(20); fbPitch = u32(24); crtcs = u32(28) fbGPUAddress = u64(32); fillNs = u64(40); commitNs = u64(48) probeStatus = Int32(bitPattern: u32(56)); commitStatus = Int32(bitPattern: u32(60)) restoreStatus = Int32(bitPattern: u32(64)) hotplugEpoch = u32(68) var list: [DisplayConnector] = [] for index in 0..= kDisplayModesBytes else { return nil } let bytes = [UInt8](data) let count = Int(le32(bytes, 8)) guard le32(bytes, 0) == 1, count <= 56, count <= Int(le32(bytes, 12)) else { return nil } status = le32(bytes, 4) total = Int(le32(bytes, 12)) widthMm = Int(le32(bytes, 16)); heightMm = Int(le32(bytes, 20)) modes = (0.. String { if status == 0 { return "ok" } let code = Int32(truncatingIfNeeded: -status) let meaning: String switch code { case ENODEV: meaning = ": no display (the driver runs without Display Core; install with activate.sh --display)" case ENOENT: meaning = ": no connected output (or no connector by that name)" case E2BIG: meaning = ": the outputs' modes need a framebuffer larger than 8192 pixels" default: meaning = "" } return "Linux errno \(code) (\(String(cString: strerror(code)))\(meaning))" } /// The identity, size, colour primaries and preferred timing of an EDID /// base block (EDID 1.3/1.4). struct EDIDSummary { let manufacturerID: UInt16 // the PNP ID word, as macOS reports a display's vendor let vendor: String let product: UInt16 let serial: UInt32 let name: String? let serialText: String? let year: Int let widthCm, heightCm: Int /// CIE xy of red, green, blue and white (10-bit fractions). let red, green, blue, white: (x: Double, y: Double) let preferred: (width: Int, height: Int, refresh: Double, clockHz: Int, widthMm: Int, heightMm: Int)? init?(_ data: Data) { let b = [UInt8](data) guard b.count >= 128, b[0..<8] == [0, 255, 255, 255, 255, 255, 255, 0][...], b[0..<128].reduce(UInt8(0), &+) == 0 else { return nil } let word = Int(b[8]) << 8 | Int(b[9]) manufacturerID = UInt16(word) vendor = String([10, 5, 0].map { Character(UnicodeScalar(UInt8(((word >> $0) & 31) + 64))) }) product = UInt16(b[10]) | UInt16(b[11]) << 8 serial = UInt32(b[12]) | UInt32(b[13]) << 8 | UInt32(b[14]) << 16 | UInt32(b[15]) << 24 year = Int(b[17]) + 1990 widthCm = Int(b[21]); heightCm = Int(b[22]) // Bytes 25-26 carry the two low bits of each coordinate, 27-34 the high eight. func coordinate(_ high: Int, _ lowByte: Int, _ shift: Int) -> Double { Double(Int(b[high]) << 2 | (Int(b[lowByte]) >> shift) & 3) / 1024 } red = (coordinate(27, 25, 6), coordinate(28, 25, 4)) green = (coordinate(29, 25, 2), coordinate(30, 25, 0)) blue = (coordinate(31, 26, 6), coordinate(32, 26, 4)) white = (coordinate(33, 26, 2), coordinate(34, 26, 0)) var name: String?, serialText: String? var preferred: (Int, Int, Double, Int, Int, Int)? for at in stride(from: 54, to: 126, by: 18) { let d = Array(b[at.. 0 ? Double(clock) / Double(total) : 0, clock, Int(d[12]) | Int(d[14] & 0xf0) << 4, Int(d[13]) | Int(d[14] & 0x0f) << 8) } continue } let text = String(decoding: d[5..<18].prefix { $0 != 0x0a }, as: UTF8.self) .trimmingCharacters(in: .whitespaces) if d[3] == 0xfc { name = text } else if d[3] == 0xff { serialText = text } } self.name = name self.serialText = serialText self.preferred = preferred.map { (width: $0.0, height: $0.1, refresh: $0.2, clockHz: $0.3, widthMm: $0.4, heightMm: $0.5) } } var summary: String { var parts = [String(format: "%@ product 0x%04x", vendor, product), name.map { "name '\($0)'" } ?? "no name", "serial \(serialText ?? String(serial))", "made \(year)", "\(widthCm)x\(heightCm) cm"] if let p = preferred { parts.append(String(format: "preferred %dx%d@%.2f (%.2f MHz, %dx%d mm)", p.width, p.height, p.refresh, Double(p.clockHz) / 1e6, p.widthMm, p.heightMm)) } return parts.joined(separator: ", ") } } // ---------------------------------------------------------------- // MARK: - The virtual display a connected monitor becomes // ---------------------------------------------------------------- /// What a CGVirtualDisplayDescriptor and its CGVirtualDisplaySettings would /// carry for one monitor (property names as macOS 26 has them). struct VirtualDisplayPlan: Equatable { struct Mode: Equatable { let width, height: Int let refreshRate: Double } let connector: String let name: String let vendorID: UInt32 let productID: UInt32 let serialNum: UInt32 let sizeInMillimeters: (width: Double, height: Double) let maxPixelsWide, maxPixelsHigh: Int let redPrimary, greenPrimary, bluePrimary, whitePoint: (x: Double, y: Double) let modes: [Mode] // preferred first let hiDPI: Int // 0: 1x, the cheapest for WindowServer static func == (a: VirtualDisplayPlan, b: VirtualDisplayPlan) -> Bool { a.connector == b.connector && a.name == b.name && a.vendorID == b.vendorID && a.productID == b.productID && a.serialNum == b.serialNum && a.sizeInMillimeters == b.sizeInMillimeters && a.maxPixelsWide == b.maxPixelsWide && a.maxPixelsHigh == b.maxPixelsHigh && a.redPrimary == b.redPrimary && a.greenPrimary == b.greenPrimary && a.bluePrimary == b.bluePrimary && a.whitePoint == b.whitePoint && a.modes == b.modes && a.hiDPI == b.hiDPI } var lines: [String] { var out = [ " CGVirtualDisplayDescriptor for \(connector):", " name \"\(name)\"", String(format: " vendorID 0x%04x productID 0x%04x serialNum %u", vendorID, productID, serialNum), String(format: " sizeInMillimeters %.0f x %.0f maxPixels %d x %d", sizeInMillimeters.width, sizeInMillimeters.height, maxPixelsWide, maxPixelsHigh), String(format: " primaries R(%.4f, %.4f) G(%.4f, %.4f) B(%.4f, %.4f) white(%.4f, %.4f)", redPrimary.x, redPrimary.y, greenPrimary.x, greenPrimary.y, bluePrimary.x, bluePrimary.y, whitePoint.x, whitePoint.y), " CGVirtualDisplaySettings: hiDPI \(hiDPI), \(modes.count) mode(s):", ] out += modes.map { String(format: " %dx%d @ %.3f Hz", $0.width, $0.height, $0.refreshRate) } return out } } enum PlanError: Error, Equatable, CustomStringConvertible { case notConnected case noEDID case noProgressiveMode var description: String { switch self { case .notConnected: return "not connected" case .noEDID: return "no valid EDID (a monitor without one cannot be described to macOS)" case .noProgressiveMode: return "no progressive mode" } } } /// The plan for one connected monitor. The EDID gives the identity and /// colour; the driver's mode list (what upstream accepted for this link) /// gives the modes; nothing is invented. func planVirtualDisplay(connector: String, modes: DisplayModes, edid: Data?) -> Result { guard modes.status == 1 else { return .failure(.notConnected) } guard let edid, let info = EDIDSummary(edid) else { return .failure(.noEDID) } var seen = Set() var list: [VirtualDisplayPlan.Mode] = [] // Preferred first, then the driver's order (upstream sorts by size, then refresh). for mode in modes.modes.filter({ $0.preferred }) + modes.modes.filter({ !$0.preferred }) where !mode.interlaced && mode.width > 0 && mode.height > 0 && mode.refreshMilliHz > 0 { let key = "\(mode.width)x\(mode.height)@\(mode.refreshMilliHz / 10)" if seen.insert(key).inserted { list.append(.init(width: mode.width, height: mode.height, refreshRate: mode.refresh)) } } guard !list.isEmpty else { return .failure(.noProgressiveMode) } let name = info.name.flatMap { $0.isEmpty ? nil : $0 } ?? String(format: "%@ %04X", info.vendor, info.product) // A numeric serial when the EDID has one; else a stable hash of its // serial string; else 0. var serial = info.serial if serial == 0, let text = info.serialText, !text.isEmpty { serial = text.utf8.reduce(UInt32(2166136261)) { ($0 ^ UInt32($1)) &* 16777619 } } let size: (Double, Double) = modes.widthMm > 0 && modes.heightMm > 0 ? (Double(modes.widthMm), Double(modes.heightMm)) : (Double(info.widthCm * 10), Double(info.heightCm * 10)) return .success(VirtualDisplayPlan( connector: connector, name: name, vendorID: UInt32(info.manufacturerID), productID: UInt32(info.product), serialNum: serial, sizeInMillimeters: size, maxPixelsWide: list.map(\.width).max() ?? 0, maxPixelsHigh: list.map(\.height).max() ?? 0, redPrimary: info.red, greenPrimary: info.green, bluePrimary: info.blue, whitePoint: info.white, modes: list, hiDPI: 0)) } /// The agent's view of the displays it maintains: the plans it acted on, /// by connector, and what a new probe changes. struct DisplayAgentState { enum Change: Equatable, CustomStringConvertible { case add(VirtualDisplayPlan) case update(VirtualDisplayPlan) case remove(String) case unchanged(String) var description: String { switch self { case .add(let p): return "add \(p.connector) (\"\(p.name)\")" case .update(let p): return "update \(p.connector) (\"\(p.name)\")" case .remove(let c): return "remove \(c)" case .unchanged(let c): return "unchanged \(c)" } } } private(set) var displays: [String: VirtualDisplayPlan] = [:] private(set) var epoch: UInt32? /// Whether the driver's hotplug epoch says the outputs need a new probe. mutating func needsProbe(epoch now: UInt32) -> Bool { defer { epoch = now } return epoch != now } /// Apply the plans of the currently connected monitors (connectors that /// failed to plan are absent): the changes, in connector order. mutating func apply(_ plans: [VirtualDisplayPlan]) -> [Change] { var changes: [Change] = [] let incoming = Dictionary(plans.map { ($0.connector, $0) }, uniquingKeysWith: { a, _ in a }) for connector in Set(displays.keys).union(incoming.keys).sorted() { switch (displays[connector], incoming[connector]) { case (nil, let plan?): changes.append(.add(plan)) case (_?, nil): changes.append(.remove(connector)) case (let old?, let plan?): changes.append(old == plan ? .unchanged(connector) : .update(plan)) default: break } } displays = incoming return changes } } // ---------------------------------------------------------------- // MARK: - Frames: the pinning check and PRESENT replies // ---------------------------------------------------------------- /// rt_surface_pattern (linuxu/headers/rt/surface.h): the value of dword /// @index of a surface filled for @seed. func surfacePattern(seed: UInt32, dword index: UInt64) -> UInt32 { UInt32(truncatingIfNeeded: index &* 2654435761) ^ (seed &* 0x85ebca77) ^ 0x5a5a0000 } /// struct rt_surface_verify_result, version 1. struct SurfaceVerifyResult { static let bytes = 64 let samples, sampleBytes, gpuMismatches, cpuMismatches: UInt32 let cpuChecked: Bool let firstGPUMismatch, firstCPUMismatch, gpuNs, gpuAddress: UInt64 let gpuValue, expectedValue: UInt32 var dwords: UInt32 { samples * sampleBytes / 4 } init?(_ data: Data) { guard data.count >= SurfaceVerifyResult.bytes else { return nil } let b = [UInt8](data) func u64(_ at: Int) -> UInt64 { UInt64(le32(b, at)) | UInt64(le32(b, at + 4)) << 32 } guard le32(b, 0) == 1 else { return nil } samples = le32(b, 4); sampleBytes = le32(b, 8) gpuMismatches = le32(b, 12); cpuMismatches = le32(b, 16); cpuChecked = le32(b, 20) != 0 firstGPUMismatch = u64(24); firstCPUMismatch = u64(32); gpuNs = u64(40); gpuAddress = u64(48) gpuValue = le32(b, 56); expectedValue = le32(b, 60) } } /// struct rt_display_present_stats, version 1. /// struct rt_display_present_stats, version 3 (linuxu/headers/rt/display.h; /// version 2, 120 bytes, without the VRAM counters, from a driver before 240): /// the output worker's counters since OUTPUT. PRESENT returns them as they /// stand when it queues a frame (the frame itself is copied and flipped /// later); PRESENT with no rectangle only reads them. struct PresentStats: Equatable { static let bytes = 144 let engines: UInt32 let received, flipped, replaced, copyJobs, bytesCopied: UInt64 let copySubmitNs, copyGPUNs, latencyNs, latencyMaxNs: UInt64 let lastBytes, lastCopyGPUNs, lastLatencyNs: UInt64 let error: Int32 let fullFrames: UInt32 /// CPU accesses to the VRAM aperture (all users): what a power-off /// could catch in flight (the driver gates them once it knows). let apertureOps: UInt64 /// Version 3: bytes copied from the framebuffer drawn before (in VRAM; /// bytesCopied came over PCIe), rows moved there, moves copied from the /// surface instead (the frame before was replaced in the mailbox). let vramBytes, movedRows, movesDropped: UInt64 init?(_ data: Data) { guard data.count >= 120 else { return nil } let b = [UInt8](data) func u64(_ at: Int) -> UInt64 { UInt64(le32(b, at)) | UInt64(le32(b, at + 4)) << 32 } let version = le32(b, 0) guard version == 2 || (version == 3 && data.count >= PresentStats.bytes) else { return nil } engines = le32(b, 4) received = u64(8); flipped = u64(16); replaced = u64(24); copyJobs = u64(32); bytesCopied = u64(40) copySubmitNs = u64(48); copyGPUNs = u64(56); latencyNs = u64(64); latencyMaxNs = u64(72) lastBytes = u64(80); lastCopyGPUNs = u64(88); lastLatencyNs = u64(96) error = Int32(bitPattern: le32(b, 104)); fullFrames = le32(b, 108) apertureOps = u64(112) if version == 3 { vramBytes = u64(120); movedRows = u64(128); movesDropped = u64(136) } else { vramBytes = 0; movedRows = 0; movesDropped = 0 } } } /// What one mirroring run measured: the agent's side per presented frame /// (the PRESENT call's CPU and wall time, the whole frame handler's CPU) /// and the driver's per flipped frame (copy time against the bytes copied), /// summarized against the driver's counters at the start and the end of the /// measured window. struct PresentMeasurement { /// Copy time by damage size: under 64 KiB, under 1 MiB, under 4 MiB, more. static let bucketLimits: [UInt64] = [64 << 10, 1 << 20, 4 << 20, .max] static let bucketNames = ["<64K", "64K-1M", "1M-4M", ">=4M"] var frames = 0, idleFrames = 0, presented = 0 /// Frames PRESENT answered busy for (their damage went with the next). var busyFrames = 0 var callCPUNs: UInt64 = 0, callWallNs: UInt64 = 0, callWallMaxNs: UInt64 = 0, handlerCPUNs: UInt64 = 0 var bucketFrames = [Int](repeating: 0, count: 4) var bucketBytes = [UInt64](repeating: 0, count: 4) var bucketCopyNs = [UInt64](repeating: 0, count: 4) var lastFlipped: UInt64 = 0 /// Damage ScreenCaptureKit reported and what was left once unchanged /// tiles were dropped (bytes), frames left with none, hashing time. var reportedBytes: UInt64 = 0, keptBytes: UInt64 = 0, unchangedFrames = 0, filterNs: UInt64 = 0, filterFrames = 0 /// Bytes the moves cover (copied in VRAM rather than over PCIe), frames with a move. var movedBytes: UInt64 = 0, movedFrames = 0 mutating func filtered(reported: [DamageFilter.Rect], kept: DamageFilter.Damage, ns: UInt64) { func bytes(_ r: [DamageFilter.Rect]) -> UInt64 { r.reduce(0) { $0 + UInt64($1.w) * UInt64($1.h) * 4 } } reportedBytes += bytes(reported) keptBytes += bytes(kept.rects) movedBytes += kept.moves.reduce(0) { $0 + UInt64($1.w) * UInt64($1.h) * 4 } movedFrames += kept.moves.isEmpty ? 0 : 1 unchangedFrames += kept.isEmpty ? 1 : 0 filterNs += ns filterFrames += 1 } /// From a frame's composition (its display time) to the frame handler. var lagNs: UInt64 = 0, lagMaxNs: UInt64 = 0, lagFrames = 0 mutating func delivered(lagNs: UInt64) { self.lagNs += lagNs lagMaxNs = max(lagMaxNs, lagNs) lagFrames += 1 } /// Waiting for the compositor to finish writing the captured buffer. var lockWaitNs: UInt64 = 0, lockWaitMaxNs: UInt64 = 0 mutating func present(callCPUNs: UInt64, callWallNs: UInt64, handlerCPUNs: UInt64, lockWaitNs: UInt64 = 0) { presented += 1 self.lockWaitNs += lockWaitNs lockWaitMaxNs = max(lockWaitMaxNs, lockWaitNs) self.callCPUNs += callCPUNs self.callWallNs += callWallNs callWallMaxNs = max(callWallMaxNs, callWallNs) self.handlerCPUNs += handlerCPUNs } /// The driver's last flipped frame, once per flip seen. mutating func observe(_ stats: PresentStats) { guard stats.flipped != lastFlipped else { return } lastFlipped = stats.flipped guard stats.lastBytes > 0 else { return } let i = PresentMeasurement.bucketLimits.firstIndex { stats.lastBytes < $0 } ?? 3 bucketFrames[i] += 1 bucketBytes[i] += stats.lastBytes bucketCopyNs[i] += stats.lastCopyGPUNs } /// The report: @start and @end are the driver's counters around the /// window of @seconds; @refreshHz the mode's rate. func lines(start: PresentStats, end: PresentStats, seconds: Double, refreshHz: Double) -> [String] { let flipped = end.flipped - start.flipped, received = end.received - start.received let replaced = end.replaced - start.replaced, bytes = end.bytesCopied - start.bytesCopied let f = Double(max(flipped, 1)), p = Double(max(presented, 1)) var out: [String] = [] out.append(String(format: "frames: %d captured (%d without damage, %d while the driver was busy), %d presented, %llu received by the driver, %llu flipped, %llu replaced before a flip; %.1f flips/s at %.3f Hz", frames, idleFrames, busyFrames, presented, received, flipped, replaced, Double(flipped) / max(seconds, 0.001), refreshHz)) out.append(String(format: "agent per presented frame: PRESENT %.1f us CPU, %.1f us wall (max %.1f); whole frame handler %.1f us CPU", Double(callCPUNs) / p / 1e3, Double(callWallNs) / p / 1e3, Double(callWallMaxNs) / 1e3, Double(handlerCPUNs) / p / 1e3)) out.append(String(format: "composition to the frame handler: %.2f ms on average, %.2f ms at most (%d frames)", Double(lagNs) / Double(max(lagFrames, 1)) / 1e6, Double(lagMaxNs) / 1e6, lagFrames)) out.append(String(format: "waiting for the compositor to finish the captured frame: %.1f us on average, %.1f us at most", Double(lockWaitNs) / p / 1e3, Double(lockWaitMaxNs) / 1e3)) let ff = Double(max(filterFrames, 1)) out.append(String(format: "unchanged damage: %d of %d damaged frame(s) changed nothing; %.1f KB reported, %.1f KB kept per damaged frame (%.0f%% dropped); hashing %.1f us per frame", unchangedFrames, filterFrames, Double(reportedBytes) / ff / 1e3, Double(keptBytes) / ff / 1e3, reportedBytes > 0 ? 100 * (1 - Double(keptBytes) / Double(reportedBytes)) : 0, Double(filterNs) / ff / 1e3)) out.append(String(format: "scrolling: %d frame(s) with moves, %.1f KB moved per damaged frame; driver: %llu rows moved in VRAM, %llu move(s) copied from the surface instead; %.1f KB per flip copied in VRAM", movedFrames, Double(movedBytes) / ff / 1e3, end.movedRows &- start.movedRows, end.movesDropped &- start.movesDropped, Double(end.vramBytes &- start.vramBytes) / f / 1e3)) out.append(String(format: "driver per flipped frame: %.1f KB copied from the surface (PCIe) in %.2f copy jobs, worker submit %.1f us CPU, GPU copy %.3f ms", Double(bytes) / f / 1e3, Double(end.copyJobs - start.copyJobs) / f, Double(end.copySubmitNs - start.copySubmitNs) / f / 1e3, Double(end.copyGPUNs - start.copyGPUNs) / f / 1e6)) out.append(String(format: "CPU accesses to the VRAM aperture: %.1f per flipped frame", Double(end.apertureOps &- start.apertureOps) / f)) out.append(String(format: "capture to scanout: %.2f ms on average, %.2f ms at most (since OUTPUT); %.2f frame(s) at %.3f Hz", Double(end.latencyNs - start.latencyNs) / f / 1e6, Double(end.latencyMaxNs) / 1e6, Double(end.latencyNs - start.latencyNs) / f / 1e9 * refreshHz, refreshHz)) for i in 0..<4 where bucketFrames[i] > 0 { let mb = Double(bucketBytes[i]) / 1048576 out.append(String(format: "copy %@: %d frame(s), %.1f KB each, %.3f ms each, %.2f ms per MiB", PresentMeasurement.bucketNames[i], bucketFrames[i], Double(bucketBytes[i]) / Double(bucketFrames[i]) / 1e3, Double(bucketCopyNs[i]) / Double(bucketFrames[i]) / 1e6, mb > 0 ? Double(bucketCopyNs[i]) / 1e6 / mb : 0)) } return out } } /// Presented frames whose capture buffers must stay unreused until the /// driver is done reading them. PRESENT only queues a frame (a mailbox of /// one); the driver's worker later takes it and copies it (SDMA reads the /// buffer) or a newer frame replaces it first (never read). A taken frame /// is done at its flip: the flip waits for its copy, and frames flip in /// the order they were taken. Which happened to a frame is known at the /// next PRESENT: the replaced count went up when it was still in the /// mailbox. The driver's counts alone do not say which frames are done: /// a replacement counts the newest frame while an older one taken before /// it may still be copying. struct PresentedFrames { /// Taken frames: the flipped count at which each is done, oldest first. private(set) var taken: [(item: Item, flip: UInt64)] = [] /// The newest frame: in the mailbox or taken, not known until the next PRESENT. private(set) var newest: Item? private var replaced: UInt64 = 0 var count: Int { taken.count + (newest == nil ? 0 : 1) } /// @item was just queued; @received, @replaced and @flipped are the /// driver's counts PRESENT returned for it. Returns the items now free. mutating func presented(_ item: Item, received: UInt64, replaced nowReplaced: UInt64, flipped: UInt64) -> [Item] { var free: [Item] = [] if let previous = newest { if nowReplaced > replaced { free.append(previous) // still in the mailbox: never read } else { // Taken: every frame before this one was taken or replaced, // so it was taken frame number (received - 1 - replaced). taken.append((previous, received - 1 - nowReplaced)) } } newest = item replaced = nowReplaced free += retire(flipped: flipped) return free } /// Frames flipped by @flipped are done. mutating func retire(flipped: UInt64) -> [Item] { var free: [Item] = [] while let first = taken.first, first.flip <= flipped { free.append(first.item) taken.removeFirst() } return free } mutating func removeAll() { taken.removeAll() newest = nil replaced = 0 } } /// Damage that changes nothing on screen, dropped before PRESENT, and rows /// that scrolled, sent as moves. Some windows are redrawn every frame with /// the same pixels (menu bar status items, a cursor drawn by the hardware /// rather than into the capture) and ScreenCaptureKit reports them as /// damage; copied and flipped, an idle display would cost a frame's work /// every refresh. Each row of the frame is cut into tiles of 64 pixels /// with a 64-bit hash of each, of what the driver was last given. A dirty /// rectangle's tiles are hashed again: tiles that did not change are /// dropped; rows whose tiles equal another row's from before (a scroll, /// found by the shift most rows agree on) become moves, which the driver /// copies in VRAM; the rest are kept in whole tiles (a tile is never /// recorded as given while part of it was not), consecutive changed rows /// merged into one rectangle. Everything is compared with the hashes from /// before the frame, so rectangles that overlap agree. struct DamageFilter { typealias Rect = (x: UInt32, y: UInt32, w: UInt32, h: UInt32) /// @w x @h pixels at (@x, @y) are the previous frame's at (@x, @srcY). typealias Move = (x: UInt32, y: UInt32, w: UInt32, h: UInt32, srcY: UInt32) struct Damage { var rects: [Rect] = [] var moves: [Move] = [] var isEmpty: Bool { rects.isEmpty && moves.isEmpty } } static let tile = 64 /// PRESENT's limits: moves, and the request (16 bytes, 16 per rectangle, 24 per move). static let movesMax = 32, requestMax = 4096 /// Shorter runs of scrolled rows are damage: a move per row or two is not worth it. static let moveRowsMin = 4 let width: Int, height: Int, columns: Int /// Off: no moves, only unchanged tiles dropped. var detectScroll = true /// Per row, per tile: the hash of what the driver was given; 0 when /// not known (hashes are odd). private var hashes: [UInt64] /// Scratch. private var fresh: [UInt64] = [], newRow: [UInt64] = [], oldRow: [UInt64] = [] init(width: Int, height: Int) { self.width = width self.height = height columns = (width + DamageFilter.tile - 1) / DamageFilter.tile hashes = [UInt64](repeating: 0, count: columns * height) } /// Nothing known: the next damage is kept whole. mutating func reset() { for i in hashes.indices { hashes[i] = 0 } } /// The damage of @rects that changed anything, given the frame at /// @base (BGRA, @pitch bytes per row, readable while this runs). When /// it does not fit PRESENT, the whole frame. mutating func filter(_ rects: [Rect], base: UnsafeRawPointer, pitch: Int) -> Damage { var out = Damage() var updates: [(at: Int, rows: Int, c0: Int, n: Int, hashes: [UInt64])] = [] let t = DamageFilter.tile for r in rects { let x0 = Int(r.x), y0 = Int(r.y) let x1 = min(x0 + Int(r.w), width), y1 = min(y0 + Int(r.h), height) guard x0 < x1, y0 < y1 else { continue } let c0 = x0 / t, c1 = (x1 - 1) / t, n = c1 - c0 + 1, rows = y1 - y0 fresh.removeAll(keepingCapacity: true) for y in y0..= 0 else { return } let px = runMin * t out.rects.append((UInt32(px), UInt32(runStart), UInt32(min((runMax + 1) * t, width) - px), UInt32(end - runStart))) runStart = -1 } func closeMove(_ end: Int) { guard moveStart >= 0 else { return } let count = end - moveStart if count >= DamageFilter.moveRowsMin && out.moves.count < DamageFilter.movesMax { out.moves.append((UInt32(px0), UInt32(moveStart), UInt32(pxw), UInt32(count), UInt32(moveStart + shift))) } else { // Too short to move: damage, its changed tiles. for y in moveStart..= 0 { runMin = min(runMin, lo); runMax = max(runMax, hi) } } for y in y0..= 0 && src < rows && oldRow[src] != 0 && oldRow[src] == newRow[i] { close(y) if moveStart < 0 { moveStart = y } continue } closeMove(y) tileRow(y, y0: y0, c0: c0, n: n) } closeMove(y1) close(y1) updates.append((y0 * columns + c0, rows, c0, n, fresh)) } for u in updates { for i in 0..() out.rects = out.rects.filter { seen.insert([$0.x, $0.y, $0.w, $0.h]).inserted } seen.removeAll() out.moves = out.moves.filter { seen.insert([$0.x, $0.y, $0.w, $0.h, $0.srcY]).inserted } if 16 + out.rects.count * 16 + out.moves.count * 24 > DamageFilter.requestMax || out.rects.count > 255 { return Damage(rects: [(0, 0, UInt32(width), UInt32(height))], moves: []) } return out } /// The vertical shift most changed rows of the rectangle agree on (a /// row's new signature found at row + shift before), counted only /// over rows whose old signature is unique (blank rows say nothing); /// 0 when fewer than moveRowsMin agree. private func scrollShift(_ rows: Int) -> Int { guard rows >= 2 * DamageFilter.moveRowsMin else { return 0 } var at: [UInt64: Int] = [:], repeated = Set() at.reserveCapacity(rows) for i in 0.. abs($1.key)) }), best.value >= DamageFilter.moveRowsMin else { return 0 } return best.key } /// One signature for @count tile hashes from @from; 0 if one is not known. private static func fold(_ h: [UInt64], from: Int, count: Int) -> UInt64 { var s: UInt64 = 0x2d358dccaa6c78a5 for k in 0.. UInt64 { let r = a.multipliedFullWidth(by: b) return r.high ^ r.low } /// A 64-bit hash of @bytes (a multiple of 4) at @p, odd (0 is "not /// known"): wyhash's multiply-fold over two lanes of 16 bytes. static func hash(_ p: UnsafeRawPointer, bytes: Int) -> UInt64 { let k0: UInt64 = 0xa0761d6478bd642f, k1: UInt64 = 0xe7037ed1a0b428db let k2: UInt64 = 0x8ebc6af09c88c6e3, k3: UInt64 = 0x589965cc75374cc3 var a = k0 ^ UInt64(bytes), b = k1 var i = 0 while i + 32 <= bytes { a = mum(p.loadUnaligned(fromByteOffset: i, as: UInt64.self) ^ k1, p.loadUnaligned(fromByteOffset: i + 8, as: UInt64.self) ^ a) b = mum(p.loadUnaligned(fromByteOffset: i + 16, as: UInt64.self) ^ k2, p.loadUnaligned(fromByteOffset: i + 24, as: UInt64.self) ^ b) i += 32 } while i + 8 <= bytes { a = mum(p.loadUnaligned(fromByteOffset: i, as: UInt64.self) ^ k3, a ^ k1) i += 8 } if i < bytes { a = mum(UInt64(p.loadUnaligned(fromByteOffset: i, as: UInt32.self)) ^ k2, a ^ k3) } return mum(a ^ k3, b ^ k0 ^ UInt64(bytes)) | 1 } } /// A frame's damage as PRESENT takes it: whole pixels inside the surface, /// at most 255 rectangles (more become the whole frame). func presentRects(_ dirty: [CGRect], width: Int, height: Int) -> [(x: UInt32, y: UInt32, w: UInt32, h: UInt32)] { let bounds = CGRect(x: 0, y: 0, width: width, height: height) var out: [(x: UInt32, y: UInt32, w: UInt32, h: UInt32)] = [] for rect in dirty { let r = rect.standardized.intersection(bounds) if r.isNull || r.isEmpty { continue } let x0 = Int(r.minX.rounded(.down)), y0 = Int(r.minY.rounded(.down)) let x1 = Int(r.maxX.rounded(.up)), y1 = Int(r.maxY.rounded(.up)) out.append((UInt32(x0), UInt32(y0), UInt32(x1 - x0), UInt32(y1 - y0))) } if out.count > 255 { return [(0, 0, UInt32(width), UInt32(height))] } return out } // ---------------------------------------------------------------- // MARK: - the display control model (daemon <-> menu bar) // ---------------------------------------------------------------- /// A monitor's identity across connectors, replugs and GPUs: its EDID /// manufacturer, product code and serial (the serial string descriptor /// when the binary serial is 0). nil without a readable EDID. func monitorKey(edid: Data?) -> String? { guard let edid, let summary = EDIDSummary(edid) else { return nil } let serial = summary.serial != 0 ? String(summary.serial) : (summary.serialText ?? "0") return String(format: "%@-%04X-%@", summary.vendor, summary.product, serial) } /// The user's per-monitor choices (the menu bar's toggles): a monitor is /// mirrored unless turned off. Persisted as JSON, keyed by monitorKey. struct DisplayPrefs: Codable, Equatable { var off: [String] = [] /// "Disconnect GPU": the daemon stops mirroring and lets go of the /// driver so the GPU can be unplugged like an ejected disk. Cleared by /// "Reconnect GPU", or by the daemon once the GPU has left the bus. var disconnected = false /// The performance controls (PerformanceLevel; a power profile by the /// name the card lists it under, e.g. "COMPUTE"). nil: never chosen, /// the driver's own default (Auto, as on Linux). Reapplied whenever the /// GPU comes up (PerformancePlan). var performanceLevel: PerformanceLevel? var powerProfile: String? init(off: [String] = [], disconnected: Bool = false, performanceLevel: PerformanceLevel? = nil, powerProfile: String? = nil) { self.off = off self.disconnected = disconnected self.performanceLevel = performanceLevel self.powerProfile = powerProfile } /// Files from before "disconnected" or the performance choices existed /// read as connected, with the driver's defaults. init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) off = try c.decodeIfPresent([String].self, forKey: .off) ?? [] disconnected = try c.decodeIfPresent(Bool.self, forKey: .disconnected) ?? false performanceLevel = try? c.decodeIfPresent(PerformanceLevel.self, forKey: .performanceLevel) powerProfile = try c.decodeIfPresent(String.self, forKey: .powerProfile) } func isOn(_ key: String) -> Bool { !off.contains(key) } mutating func set(_ key: String, on: Bool) { off.removeAll { $0 == key } if !on { off.append(key); off.sort() } } static func load(from url: URL) -> DisplayPrefs { guard let data = try? Data(contentsOf: url) else { return DisplayPrefs() } return (try? JSONDecoder().decode(DisplayPrefs.self, from: data)) ?? DisplayPrefs() } func save(to url: URL) throws { try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(self).write(to: url, options: .atomic) } } /// "Disconnect GPU": whether the GPU can be unplugged now. Safe once the /// display daemon has let go (or is not running) and no app holds a client /// of the driver (IOKit's IOUserClientCreator records, "pid N, name"; the /// asking process itself excluded); else the apps to quit. enum DisconnectReadiness: Equatable { case safe /// Safe to unplug: the driver's session is closed. These programs still /// have the driver open; any use of the GPU tells them it was /// disconnected (the next program to start brings the GPU up again). case safeWithClients([String]) case waitingForDisplays /// The GPU is up for these programs: Disconnect GPU closes it for them. case appsConnected([String]) /// The driver is closing its session (stopping the GPU's work, /// releasing its memory). case driverClosing /// Whether nothing touches the GPU any more: it can be unplugged. var canUnplug: Bool { if case .safeWithClients = self { return true } return self == .safe } /// @sessionOpen: the driver's session is up (PCI open: the GPU is in /// use, by programs or kept up between them); @sessionBusy: it closes. static func evaluate(status: DisplayStatus, clients: [String], selfPID: Int32, sessionBusy: Bool = false, sessionOpen: Bool = false) -> DisconnectReadiness { if status.daemon != 0 && status.driverAttached && !status.disconnected { return .waitingForDisplays } let apps = clients.compactMap { creator -> String? in let parts = creator.split(separator: ",", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) } guard parts.count == 2, parts[0].hasPrefix("pid ") else { return creator } if Int32(parts[0].dropFirst(4)) == selfPID { return nil } return "\(parts[1]) (\(parts[0]))" } if sessionBusy { return .driverClosing } if sessionOpen { return .appsConnected(apps) } return apps.isEmpty ? .safe : .safeWithClients(apps) } /// For the user. var message: String { switch self { case .safe: return "The GPU can be unplugged now." case .safeWithClients(let apps): return "The GPU can be unplugged now. Still connected to the driver, and told the GPU was " + "disconnected if they use it: " + apps.joined(separator: ", ") + "." case .waitingForDisplays: return "Waiting for the displays on the GPU to stop…" case .driverClosing: return "Waiting for the driver to finish with the GPU…" case .appsConnected(let apps): return apps.isEmpty ? "The GPU is still up; disconnecting closes it." : "Using the GPU: " + apps.joined(separator: ", ") + ". Disconnecting closes the GPU for " + (apps.count == 1 ? "it" : "them") + "." } } } /// GPU recovery's state (QueryInfo "LRST", dext/sources/session_state.h). struct ResetState: Equatable { static let version: UInt64 = 1 static let flagWedged: UInt64 = 1 << 0 static let flagLastVRAMLost: UInt64 = 1 << 1 var generation: UInt64 // queue resets that succeeded, device resets and the wedge var flags: UInt64 var queueResets: UInt64 var vramLost: UInt64 var lastResult: Int64 var wedged: Bool { flags & ResetState.flagWedged != 0 } var lastVRAMLost: Bool { flags & ResetState.flagLastVRAMLost != 0 } } /// What the daemon does about a change of the recovery state. enum ResetAction: Equatable { case none /// A wedged GPU: stop mirroring and let go of it until it is /// power-cycled (it leaves the bus) or "Reconnect GPU". case wedged /// A queue reset: the output redraws by itself (display.c); mirrors /// that ended around it start again now rather than after the retry /// delay. case restartEnded /// A reset that lost VRAM: every mirror imports and lights again. case remirror /// @previous: the state last seen from this driver instance (nil on /// the first read, which only records it). static func evaluate(previous: ResetState?, current: ResetState) -> ResetAction { if current.wedged { return .wedged } guard let previous, current.generation != previous.generation else { return .none } if current.lastVRAMLost || current.vramLost != previous.vramLost { return .remirror } return .restartEnded } } /// What the daemon reports for the menu bar. struct DisplayStatus: Codable, Equatable { enum State: String, Codable { case off, starting, mirroring, error } struct Monitor: Codable, Equatable { var key: String var connector: String var name: String var on: Bool var state: State var mode: String? // "2560x1440 @ 59.950 Hz" while mirroring var error: String? // the last error line } var daemon: Int32 = 0 // the daemon's pid, 0 when it is not running var driverAttached = false var monitors: [Monitor] = [] /// The daemon has let go of the driver for "Disconnect GPU". var disconnected = false /// The GPU stopped answering and its reset failed: it works again only /// once power-cycled. var gpuWedged = false /// The daemon could not reapply the persisted performance choices. var performanceError: String? init(daemon: Int32 = 0, driverAttached: Bool = false, monitors: [Monitor] = [], disconnected: Bool = false, gpuWedged: Bool = false, performanceError: String? = nil) { self.daemon = daemon self.driverAttached = driverAttached self.monitors = monitors self.disconnected = disconnected self.gpuWedged = gpuWedged self.performanceError = performanceError } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) daemon = try c.decodeIfPresent(Int32.self, forKey: .daemon) ?? 0 driverAttached = try c.decodeIfPresent(Bool.self, forKey: .driverAttached) ?? false monitors = try c.decodeIfPresent([Monitor].self, forKey: .monitors) ?? [] disconnected = try c.decodeIfPresent(Bool.self, forKey: .disconnected) ?? false gpuWedged = try c.decodeIfPresent(Bool.self, forKey: .gpuWedged) ?? false performanceError = try c.decodeIfPresent(String.self, forKey: .performanceError) } static let wedgedTitle = "The GPU stopped answering and its reset failed" static let wedgedAdvice = "Power-cycle the GPU (switch its enclosure off and on), then choose Reconnect GPU." /// The menu bar icon's state: an error on any monitor, else whether /// any is mirrored. var summary: State { if gpuWedged { return .error } if monitors.contains(where: { $0.state == .error }) { return .error } if monitors.contains(where: { $0.state == .mirroring }) { return .mirroring } if monitors.contains(where: { $0.state == .starting }) { return .starting } return .off } static func load(from url: URL) -> DisplayStatus? { guard let data = try? Data(contentsOf: url) else { return nil } return try? JSONDecoder().decode(DisplayStatus.self, from: data) } func save(to url: URL) throws { try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(self).write(to: url, options: .atomic) } } /// What a mirroring process's output line says about its monitor. enum AgentLine: Equatable { case mirroring(String) case failed(String) case other } func parseAgentLine(_ line: String) -> AgentLine { if let range = line.range(of: " lit at ") { return .mirroring(String(line[range.upperBound...]).trimmingCharacters(in: .whitespaces)) } if let range = line.range(of: "FAILED: ") { return .failed(String(line[range.upperBound...])) } return .other } /// A mirroring process's output as it comes: @onData with each chunk (on /// the handle's queue), then, at end of file, the read end is closed and /// @onEnd called. At end of file availableData is empty and the handler /// would otherwise fire again at once, forever, with the descriptor left /// open: a daemon up for a day spun at 170-260% CPU holding 2,556 pipes. func followOutput(of pipe: Pipe, onEnd: (() -> Void)? = nil, onData: @escaping (Data) -> Void) { pipe.fileHandleForReading.readabilityHandler = { handle in let data = handle.availableData guard !data.isEmpty else { handle.readabilityHandler = nil try? handle.close() onEnd?() return } onData(data) } } /// The connected monitors to mirror: those with an identity the user has /// not turned off. (A monitor without a readable EDID cannot be told apart /// across replugs; it is mirrored, under its connector's name.) func connectorsToMirror(connected: [(connector: String, key: String)], prefs: DisplayPrefs) -> [String] { connected.filter { prefs.isOn($0.key) }.map { $0.connector } } /// Where the daemon and the menu bar meet: the choices, the status, and the /// Darwin notifications each posts when it changed its file. enum DisplayControl { static var directory: URL { FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/MacLinuxGPU") } static var prefsURL: URL { directory.appendingPathComponent("displays.json") } static var statusURL: URL { directory.appendingPathComponent("display-status.json") } static let prefsChanged = "com.geramyloveless.maclinuxgpu.display-prefs" static let statusChanged = "com.geramyloveless.maclinuxgpu.display-status" } /// Durations of one stage of a latency (ns), summarized as percentiles. struct LatencySeries { private(set) var values: [UInt64] = [] mutating func add(_ ns: UInt64) { values.append(ns) } var count: Int { values.count } /// The value at @fraction (0...1) of the sorted series, nearest rank. func percentile(_ fraction: Double) -> UInt64 { guard !values.isEmpty else { return 0 } let sorted = values.sorted() let rank = Int((fraction * Double(sorted.count)).rounded(.up)) - 1 return sorted[min(max(rank, 0), sorted.count - 1)] } /// "p50 a ms, p90 b ms, max c ms (n)". var summary: String { String(format: "p50 %.2f ms, p90 %.2f ms, max %.2f ms (%d)", Double(percentile(0.5)) / 1e6, Double(percentile(0.9)) / 1e6, Double(values.max() ?? 0) / 1e6, values.count) } } /// The type workload's marks: four glyph-sized squares, square i white /// when bit i of the change number is set, else black (black and white /// survive the display's colour conversion, grey levels do not). The four /// captured pixels' brightness gives seq % 16 back. func typeMarkBit(_ seq: Int, _ bit: Int) -> Bool { (seq >> bit) & 1 == 1 } func typeMarkIndex(brightness: [Int]) -> Int { brightness.prefix(4).enumerated().reduce(0) { $0 | ($1.element >= 128 ? 1 << $1.offset : 0) } } // ---------------------------------------------------------------- // MARK: - performance controls // ---------------------------------------------------------------- /// The driver's SysfsWrite attributes (dext/sources/session_state.h, /// MLG_SYSFS_WRITE_*): upstream's own store() of each. enum SysfsWriteAttribute: UInt64 { case performanceLevel = 0 // power_dpm_force_performance_level case powerProfile = 1 // pp_power_profile_mode var path: String { self == .performanceLevel ? "power_dpm_force_performance_level" : "pp_power_profile_mode" } } /// power_dpm_force_performance_level as the menu offers it. Auto is the /// driver's default, as on Linux: pinning clocks costs idle power. enum PerformanceLevel: String, CaseIterable, Codable { case auto, high, peak, low /// What the sysfs file takes and shows. var sysfsValue: String { self == .peak ? "profile_peak" : rawValue } var title: String { switch self { case .auto: return "Auto" case .high: return "High" case .peak: return "Peak" case .low: return "Low" } } /// The file's contents (one level, a newline); nil for a level the menu /// does not offer (manual, the other profile_* ones). init?(sysfs text: String) { switch text.trimmingCharacters(in: .whitespacesAndNewlines) { case "auto": self = .auto case "high": self = .high case "profile_peak": self = .peak case "low": self = .low default: return nil } } /// A command-line argument: a level's name, or the sysfs spelling. init?(argument: String) { let a = argument.lowercased() if let level = PerformanceLevel(rawValue: a) { self = level } else if let level = PerformanceLevel(sysfs: a) { self = level } else { return nil } } } /// One line of pp_power_profile_mode's list: " 5 COMPUTE*:". struct PowerProfile: Equatable { let index: Int let name: String let active: Bool /// The menu's name for it; profiles the card lists that the menu does /// not know keep the card's name, readable. var title: String { switch name { case "BOOTUP_DEFAULT": return "Default" case "3D_FULL_SCREEN": return "3D Fullscreen" case "POWER_SAVING": return "Power Saving" case "COMPUTE": return "Compute" case "VR": return "VR" case "WINDOW_3D": return "3D Windowed" default: return name.replacingOccurrences(of: "_", with: " ").capitalized } } /// Every profile the file lists, in its order. The per-clock parameter /// lines under each are skipped. static func parse(_ text: String) -> [PowerProfile] { var profiles: [PowerProfile] = [] for line in text.split(separator: "\n") { let fields = line.split(whereSeparator: { $0 == " " || $0 == "\t" }) guard fields.count >= 2, let index = Int(fields[0]) else { continue } var name = String(fields[1]) if name.hasSuffix(":") { name.removeLast() } let active = name.hasSuffix("*") if active { name.removeLast() } if name.hasSuffix(":") { name.removeLast() } guard !name.isEmpty, name.allSatisfy({ $0.isUppercase || $0.isNumber || $0 == "_" }), !profiles.contains(where: { $0.index == index }) else { continue } profiles.append(PowerProfile(index: index, name: name, active: active)) } return profiles } /// The ones the menu offers: all but CUSTOM, which takes parameters. static func selectable(_ profiles: [PowerProfile]) -> [PowerProfile] { profiles.filter { $0.name != "CUSTOM" } } /// A command-line argument: a profile's card name, its menu title, or /// its index. static func find(_ argument: String, in profiles: [PowerProfile]) -> PowerProfile? { let key = argument.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "_", with: "") let candidates = selectable(profiles) if let index = Int(argument) { return candidates.first { $0.index == index } } return candidates.first { $0.name.lowercased().replacingOccurrences(of: "_", with: "") == key || $0.title.lowercased().replacingOccurrences(of: " ", with: "") == key || (key == "default" && $0.name == "BOOTUP_DEFAULT") } } } /// The live line: the clock level marked current in pp_dpm_sclk/mclk /// ("1: 3462Mhz *", "S: 41Mhz *" in deep sleep), the hwmon temperature /// (millidegrees) and power (microwatts). struct PerformanceReading: Equatable { var gfxMHz: Int? var memoryMHz: Int? var temperatureC: Double? var powerW: Double? static func currentMHz(_ dpm: String) -> Int? { for line in dpm.split(separator: "\n") where line.hasSuffix("*") { let digits = line.split(separator: ":").last?.filter { $0.isNumber } ?? "" if let mhz = Int(digits) { return mhz } } return nil } var line: String { var parts: [String] = [] parts.append("GFX " + (gfxMHz.map { "\($0) MHz" } ?? "?")) parts.append("Memory " + (memoryMHz.map { "\($0) MHz" } ?? "?")) if let temperatureC { parts.append(String(format: "%.0f °C", temperatureC)) } if let powerW { parts.append(String(format: "%.0f W", powerW)) } return parts.joined(separator: " · ") } } /// What reapplying the persisted choices writes, in order: the level, then /// the profile (by the index the card now lists the persisted name under). /// Nothing for a choice never made. A persisted profile the card no longer /// lists is an error, said, never a silent default. enum PerformancePlan { struct Write: Equatable { let attribute: SysfsWriteAttribute; let value: String } static func writes(prefs: DisplayPrefs, profiles: [PowerProfile]) -> Result<[Write], PlanError> { var writes: [Write] = [] if let level = prefs.performanceLevel { writes.append(Write(attribute: .performanceLevel, value: level.sysfsValue)) } if let name = prefs.powerProfile { guard let profile = PowerProfile.selectable(profiles).first(where: { $0.name == name }) else { return .failure(PlanError(message: "the card lists no power profile \(name)")) } writes.append(Write(attribute: .powerProfile, value: String(profile.index))) } return .success(writes) } struct PlanError: Error, Equatable { let message: String } } // ---------------------------------------------------------------- // MARK: - The driver trail (~/Library/Logs/MacLinuxGPU-driver-trail.log) // // What the driver was doing, kept on disk by the display agent so it // survives a panic: the driver's retained log ring and its cached session // state, polled once a second over an observer client (the snapshot query // scripts/read-driver-log.py uses), and a line whenever a driver instance // appears or disappears. Every write is fsynced; the file rotates to .1. // ---------------------------------------------------------------- /// The trail file: appended and fsynced line by line batches, rotated to /// `.1` once it passes `maxBytes`. struct TrailFile { let url: URL let maxBytes: Int static var defaultURL: URL { FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Logs/MacLinuxGPU-driver-trail.log") } /// Append `lines` (each gets a newline) and fsync. Errors are returned, /// never swallowed: the caller says so in its own log. func append(_ lines: [String]) -> String? { guard !lines.isEmpty else { return nil } if let size = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.size] as? Int, size >= maxBytes { let old = URL(fileURLWithPath: url.path + ".1") _ = unlink(old.path) if rename(url.path, old.path) != 0 { return "could not rotate \(url.path): \(String(cString: strerror(errno)))" } } let fd = open(url.path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0o644) guard fd >= 0 else { return "could not open \(url.path): \(String(cString: strerror(errno)))" } defer { close(fd) } let data = Array(lines.map { $0 + "\n" }.joined().utf8) var written = 0 while written < data.count { let n = data[written...].withUnsafeBytes { write(fd, $0.baseAddress, $0.count) } if n < 0 { if errno == EINTR { continue } return "could not write \(url.path): \(String(cString: strerror(errno)))" } written += n } if fsync(fd) != 0 { return "could not fsync \(url.path): \(String(cString: strerror(errno)))" } return nil } } /// One cached snapshot of the driver's state, as the trail records it. struct TrailState: Equatable { /// Bit names of the session flags (dext/sources/session_state.h, as /// scripts/read-driver-log.py names them). static let sessionFlags = ["closing", "quarantined", "stopping", "pci_open", "modules_running", "final_cleanup", "releasable", "restart_required", "raw_bar_mapped", "runtime_device", "isolation_attempted", "device_removed", "retiring", "gpu_wedged"] static let powerStates = ["active", "suspending", "suspended", "resuming", "lost"] var session: [UInt64]? // LSES words var probe: [UInt64]? // LPRO words var power: [UInt64]? // LPWR words var reset: [UInt64]? // LRST words var summary: String { var parts: [String] = [] if let s = session, s.count >= 9 { let flags = TrailState.sessionFlags.enumerated().filter { s[1] >> UInt64($0.offset) & 1 == 1 } .map { $0.element } parts.append("session [\(flags.joined(separator: ","))] cause \(s[2]) code \(Int64(bitPattern: s[3])) " + "blocker \(s[6]) generation \(s[7]) participants \(s[8])") } else { parts.append("session unavailable") } if let p = probe, p.count >= 5 { parts.append("probe attempted \(p[0]) modules \(p[1]) result \(Int64(bitPattern: p[2])) " + "fault \(p[3]) at \(String(format: "%#llx", p[4]))") } if let w = power, w.count >= 6 { let state = Int(w[1]) < TrailState.powerStates.count ? TrailState.powerStates[Int(w[1])] : "\(w[1])" parts.append("power \(state) flags \(String(format: "%#llx", w[3])) cause \(w[4]) " + "error \(Int64(bitPattern: w[5]))") } if let r = reset, r.count >= 6 { parts.append("reset generation \(r[1]) flags \(String(format: "%#llx", r[2])) " + "queue resets \(r[3]) last \(Int64(bitPattern: r[5]))") } return parts.joined(separator: "; ") } } /// The driver's retained log ring, read in bounded chunks (selector 21, /// "LLOG": end, next cursor, byte count, then up to 104 bytes), exactly as /// scripts/read-driver-log.py reads it. enum TrailLogReader { static let tag: UInt64 = 0x4c4c4f47 enum Failure: Error, Equatable { case query(Int32), invalid(String) } /// The bytes from `cursor` to the ring's end as first seen, the next /// cursor, and how many bytes the ring dropped before `cursor` could /// read them. `query` is one cached query: (status, scalars). static func read(from cursor: UInt64, maxChunks: Int = 512, query: (UInt64) -> (Int32, [UInt64])) -> Result<(Data, UInt64, UInt64), Failure> { var cursor = cursor var target: UInt64? var collected = Data() var dropped: UInt64 = 0 for _ in 0..= 3, values.count <= 16 else { return .failure(.invalid("snapshot size")) } let end = values[0], next = values[1], size = values[2] guard size <= UInt64(values.count - 3) * 8, size <= 104, size <= next else { return .failure(.invalid("byte count")) } let start = next - size guard end >= next, !(start < cursor && cursor <= end), size != 0 || next == end else { return .failure(.invalid("cursor")) } if target == nil { target = end } if start > cursor { dropped += start - cursor } var bytes = Data() for value in values[3...] { withUnsafeBytes(of: value.littleEndian) { bytes.append(contentsOf: $0) } } let keep = Int(min(size, target! > start ? target! - start : 0)) collected.append(bytes.prefix(keep)) cursor = min(next, target!) if next >= target! || size == 0 { return .success((collected, cursor, dropped)) } } // More than a tick's worth: the rest is read on the next tick. return .success((collected, cursor, dropped)) } } /// Splits the ring's bytes into whole lines; a partial last line waits for /// the rest. struct TrailLineBuffer { private var pending = Data() mutating func lines(_ data: Data) -> [String] { pending.append(data) var out: [String] = [] while let newline = pending.firstIndex(of: 0x0a) { out.append(String(decoding: pending[pending.startIndex.. 4096 { out.append(String(decoding: pending, as: UTF8.self) + " [no newline]") pending.removeAll() } return out } mutating func reset() -> String? { defer { pending.removeAll() } return pending.isEmpty ? nil : String(decoding: pending, as: UTF8.self) + " [cut off]" } } /// An upgrade's handover when the previous driver refuses Retire (this app /// lacks the session-release authorization): the previous instance can /// leave only once its session is closed, so the installer asks it with /// ShutdownGPU (selector 42) from a session client of its own, which never /// joins the session. One answer, read here. enum UpgradeHandover: Equatable { /// The session is closed: the instance leaves once IOKit stops it. case closed /// The close runs; ask again to follow it. case closing /// Other programs use the GPU. A driver from build 263 on remembers the /// request and closes the session when the last of them leaves; an /// older one must be asked again after they leave. case clientsRemain /// The session's close is uncertain: a restart (never a kill) ends it. case quarantined /// No answer to act on (the instance is leaving, or refused the call). case refused(Int32) static let busy = Int32(bitPattern: 0xe00002d5) // kIOReturnBusy static let error = Int32(bitPattern: 0xe00002bc) // kIOReturnError /// @kr: the call's IOReturn; @status, @phase: ShutdownGPU's out[0] and /// out[1] (session_state.h's reference layout: phase 2 closing, 5 /// quarantined, 6 closed). static func evaluate(kr: Int32, status: UInt64, phase: UInt64) -> UpgradeHandover { if kr == busy { return .clientsRemain } guard kr == 0 else { return .refused(kr) } let result = Int32(bitPattern: UInt32(truncatingIfNeeded: status)) if phase == 5 || result == error { return .quarantined } if phase == 6 && result == 0 { return .closed } if phase == 2 { return .closing } return .refused(result) } var summary: String { switch self { case .closed: return "its session is closed; it leaves once macOS stops it" case .closing: return "closing its session through the normal close" case .clientsRemain: return "programs still use the GPU; its session closes when the last of them quits" case .quarantined: return "its session could not close cleanly: restart the Mac, do not kill the driver" case .refused(let kr): return String(format: "did not take ShutdownGPU (kr=%#x)", UInt32(bitPattern: kr)) } } }