-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLibXPUInfo_Metal.mm
298 lines (251 loc) · 10.2 KB
/
LibXPUInfo_Metal.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright (C) 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "LibXPUInfo.h"
#include "LibXPUInfo_Util.h"
#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>
#include <Metal/Metal.h>
#include <mach/vm_statistics.h>
#include <sstream>
//#pragma optimize("", off)
namespace
{
static uint64_t util_get_free_memory()
{
mach_port_t hostPort;
mach_msg_type_number_t hostSize;
vm_size_t pageSize;
hostPort = mach_host_self();
hostSize = sizeof(vm_statistics64_data_t) / sizeof(integer_t);
host_page_size(hostPort, &pageSize);
vm_statistics64_data_t vmStat;
if (host_statistics(hostPort, HOST_VM_INFO, (host_info_t)&vmStat, &hostSize) != KERN_SUCCESS)
{
NSLog(@"Failed to fetch vm statistics");
return UINT64_MAX;
}
return vmStat.free_count * pageSize;
}
static uint64_t util_get_active_memory()
{
mach_port_t hostPort;
mach_msg_type_number_t hostSize;
vm_size_t pageSize;
hostPort = mach_host_self();
hostSize = sizeof(vm_statistics64_data_t) / sizeof(integer_t);
host_page_size(hostPort, &pageSize);
vm_statistics64_data_t vmStat;
if (host_statistics(hostPort, HOST_VM_INFO, (host_info_t)&vmStat, &hostSize) != KERN_SUCCESS)
{
NSLog(@"Failed to fetch vm statistics");
return UINT64_MAX;
}
//std::cout << "Usage: " << vmStat.active_count * pageSize / (1024*1024*1024ULL) << std::endl;
return vmStat.active_count * pageSize;
}
static uint64_t util_get_total_memory()
{
mach_port_t hostPort;
mach_msg_type_number_t hostSize;
vm_size_t pageSize;
hostPort = mach_host_self();
hostSize = sizeof(vm_statistics64_data_t) / sizeof(integer_t);
host_page_size(hostPort, &pageSize);
vm_statistics64_data_t vmStat;
if (host_statistics(hostPort, HOST_VM_INFO, (host_info_t)&vmStat, &hostSize) != KERN_SUCCESS)
{
NSLog(@"Failed to fetch vm statistics");
return UINT64_MAX;
}
//std::cout << "Usage: " << vmStat.active_count * pageSize / (1024*1024*1024ULL) << std::endl;
//return (vmStat.active_count+vmStat.free_count+vmStat.inactive_count+vmStat.wire_count) * pageSize;
return (vmStat.internal_page_count + vmStat.external_page_count) * pageSize;
}
}
namespace XI
{
DXCoreAdapterMemoryBudget Device::getMemUsage_Metal() const
{
DXCoreAdapterMemoryBudget mi{};
#if 1
mi.currentUsage = util_get_active_memory();
//std::cout << __FUNCTION__ << ": Usage = " << mi.currentUsage / (1024*1024*1024.0) << std::endl;
#elif 0
task_t task = MACH_PORT_NULL;
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(),
TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count))
{
return mi;
}
mi.currentUsage = t_info.resident_size * getpagesize(); // working set
//*vs = t_info.virtual_size; // commit
#endif
#if 0
// Not macOS?
return os_proc_available_memory();
#else
if (@available(macOS 10.13, *))
{
NSArray* metalDevices = MTLCopyAllDevices();
for (id device in metalDevices)
{
uint64_t deviceId = [device registryID];
if (deviceId == getLUID())
{
// UNUSED auto memUsed = [device currentAllocatedSize];
auto budget = [device recommendedMaxWorkingSetSize];
//mi.currentUsage = memUsed;
mi.budget = budget;
break;
}
}
}
#endif
return mi;
}
SystemInfo::SystemInfo()
{
// The following block won't compile with automatic reference counting
// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// [pool drain];
// Therefore use the modernized way: @autoreleasepool
@autoreleasepool {
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
NSOperatingSystemVersion osVersion = [processInfo operatingSystemVersion];
OS.BuildNumber = convert(std::to_string(osVersion.majorVersion) + "." + std::to_string(osVersion.minorVersion) + "." + std::to_string(osVersion.patchVersion));
std::string osVersionStr = [[processInfo operatingSystemVersionString] UTF8String];
auto buildPos = osVersionStr.find("(Build");
if (buildPos != osVersionStr.npos)
{
OS.BuildNumber += convert(" " + osVersionStr.substr(buildPos));
}
OS.Caption = L"macOS " + convert(osVersionStr);
TotalPhysicalMemory = [processInfo physicalMemory];
NumberOfProcessors = [processInfo processorCount];
}
char model[64] = {};
size_t len=sizeof(model);
int err = sysctlbyname("hw.model", model, &len, NULL, 0);
Manufacturer = L"Apple";
if (!err)
{
Model = convert(model);
}
memset(model, 0, sizeof(model));
len=sizeof(model);
err = sysctlbyname("hw.targettype", model, &len, NULL, 0);
if (!err)
{
SystemSKUNumber = convert(model);
}
//OS.TotalVirtualMemorySizeKB = util_get_total_memory() / 1024ULL;
//OS.FreeVirtualMemoryKB = util_get_free_memory() / 1024ULL;
}
UI32 SystemInfo::OSInfo::getUptimeDays() const
{
NSTimeInterval systemUptime;
@autoreleasepool {
systemUptime = [[NSProcessInfo processInfo] systemUptime];
}
const double secondsInDay = 60*60*24;
return (UI32)(systemUptime / secondsInDay);
}
void XPUInfo::initMetal()
{
m_pSystemInfo.reset(new SystemInfo);
UI64 deviceVersionFromOS = 0;
@autoreleasepool {
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
NSOperatingSystemVersion osVersion = [processInfo operatingSystemVersion];
deviceVersionFromOS = (UI64(osVersion.majorVersion) << 16*3) |
(UI64(osVersion.minorVersion) << 16*2) |
(UI64(osVersion.patchVersion) << 16*1);
}
int adapterIndex=0;
if (@available(macOS 10.13, *))
{
NSArray* metalDevices = MTLCopyAllDevices();
for (id device in metalDevices)
{
DXGI_ADAPTER_DESC1 desc{};
const char* cdeviceName = [[device name] UTF8String];
uint64_t deviceId = [device registryID];
BOOL isRemovable = [device isRemovable];
BOOL isHighPerformance = ![device isLowPower]; // The property is typically true for integrated GPUs and false for discrete GPUs. However, an Apple silicon GPU on a Mac sets the property to false because it doesn’t need to lower its performance to conserve energy.
WString name(convert(cdeviceName));
wcsncpy(desc.Description, name.c_str(), 128);
desc.AdapterLuid.ui64 = deviceId;
desc.SharedSystemMemory = [device recommendedMaxWorkingSetSize];
DevicePtr newDevice(new Device(adapterIndex++, &desc, DEVICE_TYPE_GPU, API_TYPE_METAL, deviceVersionFromOS));
I64 bw = [device maxTransferRate];
newDevice->m_props.MemoryBandWidthMax = (bw > 0) ? bw : -1LL;
newDevice->m_props.UMA = [device hasUnifiedMemory] ? UMA_INTEGRATED : NONUMA_DISCRETE;
newDevice->validAPIs = API_TYPE_METAL;
newDevice->m_props.IsDetachable = isRemovable;
newDevice->m_props.IsHighPerformance = isHighPerformance;
m_Devices.insert(std::make_pair(deviceId, newDevice));
if (!(m_UsedAPIs & API_TYPE_METAL))
{
m_UsedAPIs = m_UsedAPIs | API_TYPE_METAL;
}
}
}
}
#if 0
// See https://stackoverflow.com/questions/10110658/programmatically-get-gpu-percent-usage-in-os-x
#include <CoreFoundation/CoreFoundation.h>
#include <Cocoa/Cocoa.h>
#include <IOKit/IOKitLib.h>
int main(int argc, const char * argv[])
{
while (1) {
// Get dictionary of all the PCI Devicces
CFMutableDictionaryRef matchDict = IOServiceMatching(kIOAcceleratorClassName);
// Create an iterator
io_iterator_t iterator;
if (IOServiceGetMatchingServices(kIOMasterPortDefault,matchDict,
&iterator) == kIOReturnSuccess)
{
// Iterator for devices found
io_registry_entry_t regEntry;
while ((regEntry = IOIteratorNext(iterator))) {
// Put this services object into a dictionary object.
CFMutableDictionaryRef serviceDictionary;
if (IORegistryEntryCreateCFProperties(regEntry,
&serviceDictionary,
kCFAllocatorDefault,
kNilOptions) != kIOReturnSuccess)
{
// Service dictionary creation failed.
IOObjectRelease(regEntry);
continue;
}
CFMutableDictionaryRef perf_properties = (CFMutableDictionaryRef) CFDictionaryGetValue( serviceDictionary, CFSTR("PerformanceStatistics") );
if (perf_properties) {
static ssize_t gpuCoreUse=0;
static ssize_t freeVramCount=0;
static ssize_t usedVramCount=0;
const void* gpuCoreUtilization = CFDictionaryGetValue(perf_properties, CFSTR("GPU Core Utilization"));
const void* freeVram = CFDictionaryGetValue(perf_properties, CFSTR("vramFreeBytes"));
const void* usedVram = CFDictionaryGetValue(perf_properties, CFSTR("vramUsedBytes"));
if (gpuCoreUtilization && freeVram && usedVram)
{
CFNumberGetValue( (CFNumberRef) gpuCoreUtilization, kCFNumberSInt64Type, &gpuCoreUse);
CFNumberGetValue( (CFNumberRef) freeVram, kCFNumberSInt64Type, &freeVramCount);
CFNumberGetValue( (CFNumberRef) usedVram, kCFNumberSInt64Type, &usedVramCount);
NSLog(@"GPU: %.3f%% VRAM: %.3f%%",gpuCoreUse/(double)10000000,usedVramCount/(double)(freeVramCount+usedVramCount)*100.0);
}
}
CFRelease(serviceDictionary);
IOObjectRelease(regEntry);
}
IOObjectRelease(iterator);
}
sleep(1);
}
return 0;
}
#endif
} // XI