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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions App/Dashboard/CPUSection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,18 @@ struct CPUDetails: View {
}
DetailsHeading("Cores")
CoreGrid(cores: cpu.cores)
ForEach([CoreKind.efficiency, .performance], id: \.self) { kind in
ForEach(CoreKind.allCases, id: \.self) { kind in
if let average = cpu.averageLoad(of: kind) {
let count = cpu.cores.count { $0.kind == kind }
DetailRow(
label: "\(kind.name) · \(count)",
value: summary(average.formatted(), frequency(of: kind)?.formatted()) ?? missingValue
value: summary(average.formatted(), frequencies?.cores[kind]?.formatted()) ?? missingValue
)
}
}
AppList.byCPU(processes, tint: DashboardSection.cpu.tint)
}
}

private func frequency(of kind: CoreKind) -> Frequency? {
kind == .efficiency ? frequencies?.efficiencyCores : frequencies?.performanceCores
}
}

/// Total load over the whole history, user stacked under system.
Expand All @@ -86,7 +82,7 @@ private struct LoadChart: View {
}
}

/// One cell per core, shaded by load, with efficiency cores first.
/// One cell per core, shaded by load, with the slowest cores first.
private struct CoreGrid: View {
let cores: [CoreLoad]

Expand Down Expand Up @@ -125,13 +121,15 @@ private extension CoreKind {
switch self {
case .efficiency: "Efficiency"
case .performance: "Performance"
case .super: "Super"
}
}

var abbreviation: String {
switch self {
case .efficiency: "E"
case .performance: "P"
case .super: "S"
}
}
}
12 changes: 11 additions & 1 deletion Packages/BarometryKit/Sources/BarometryKit/Model/CPUSample.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
// SPDX-FileCopyrightText: 2026 Nick Wolff <nick@wolff.tech>
// SPDX-License-Identifier: GPL-3.0-only

