mirror of
https://github.com/lemonade-sdk/mac_linuxgpu.git
synced 2026-11-22 23:57:31 -10:00
Display agent: close a mirroring process's pipe at end of file
The daemon read each mirroring process's output with a readabilityHandler that ignored end of file. At end of file availableData is empty and the handler fires again at once, so the handler spun and the read descriptor stayed open after every child exit. A daemon up for 29 hours ran at 170-260% CPU holding 2,556 pipes, and the child output stopped reaching the log. followOutput (DisplayAgent.swift) closes the read end and clears the handler at end of file, after the last chunk. The termination handler no longer clears the readability handler, which could drop the last lines and leave the descriptor open. A pipe whose process failed to start is closed. A mirroring process no longer ends when its STATUS poll is answered kIOReturnBusy: the daemon's STATUS and PROBE and the child's own IMPORT share the driver's display gate, and a collision ended the mirror, which the daemon restarted 10 s later. IMPORT is asked again for up to 2 s on kIOReturnBusy. The daemon logs a mirroring process's exit status. test-display-agent runs 20 short processes through followOutput and checks every byte arrives, the end is seen once, no descriptor is left open and nothing spins afterwards.
This commit is contained in:
1 parent
3b442516b6
commit
dc0229043a
3 files changed
+76
-6
No files matched your search
@@ -1052,6 +1052,24 @@ func parseAgentLine(_ line: String) -> AgentLine {
|
||||
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.)
|
||||
|
||||
@@ -538,9 +538,16 @@ private final class MirroredDisplay: NSObject, SCStreamOutput, SCStreamDelegate
|
||||
guard width == mode.width, height == mode.height else { return } // a frame of the old mode
|
||||
IOSurfaceLock(surface, .readOnly, nil)
|
||||
let importStart = uptimeNs()
|
||||
let (kr, status, h) = observer.displayImport(base: UnsafeRawPointer(IOSurfaceGetBaseAddress(surface)),
|
||||
var (kr, status, h) = (kIOReturnBusy, Int64(0), UInt32(0))
|
||||
// kIOReturnBusy: another op holds the display gate (a STATUS or
|
||||
// PROBE, queued behind other clients' work on the driver's wait
|
||||
// pool); asked again for up to 2 s.
|
||||
for attempt in 0..<400 where kr == kIOReturnBusy {
|
||||
if attempt > 0 { usleep(5_000) }
|
||||
(kr, status, h) = observer.displayImport(base: UnsafeRawPointer(IOSurfaceGetBaseAddress(surface)),
|
||||
length: IOSurfaceGetAllocSize(surface), width: width,
|
||||
height: height, pitch: IOSurfaceGetBytesPerRow(surface))
|
||||
}
|
||||
IOSurfaceUnlock(surface, .readOnly, nil)
|
||||
guard kr == kIOReturnSuccess, status == 0, h != 0 else {
|
||||
failure = kr == kIOReturnSuccess ? "IMPORT of capture surface \(id): \(displayErrno(status))" :
|
||||
@@ -1186,6 +1193,9 @@ private func mirrorMonitor(observer: MacLinuxGPUHost, options: [String], daemon:
|
||||
if daemon && Date().timeIntervalSince(lastHotplugCheck) >= 2 {
|
||||
lastHotplugCheck = Date()
|
||||
let (kr, _, status) = observer.display(.status)
|
||||
// kIOReturnBusy: another op holds the display gate (the daemon's
|
||||
// own STATUS poll, or this process's IMPORT); the next poll reads.
|
||||
if kr == kIOReturnBusy { continue }
|
||||
if kr != kIOReturnSuccess { mirror.failure = callFailure(kr, "STATUS"); break }
|
||||
if let status, !status.connectors.contains(where: { $0.name == plan.connector && $0.connected }) {
|
||||
print("display-agent: \(plan.connector) disconnected")
|
||||
@@ -1527,10 +1537,9 @@ func runDisplayAgentDaemon(_ options: [String]) -> Int32 {
|
||||
let pipe = Pipe()
|
||||
child.process.standardOutput = pipe
|
||||
child.process.standardError = pipe
|
||||
pipe.fileHandleForReading.readabilityHandler = { handle in
|
||||
let data = handle.availableData
|
||||
// The read end closes itself at end of file, after the last line.
|
||||
followOutput(of: pipe) { data in
|
||||
DispatchQueue.main.async {
|
||||
guard !data.isEmpty else { return }
|
||||
FileHandle.standardOutput.write(data)
|
||||
child.buffer += String(decoding: data, as: UTF8.self)
|
||||
while let newline = child.buffer.firstIndex(of: "\n") {
|
||||
@@ -1547,7 +1556,6 @@ func runDisplayAgentDaemon(_ options: [String]) -> Int32 {
|
||||
}
|
||||
child.process.terminationHandler = { process in
|
||||
DispatchQueue.main.async {
|
||||
pipe.fileHandleForReading.readabilityHandler = nil
|
||||
child.exited = true
|
||||
// 0: the monitor left or it was stopped; 3: no monitor.
|
||||
if process.terminationStatus != 0 && process.terminationStatus != 3 {
|
||||
@@ -1559,6 +1567,9 @@ func runDisplayAgentDaemon(_ options: [String]) -> Int32 {
|
||||
do {
|
||||
try child.process.run()
|
||||
} catch {
|
||||
pipe.fileHandleForReading.readabilityHandler = nil
|
||||
try? pipe.fileHandleForReading.close()
|
||||
try? pipe.fileHandleForWriting.close()
|
||||
lastErrors[connector] = "could not start the mirroring process: \(error)"
|
||||
retryAt[connector] = Date().addingTimeInterval(10)
|
||||
return
|
||||
@@ -1739,7 +1750,8 @@ func runDisplayAgentDaemon(_ options: [String]) -> Int32 {
|
||||
lastErrors[connector] = nil
|
||||
}
|
||||
children[connector] = nil
|
||||
agentLog("display-agent: \(connector): mirroring process ended")
|
||||
agentLog("display-agent: \(connector): mirroring process ended" +
|
||||
(child.exited ? " (status \(child.process.terminationStatus))" : " (did not stop within 15 s)"))
|
||||
}
|
||||
for connector in wanted where children[connector] == nil {
|
||||
if let at = retryAt[connector], at > Date() { continue }
|
||||
|
||||
@@ -694,3 +694,43 @@ do {
|
||||
check(UpgradeHandover.clientsRemain.summary.contains("closes when the last of them quits"))
|
||||
}
|
||||
print("PASS upgrade handover: ShutdownGPU answers read as closed, closing, waiting for clients, quarantined or refused")
|
||||
|
||||
// A mirroring process's output (followOutput): every chunk, then the read
|
||||
// end closed at end of file. Before, the handler fired again at once at end
|
||||
// of file, forever, and each exited process left its pipe open.
|
||||
do {
|
||||
func openDescriptors() -> Int { (try? FileManager.default.contentsOfDirectory(atPath: "/dev/fd").count) ?? -1 }
|
||||
func cpuSeconds() -> Double {
|
||||
var usage = rusage()
|
||||
getrusage(RUSAGE_SELF, &usage)
|
||||
return Double(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) +
|
||||
Double(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1e6
|
||||
}
|
||||
let before = openDescriptors()
|
||||
for i in 0..<20 {
|
||||
let process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: "/bin/echo")
|
||||
process.arguments = ["line \(i)"]
|
||||
let pipe = Pipe()
|
||||
process.standardOutput = pipe
|
||||
process.standardError = pipe
|
||||
let lock = NSLock(), ended = DispatchSemaphore(value: 0)
|
||||
var received = Data(), ends = 0
|
||||
followOutput(of: pipe, onEnd: { lock.lock(); ends += 1; lock.unlock(); ended.signal() }) { data in
|
||||
lock.lock(); received.append(data); lock.unlock()
|
||||
}
|
||||
do { try process.run() } catch { check(false, "/bin/echo: \(error)") }
|
||||
process.waitUntilExit()
|
||||
check(ended.wait(timeout: .now() + 5) == .success, "end of file seen")
|
||||
lock.lock()
|
||||
check(String(decoding: received, as: UTF8.self) == "line \(i)\n", "every byte before the end")
|
||||
check(ends == 1, "the end is seen once")
|
||||
lock.unlock()
|
||||
}
|
||||
check(openDescriptors() == before, "no pipe left open: \(before) descriptors before, \(openDescriptors()) after")
|
||||
// Nothing fires once every process has ended.
|
||||
let cpu = cpuSeconds()
|
||||
Thread.sleep(forTimeInterval: 0.5)
|
||||
check(cpuSeconds() - cpu < 0.1, "idle after the processes ended")
|
||||
}
|
||||
print("PASS mirroring process output: every chunk, the read end closed at end of file, no descriptor left, no spin")
|
||||
Reference in new issue
Block a user