public enum CoreKind: Sendable {
public enum CoreKind: Sendable, CaseIterable {
case efficiency
case performance
case `super`

init?(perflevelName: String) {
switch perflevelName {
case "Efficiency": self = .efficiency
case "Performance": self = .performance
case "Super": self = .super
default: return nil
}
}
}

/// Cumulative scheduler ticks for one logical CPU since boot.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,22 +56,20 @@ public struct GPUSample: Equatable, Sendable {
/// Average clock speed while active, over the last interval. Nil when the unit was idle
/// for the whole interval.
public struct FrequencySample: Equatable, Sendable {
public let efficiencyCores: Frequency?
public let performanceCores: Frequency?
public let cores: [CoreKind: Frequency]
public let gpu: Frequency?
/// Highest clock in each table, for scaling gauges.
public let gpuMaximum: Frequency?

public init(efficiencyCores: Frequency?, performanceCores: Frequency?, gpu: Frequency?, gpuMaximum: Frequency?) {
self.efficiencyCores = efficiencyCores
self.performanceCores = performanceCores
public init(cores: [CoreKind: Frequency], gpu: Frequency?, gpuMaximum: Frequency?) {
self.cores = cores
self.gpu = gpu
self.gpuMaximum = gpuMaximum
}

/// The headline CPU clock: performance cores when they ran, otherwise efficiency cores.
/// The headline CPU clock: the fastest core kind that ran.
public var cpu: Frequency? {
performanceCores ?? efficiencyCores
CoreKind.allCases.reversed().lazy.compactMap { cores[$0] }.first
}
}

Expand All @@ -94,6 +92,11 @@ enum DVFS {
return Frequency(hertz: weighted / total)
}

static func voltageStateIndices(fromAccClusters data: [UInt8]) -> [Int: Int] {
let entries = stride(from: 0, to: data.count - 7, by: 8).map { (cluster: Int(data[$0 + 1]), table: Int(data[$0])) }
return Dictionary(entries.map { ($0.cluster, $0.table) }) { first, _ in first }
}

/// Frequencies from a device tree `voltage-states` property: little-endian
/// (frequency, voltage) UInt32 pairs. Zero-frequency (off) entries are dropped.
/// Units vary by chip generation, so values are normalized to hertz by magnitude.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,77 @@
import Foundation
import IOKit

enum CoreTopology {
struct CoreTopology: Equatable {
struct PerfLevel: Equatable {
let kind: CoreKind
let logicalCPUs: Int
}

struct CPUNode: Equatable {
let logicalID: Int
let clusterID: Int?
let clusterType: Character
}

struct Cluster: Equatable {
let id: Int
let type: Character
let kind: CoreKind
}

/// Core kinds indexed by logical CPU number.
static func current() -> [CoreKind] {
if let kinds = deviceTreeKinds() {
return kinds
let kinds: [CoreKind]
let clusters: [Cluster]

static func current() -> CoreTopology {
let levels = perfLevels()
if let cpus = deviceTreeCPUs(), let topology = CoreTopology(cpus: cpus, levels: levels) {
return topology
}
let performance = Sysctl.integer("hw.perflevel0.logicalcpu", as: Int32.self)
?? Sysctl.integer("hw.ncpu", as: Int32.self)
?? 0
let efficiency = Sysctl.integer("hw.perflevel1.logicalcpu", as: Int32.self) ?? 0
return fallbackKinds(efficiency: Int(efficiency), performance: Int(performance))
return CoreTopology(levels: levels)
}

/// Apple Silicon numbers efficiency cores before performance cores.
static func fallbackKinds(efficiency: Int, performance: Int) -> [CoreKind] {
Array(repeating: .efficiency, count: max(efficiency, 0)) + Array(repeating: .performance, count: max(performance, 0))
/// Apple Silicon numbers its slowest cores first.
init(levels: [PerfLevel]) {
kinds = levels.reversed().flatMap { Array(repeating: $0.kind, count: max($0.logicalCPUs, 0)) }
clusters = []
}

/// Reads each `IODeviceTree:/cpus/cpuN` node's `logical-cpu-id` and `cluster-type` ("E" or "P").
private static func deviceTreeKinds() -> [CoreKind]? {
init?(cpus: [CPUNode], levels: [PerfLevel]) {
let clusterTypesSlowestFirst: [Character] = ["E", "M", "P"]
let types = Set(cpus.map(\.clusterType))
guard !cpus.isEmpty,
types.isSubset(of: clusterTypesSlowestFirst),
types.count == levels.count,
Set(cpus.map(\.logicalID)) == Set(0..<cpus.count)
else { return nil }

let presentTypes = clusterTypesSlowestFirst.filter(types.contains)
let kindByType = Dictionary(uniqueKeysWithValues: zip(presentTypes, levels.reversed().map(\.kind)))
let byLogicalID = Dictionary(uniqueKeysWithValues: cpus.map { ($0.logicalID, $0) })
kinds = (0..<cpus.count).compactMap { byLogicalID[$0].flatMap { kindByType[$0.clusterType] } }
let typeByClusterID = Dictionary(cpus.compactMap { cpu in cpu.clusterID.map { ($0, cpu.clusterType) } }) { first, _ in first }
clusters = typeByClusterID
.compactMap { id, type in kindByType[type].map { Cluster(id: id, type: type, kind: $0) } }
.sorted { $0.id < $1.id }
}

private static func perfLevels() -> [PerfLevel] {
let count = Int(Sysctl.integer("hw.nperflevels", as: Int32.self) ?? 0)
let levels = (0..<count).compactMap { level -> PerfLevel? in
guard let cpus = Sysctl.integer("hw.perflevel\(level).logicalcpu", as: Int32.self) else { return nil }
let kind = Sysctl.string("hw.perflevel\(level).name").flatMap(CoreKind.init(perflevelName:))
?? (level == 0 ? .performance : .efficiency)
return PerfLevel(kind: kind, logicalCPUs: Int(cpus))
}
if levels.isEmpty, let cpus = Sysctl.integer("hw.ncpu", as: Int32.self) {
return [PerfLevel(kind: .performance, logicalCPUs: Int(cpus))]
}
return levels
}

/// Reads each `IODeviceTree:/cpus/cpuN` node's `logical-cpu-id`, `cluster-id`, and `cluster-type`.
private static func deviceTreeCPUs() -> [CPUNode]? {
let cpus = IORegistryEntryFromPath(kIOMainPortDefault, "IODeviceTree:/cpus")
guard cpus != IO_OBJECT_NULL else { return nil }
defer { IOObjectRelease(cpus) }
Expand All @@ -32,18 +83,16 @@ enum CoreTopology {
guard IORegistryEntryGetChildIterator(cpus, kIODeviceTreePlane, &iterator) == KERN_SUCCESS else { return nil }
defer { IOObjectRelease(iterator) }

var kindsByID: [Int: CoreKind] = [:]
var nodes: [CPUNode] = []
while case let entry = IOIteratorNext(iterator), entry != IO_OBJECT_NULL {
defer { IOObjectRelease(entry) }
guard let id = property(entry, "logical-cpu-id") as? Int,
let clusterType = property(entry, "cluster-type") as? Data,
let first = clusterType.first
let clusterType = (property(entry, "cluster-type") as? Data)?.first
else { continue }
kindsByID[id] = first == UInt8(ascii: "E") ? .efficiency : .performance
let clusterID = (property(entry, "cluster-id") as? Data)?.first.map(Int.init)
nodes.append(CPUNode(logicalID: id, clusterID: clusterID, clusterType: Character(UnicodeScalar(clusterType))))
}

guard !kindsByID.isEmpty, Set(kindsByID.keys) == Set(0..<kindsByID.count) else { return nil }
return (0..<kindsByID.count).compactMap { kindsByID[$0] }
return nodes.isEmpty ? nil : nodes
}

private static func property(_ entry: io_registry_entry_t, _ key: String) -> Any? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Darwin

struct CPUSampler {
private let host = mach_host_self()
private let kinds = CoreTopology.current()
private let kinds = CoreTopology.current().kinds
private var previous: [CPUTicks]?

/// Returns nil on the first call, since load needs two readings.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,64 @@ struct FrequencySampler {
("CPU Stats", "CPU Complex Performance States"),
("GPU Stats", "GPU Performance States"),
])
private let efficiencyTable: [Frequency]
private let performanceTable: [Frequency]
private struct CoreCluster {
let kind: CoreKind
let channelPrefix: String
let table: [Frequency]
}

private static let legacyCoreTableKeys: [Character: String] = ["E": "voltage-states1-sram", "P": "voltage-states5-sram"]

private let coreClusters: [CoreCluster]
private let gpuTable: [Frequency]

init() {
let tables = Self.voltageStateTables(["voltage-states1-sram", "voltage-states5-sram", "voltage-states9"])
efficiencyTable = tables[0]
performanceTable = tables[1]
gpuTable = tables[2]
let pmgr = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceNameMatching("pmgr"))
defer { IOObjectRelease(pmgr) }
func data(_ key: String) -> [UInt8]? {
guard pmgr != IO_OBJECT_NULL,
let value = IORegistryEntryCreateCFProperty(pmgr, key as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? Data
else { return nil }
return Array(value)
}
func table(_ key: String) -> [Frequency] {
data(key).map(DVFS.frequencyTable(fromVoltageStates:)) ?? []
}

let clusters = CoreTopology.current().clusters
let kindByType = clusters.isEmpty
? ["E": .efficiency, "P": .performance]
: Dictionary(clusters.map { ($0.type, $0.kind) }) { first, _ in first }
let voltageStatesByCluster = data("acc-clusters").map(DVFS.voltageStateIndices(fromAccClusters:)) ?? [:]

coreClusters = kindByType.sorted { $0.key < $1.key }.map { type, kind in
let legacyTable = Self.legacyCoreTableKeys[type].map(table) ?? []
let discoveredTable = clusters.first { $0.type == type }
.flatMap { voltageStatesByCluster[$0.id] }
.map { table("voltage-states\($0)-sram") } ?? []
return CoreCluster(kind: kind, channelPrefix: "\(type)CPU", table: legacyTable.isEmpty ? discoveredTable : legacyTable)
}
gpuTable = table("voltage-states9")
}

/// Nil on the first call and when IOReport is unavailable.
func sample() -> FrequencySample? {
guard let channels = subscription?.sample(), !channels.isEmpty else { return nil }

// Channel names: ECPU/PCPU per cluster (with a trailing number on multi-cluster chips),
// ECPM/PCPM for cluster memory, which is skipped, and GPUPH for the GPU.
// Channel names: ECPU/MCPU/PCPU per cluster (with a trailing number on multi-cluster chips),
// ECPM/MCPM/PCPM for cluster memory, which is skipped, and GPUPH for the GPU.
func frequency(prefix: String, table: [Frequency]) -> Frequency? {
let states = channels
.filter { $0.name.hasPrefix(prefix) }
.flatMap(\.states)
return DVFS.averageFrequency(states: Self.mergeByName(states), table: table)
}

let cores = coreClusters.compactMap { cluster in
frequency(prefix: cluster.channelPrefix, table: cluster.table).map { (cluster.kind, $0) }
}
return FrequencySample(
efficiencyCores: frequency(prefix: "ECPU", table: efficiencyTable),
performanceCores: frequency(prefix: "PCPU", table: performanceTable),
cores: Dictionary(cores) { first, _ in first },
gpu: frequency(prefix: "GPUPH", table: gpuTable),
gpuMaximum: gpuTable.max()
)
Expand All @@ -56,13 +87,4 @@ struct FrequencySampler {
return order.map { ($0, totals[$0] ?? 0) }
}

private static func voltageStateTables(_ keys: [String]) -> [[Frequency]] {
let pmgr = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceNameMatching("pmgr"))
guard pmgr != IO_OBJECT_NULL else { return keys.map { _ in [] } }
defer { IOObjectRelease(pmgr) }
return keys.map { key in
guard let data = IORegistryEntryCreateCFProperty(pmgr, key as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? Data else { return [] }
return DVFS.frequencyTable(fromVoltageStates: Array(data))
}
}
}
Loading
Loading