Repository navigation
Expand file tree
/
Copy pathNVMTLDevice.m
More file actions
2223 lines (2181 loc) · 147 KB
/
Copy pathNVMTLDevice.m
File metadata and controls
2223 lines (2181 loc) · 147 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* NullMoth NVIDIA driver for macOS
* Copyright (c) 2026 NullMoth Systems.
* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
*/
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h> // the decode service finds the GPU in the I/O registry (#175)
#import <Metal/Metal.h>
#import <objc/runtime.h>
#import <objc/message.h>
#import <mach/mach.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <stdint.h>
#include <vulkan/vulkan_core.h>
#include <pthread.h>
#include <stdatomic.h>
#include <time.h>
#include "nvmtl_sample_positions.h"
#include "nvmtl_log_failure.h"
#include <sys/sysctl.h>
#ifndef NVMTL_RELEASE
#define NVMTL_RELEASE 0
#endif
#if NVMTL_RELEASE
static inline int nvmtl_rel_devpath(const char *p) {
return p && (!strncmp(p, "/tmp/nvmtl-", 11) || !strncmp(p, "/private/tmp/nvmtl-", 19));
}
static inline int nvmtl_rel_access(const char *p, int m) { return nvmtl_rel_devpath(p) ? -1 : access(p, m); }
static inline FILE *nvmtl_rel_fopen(const char *p, const char *m) { return nvmtl_rel_devpath(p) ? NULL : fopen(p, m); }
// Function-like on purpose: an object-like `#define access` also renamed every Objective-C `-access` method in this
// one-TU plugin, so release builds answered -[MTLBinding access] with nothing (selector nvmtl_rel_access in the
// shipped binary). Apple's OpenCL then read every image as read-only and refused write-only images (-38).
#define access(p, m) nvmtl_rel_access(p, m)
#define fopen(p, m) nvmtl_rel_fopen(p, m)
#endif
int nvmtl_vk_init(void);
void nvmtl_gl_caps_enable(void);
uint16_t nvmtl_vk_set_accelerator(mach_port_t accelerator);
uint16_t nvmtl_vk_vendor(void);
const char *nvmtl_vk_device_name(void);
void nvmtl_vk_counts(uint64_t *bm, uint64_t *bg, uint64_t *im, uint64_t *ig, size_t *bytes);
void nvmtl_vk_cmd_counts(uint64_t *begun, uint64_t *submitted, uint64_t *abandoned);
static int nvmtl_sample_payload_abi(id value) {
if (![value isKindOfClass:[NSDictionary class]]) return 0;
const unsigned long long expected[] = {NVMTL_SAMPLE_POSITION_OFFSET, NVMTL_SAMPLE_POSITION_BYTES, NVMTL_MAX_SAMPLE_POSITIONS, sizeof(nvmtl_sample_position)};
NSArray *keys = @[@"offset", @"size", @"positions", @"stride"];
for (NSUInteger i = 0; i < keys.count; ++i) {
id number = value[keys[i]];
if (![number isKindOfClass:[NSNumber class]]) return 0;
const char *type = [number objCType];
if (!type || !type[0] || type[1] || !strchr("cCsSiIlLqQ", type[0])) return 0;
if ([number longLongValue] < 0 || [number unsignedLongLongValue] != expected[i]) return 0;
}
return 1;
}
#define NVLOG_SITES 256
#define NVLOG_VERBATIM 8
#define NVLOG_EVERY 4096
static struct { const char *fmt; uint64_t n; } g_nvlog_sites[NVLOG_SITES];
static pthread_mutex_t g_nvlog_lock = PTHREAD_MUTEX_INITIALIZER;
static int nvlog_dropped(const char *fmt, uint64_t *rep) {
*rep = 0;
pthread_mutex_lock(&g_nvlog_lock);
int i = 0;
for (; i < NVLOG_SITES; i++) {
if (g_nvlog_sites[i].fmt == fmt) break;
if (!g_nvlog_sites[i].fmt) { g_nvlog_sites[i].fmt = fmt; break; }
}
if (i == NVLOG_SITES) { pthread_mutex_unlock(&g_nvlog_lock); return 0; }
uint64_t n = ++g_nvlog_sites[i].n;
pthread_mutex_unlock(&g_nvlog_lock);
if (n <= NVLOG_VERBATIM) return 0;
if (n % NVLOG_EVERY == 0) { *rep = n; return 0; }
return 1;
}
const char *nvmtl_log_path(void) {
#if NVMTL_RELEASE
return "/private/tmp/nvmtl-off.log";
#endif
// A diagnostic probe needs its own file even when the system log is writable.
// Otherwise the per-run fault watcher reads an empty file and misses GPU faults.
const char *requested = getenv("NVMTL_LOG_PATH");
if (requested && *requested) return requested;
static char path[1024]; static int decided;
if (!decided) {
decided = 1;
FILE *f = fopen("/tmp/nvmtl.log", "a");
if (f) { fclose(f); snprintf(path, sizeof path, "/tmp/nvmtl.log"); }
else { const char *t = getenv("TMPDIR"); snprintf(path, sizeof path, "%s/nvmtl.log", (t && *t) ? t : "/private/tmp"); }
}
return path;
}
void nvlog(const char *fmt, ...) {
uint64_t rep; if (nvlog_dropped(fmt, &rep)) return;
char b[512]; va_list a; va_start(a, fmt); vsnprintf(b, sizeof b, fmt, a); va_end(a);
char t[640];
if (rep) snprintf(t, sizeof t, "%s [logged %llu times now]", b, (unsigned long long)rep);
else snprintf(t, sizeof t, "%s", b);
#if NVMTL_RELEASE
if (nvmtl_log_failure(t)) syslog(LOG_ERR, "NullMoth: %s", t);
#else
syslog(LOG_NOTICE, "NVMTL: %s", t);
FILE *f = fopen(nvmtl_log_path(), "a"); if (f) { fprintf(f, "pid %d NVMTL: %s\n", getpid(), t); fclose(f); }
#endif
}
#define NVMTL_OOM_STREAK 32
#define NVMTL_OOM_COOLDOWN_NS (250ull * 1000ull * 1000ull)
static _Atomic uint64_t g_oom_streak, g_oom_until;
static int nvmtl_alloc_blocked(void) {
if (atomic_load(&g_oom_streak) < NVMTL_OOM_STREAK) return 0;
if (clock_gettime_nsec_np(CLOCK_MONOTONIC) >= atomic_load(&g_oom_until)) {
atomic_store(&g_oom_streak, NVMTL_OOM_STREAK - 1);
return 0;
}
return 1;
}
static void nvmtl_alloc_ok(void) { atomic_store(&g_oom_streak, 0); }
static void nvmtl_alloc_failed(const char *what) {
uint64_t n = atomic_fetch_add(&g_oom_streak, 1) + 1;
atomic_store(&g_oom_until, clock_gettime_nsec_np(CLOCK_MONOTONIC) + NVMTL_OOM_COOLDOWN_NS);
if (n < NVMTL_OOM_STREAK) return;
uint64_t bm = 0, bg = 0, im = 0, ig = 0; size_t bytes = 0;
nvmtl_vk_counts(&bm, &bg, &im, &ig, &bytes);
uint64_t cb = 0, cs = 0, ca = 0; nvmtl_vk_cmd_counts(&cb, &cs, &ca);
nvlog("ALLOCATION FAILING (%s) - throttling %llu ms. buffers made %llu freed %llu LIVE %llu | "
"images made %llu freed %llu LIVE %llu | holding %llu MB of VkDeviceMemory | cmdbufs begun %llu submitted %llu abandoned %llu",
what, (unsigned long long)(NVMTL_OOM_COOLDOWN_NS / 1000000ull),
(unsigned long long)bm, (unsigned long long)bg, (unsigned long long)(bm - bg),
(unsigned long long)im, (unsigned long long)ig, (unsigned long long)(im - ig),
(unsigned long long)(bytes >> 20), (unsigned long long)cb, (unsigned long long)cs, (unsigned long long)ca);
}
@interface MTLIOAccelDevice : NSObject
- (instancetype)initWithAcceleratorPort:(mach_port_t)port;
@end
@protocol MTLDeviceSPI <NSObject> @end
@interface NVMTLDevice : MTLIOAccelDevice <MTLDevice, MTLDeviceSPI>
@end
#import "NVMTLObjects.h"
void nvmtl_vendor_compile_airs(NSDictionary<NSString *, NSString *> *airs,
NSDictionary<NSString *, NSString *> *stages);
void nvmtl_vendor_attach_sass(id device, id pipelineState, id function);
int nvmtl_vendor_dispatch_sass(id pipelineState, nvk_cmdbuf *c,
const uint32_t threads[3], const uint32_t tg[3]);
id nvmtl_vendor_apple_pipeline(id device, id function);
id nvmtl_sass_kernel_for_function(id function);
id nvmtl_sass_kernel_for_linked(id function, NSDictionary *mods, NSDictionary *fc);
BOOL nvmtl_sass_tables_wanted(void);
int nvmtl_sass_dispatch(id encoder, MTLSize grid, MTLSize group, uint32_t kind, BOOL hasFallback);
NSDictionary<NSString *, NSData *> *nvmtl_translate_metallib(NSData *lib, NSDictionary **stages, NSDictionary **airs);
void nvmtl_vendor_compile_airs(NSDictionary<NSString *, NSString *> *airs,
NSDictionary<NSString *, NSString *> *stages);
#include <sys/stat.h>
NSDictionary<NSString *, NSData *> *nvmtl_translate_metallib_k(NSData *lib, NSData *knownKey, NSDictionary **stages, NSDictionary **airs);
NSData *nvmtl_lib_sha256(NSData *lib);
NSData *nvmtl_libkey_for_file(NSString *path, NSData *lib, const struct stat *before);
int nvmtl_stat_same(const struct stat *a, const struct stat *b);
static char gNVMTLLibKeyAssoc, gNVMTLLibFileAssoc;
NSArray<NSString *> *nvmtl_externs_of_airs(NSDictionary<NSString *, NSString *> *airs);
NSSet<NSString *> *nvmtl_mtlb_extern_names(NSData *raw);
@interface NSObject (NVMTLExternSPI)
- (id)newExternFunctionWithName:(NSString *)name;
- (id)nvmtlAppleTwinOf:(id)lib;
@end
static nvk_queue *nvmtl_device_queue(void) {
static nvk_queue q; static int made = 0;
if (!made) { if (nvmtl_vk_queue_create(&q)) { nvlog("device queue FAILED"); return NULL; } made = 1; }
return &q;
}
static bool nvmtl_accel_armed(void)
{
int v = 0; size_t n = sizeof v;
if (sysctlbyname("debug.nvaccelfb", &v, &n, NULL, 0) != 0) return false;
return v != 0;
}
#include <dlfcn.h>
#include <libgen.h>
// The video libraries tile and untile frames in the Blackwell (GB20x) layout. Earlier GPUs' NVDEC/NVENC use the classic
// one: on an RTX 3070 Laptop (issue #65, measured against Apple's software codecs) H.264 decode showed shifted macroblock
// rows and a green stripe, and both encoders produced torn pictures. The decoder's only difference is its untiling mode
// (1 = Blackwell, 0 = classic), so earlier GPUs load libnvdec_h264_t2d.dylib, the same library with mode 0 (51 dB on
// GA104). The encoders are not registered on them, so apps use Apple's encoder until they are fixed for those GPUs.
// Set from the I/O registry where no Metal device (and so no Vulkan device name) exists: -1 = unknown, use the name.
static int g_video_blackwell = -1;
// One string from the per-generation profile NVRM publishes on the GPU's PCI device ("nvrm-gpu-profile": chip,
// generation, engine classes, scan-out model, video layout). False when the driver is older than the profile or the key
// is missing; callers then keep their previous rule.
static bool nvmtl_gpu_profile_string(CFStringRef key, char *out, size_t n)
{
bool ok = false;
io_iterator_t it = IO_OBJECT_NULL;
if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOPCIDevice"), &it) != KERN_SUCCESS) return false;
for (io_object_t o; !ok && (o = IOIteratorNext(it)); IOObjectRelease(o)) {
CFTypeRef d = IORegistryEntryCreateCFProperty(o, CFSTR("nvrm-gpu-profile"), kCFAllocatorDefault, 0);
if (!d) continue;
if (CFGetTypeID(d) == CFDictionaryGetTypeID()) {
CFTypeRef v = CFDictionaryGetValue((CFDictionaryRef)d, key);
if (v && CFGetTypeID(v) == CFStringGetTypeID()) ok = CFStringGetCString((CFStringRef)v, out, (CFIndex)n, kCFStringEncodingUTF8);
}
CFRelease(d);
}
IOObjectRelease(it);
return ok;
}
static bool nvmtl_video_is_blackwell(void)
{
if (g_video_blackwell >= 0) return g_video_blackwell == 1;
char layout[32];
if (nvmtl_gpu_profile_string(CFSTR("video-layout"), layout, sizeof layout)) {
g_video_blackwell = !strcmp(layout, "blackwell");
return g_video_blackwell == 1;
}
return strstr(nvmtl_vk_device_name(), "NVK GB") != NULL;
}
// The H.264 encoder library built for this card's generation, or NULL when we ship none for it (then the app keeps
// Apple's encoder, which is what every non-Blackwell card got before these libraries existed).
// The setup a card's NVENC expects differs per generation: Turing and Ampere write the same picture setup apart from
// the class byte, and Blackwell differs in the plane offsets, the input layout and the padding. Each library is
// checked byte-for-byte against NVIDIA's own output on that generation before it ships.
// The HEVC encoder library for this card's generation. Turing and Ampere write the same HEVC setup apart from the
// class byte, checked byte-for-byte against NVIDIA's own output on each; Blackwell differs in the layout as it does
// for H.264.
static const char *nvmtl_nvenc_hevc_library_for_this_gpu(void)
{
char gen[32];
if (!nvmtl_gpu_profile_string(CFSTR("generation"), gen, sizeof gen))
return nvmtl_video_is_blackwell() ? "libnvenc_hevc.dylib" : NULL;
if (!strcmp(gen, "Blackwell")) return "libnvenc_hevc.dylib";
if (!strcmp(gen, "Ampere")) return "libnvenc_hevc_ga10x.dylib";
if (!strcmp(gen, "Turing")) return "libnvenc_hevc_tu10x.dylib";
return NULL;
}
static const char *nvmtl_nvenc_library_for_this_gpu(void)
{
char gen[32];
if (!nvmtl_gpu_profile_string(CFSTR("generation"), gen, sizeof gen)) {
// No profile: fall back to the name test, which only recognises Blackwell.
return nvmtl_video_is_blackwell() ? "libnvenc_h264.dylib" : NULL;
}
if (!strcmp(gen, "Blackwell")) return "libnvenc_h264.dylib";
if (!strcmp(gen, "Ampere")) return "libnvenc_h264_ga10x.dylib";
if (!strcmp(gen, "Turing")) return "libnvenc_h264_tu10x.dylib";
return NULL;
}
static void nvmtl_nvdec_register(void)
{
static dispatch_once_t once;
dispatch_once(&once, ^{
const char *me = getprogname();
if (getenv("NVMTL_NO_NVDEC")) { nvlog("nvdec: NVMTL_NO_NVDEC set - not registering in %s", me); return; }
if (!strcmp(me, "WindowServer")) return;
typedef int32_t (*RegFn)(uint32_t, CFDictionaryRef, void *);
RegFn reg = (RegFn)dlsym(RTLD_DEFAULT, "VTRegisterVideoDecoderWithInfo");
if (!reg) { nvlog("nvdec: VideoToolbox is not loaded in %s - not registering", me); return; }
Dl_info di;
if (!dladdr((const void *)nvmtl_nvdec_register, &di) || !di.dli_fname) { nvlog("nvdec: dladdr failed - not registering"); return; }
char dir[1024], path[1200];
strlcpy(dir, di.dli_fname, sizeof dir);
snprintf(path, sizeof path, "%s/%s", dirname(dir), nvmtl_video_is_blackwell() ? "libnvdec_h264.dylib" : "libnvdec_h264_t2d.dylib");
void *h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!h) { nvlog("nvdec: dlopen %s FAILED: %s", path, dlerror()); return; }
void *fac = dlsym(h, "NVDecH264_CreateInstance");
if (!fac) { nvlog("nvdec: %s has no NVDecH264_CreateInstance", path); return; }
NSDictionary *info = @{ @"CMClassImplementationID": @"com.nvmtl.videodecoder.avc.nvdec",
@"VTRating": @1000, @"VTIsHardwareAccelerated": @YES };
int32_t st = reg('avc1', (__bridge CFDictionaryRef)info, fac);
nvlog("nvdec: H.264 decoder %s in %s (VTRegisterVideoDecoderWithInfo -> %d, rating 1000, %s)",
st ? "NOT registered" : "REGISTERED", me, (int)st, path);
});
}
static void nvmtl_nvenc_register(void)
{
static dispatch_once_t once;
dispatch_once(&once, ^{
const char *me = getprogname();
if (getenv("NVMTL_NO_NVENC")) { nvlog("nvenc: NVMTL_NO_NVENC set - not registering in %s", me); return; }
const char *lib = nvmtl_nvenc_library_for_this_gpu();
if (!lib) { nvlog("nvenc: no encoder library for %s - H.264 encode stays on Apple's encoder", nvmtl_vk_device_name()); return; }
if (!strcmp(me, "WindowServer")) return;
typedef int32_t (*RegFn)(uint32_t, CFDictionaryRef, void *);
RegFn reg = (RegFn)dlsym(RTLD_DEFAULT, "VTRegisterVideoEncoderWithInfo");
if (!reg) { nvlog("nvenc: VideoToolbox is not loaded in %s - not registering", me); return; }
Dl_info di;
if (!dladdr((const void *)nvmtl_nvenc_register, &di) || !di.dli_fname) { nvlog("nvenc: dladdr failed - not registering"); return; }
char dir[1024], path[1200];
strlcpy(dir, di.dli_fname, sizeof dir);
snprintf(path, sizeof path, "%s/%s", dirname(dir), lib);
void *h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!h) { nvlog("nvenc: dlopen %s FAILED: %s", path, dlerror()); return; }
void *fac = dlsym(h, "NVEncH264_CreateInstance");
if (!fac) { nvlog("nvenc: %s has no NVEncH264_CreateInstance", path); return; }
NSDictionary *info = @{ @"CMClassImplementationID": @"com.nvmtl.videoencoder.avc.nvenc",
@"CMClassImplementationName": @"NVIDIA NVENC H.264",
@"VTRating": @1000, @"VTIsHardwareAccelerated": @YES };
int32_t st = reg('avc1', (__bridge CFDictionaryRef)info, fac);
nvlog("nvenc: H.264 encoder %s in %s (VTRegisterVideoEncoderWithInfo -> %d, rating 1000, %s)",
st ? "NOT registered" : "REGISTERED", me, (int)st, path);
});
}
// An encoder built outside this driver can register itself beside ours and let VTRating decide which
// one an app gets, so both can be installed and compared. The one this was written for reports H.264
// at about 5 ms where the library we ship takes about 12, and it runs on Turing, Ampere and Ada,
// which nvmtl_nvenc_register above turns away for not being Blackwell.
// Off unless NVMTL_NVENCVT names this process (or is 1), from nvrm610.conf or the environment.
// This loads code into every app that encodes, so the library and the directory holding it must be
// ours and nobody else's. The firmware taught this: it used to sit in /Users/Shared, which is mode
// 1777, and the only permission step was a chmod that adds read bits and never takes write away, so
// a directory left there by any user was adopted as-is. A path anyone can write is not a path you can
// trust. lstat, not stat: a symlink must not be followed into something else.
static bool nvmtl_loadable_root_only(const char *path)
{
struct stat st;
if (lstat(path, &st) != 0 || !S_ISREG(st.st_mode)) return false;
if (st.st_uid != 0 || (st.st_mode & (S_IWGRP | S_IWOTH))) return false;
char dir[1024]; strlcpy(dir, path, sizeof dir);
char *d = dirname(dir);
struct stat ds; // a writable directory lets the file be swapped
if (!d || lstat(d, &ds) != 0 || !S_ISDIR(ds.st_mode)) return false;
return ds.st_uid == 0 && !(ds.st_mode & (S_IWGRP | S_IWOTH));
}
static void nvmtl_nvencvt_register(void)
{
static dispatch_once_t once;
dispatch_once(&once, ^{
const char *me = getprogname();
const char *sel = getenv("NVMTL_NVENCVT");
if (!sel || !*sel || !strcmp(sel, "0")) return;
if (strcmp(sel, "1")) { // a process list, so one app can be moved over at a time
char list[512]; strlcpy(list, sel, sizeof list);
bool named = false;
for (char *t = strtok(list, ", :"); t && !named; t = strtok(NULL, ", :")) named = !strcmp(t, me);
if (!named) return;
}
if (!strcmp(me, "WindowServer")) return; // the codec registrars all stay out of it
Dl_info di;
if (!dladdr((const void *)nvmtl_nvencvt_register, &di) || !di.dli_fname) { nvlog("nvencvt: dladdr failed - not registering"); return; }
char dir[1024], path[1200];
strlcpy(dir, di.dli_fname, sizeof dir);
snprintf(path, sizeof path, "%s/libnvencvt.dylib", dirname(dir));
if (!nvmtl_loadable_root_only(path)) {
nvlog("nvencvt: %s is absent, or is not a root-owned file inside a root-owned directory - REFUSED", path);
return;
}
void *h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!h) { nvlog("nvencvt: dlopen %s FAILED: %s", path, dlerror()); return; }
typedef int32_t (*RegFn)(int);
RegFn r = (RegFn)dlsym(h, "NVEncVT_Register");
if (!r) { nvlog("nvencvt: %s has no NVEncVT_Register", path); return; }
int rating = 1100; // above our own 1000, so the opt-in one wins where it is asked for
const char *rv = getenv("NVMTL_NVENCVT_RATING");
if (rv) { int v = atoi(rv); if (v > 0) rating = v; }
int32_t st = r(rating);
nvlog("nvencvt: external encoder %s in %s (NVEncVT_Register -> %d, rating %d, %s)",
st ? "NOT registered" : "REGISTERED", me, (int)st, rating, path);
});
}
static void nvmtl_nvdec_hevc_register(void)
{
static dispatch_once_t once;
dispatch_once(&once, ^{
const char *me = getprogname();
if (getenv("NVMTL_NO_NVDEC_HEVC")) { nvlog("nvdec: NVMTL_NO_NVDEC_HEVC set - not registering HEVC in %s", me); return; }
if (!strcmp(me, "WindowServer")) return;
typedef int32_t (*RegFn)(uint32_t, CFDictionaryRef, void *);
RegFn reg = (RegFn)dlsym(RTLD_DEFAULT, "VTRegisterVideoDecoderWithInfo");
if (!reg) { nvlog("nvdec: VideoToolbox is not loaded in %s - not registering HEVC", me); return; }
Dl_info di;
if (!dladdr((const void *)nvmtl_nvdec_hevc_register, &di) || !di.dli_fname) { nvlog("nvdec: dladdr failed - not registering HEVC"); return; }
char dir[1024], path[1200];
strlcpy(dir, di.dli_fname, sizeof dir);
snprintf(path, sizeof path, "%s/libnvdec_hevc.dylib", dirname(dir));
void *h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!h) { nvlog("nvdec: dlopen %s FAILED: %s", path, dlerror()); return; }
void *fac = dlsym(h, "NVDecHEVC_CreateInstance");
if (!fac) { nvlog("nvdec: %s has no NVDecHEVC_CreateInstance", path); return; }
NSDictionary *info = @{ @"CMClassImplementationID": @"com.nvmtl.videodecoder.hevc.nvdec",
@"VTRating": @1000, @"VTIsHardwareAccelerated": @YES };
int32_t st = reg('hvc1', (__bridge CFDictionaryRef)info, fac);
nvlog("nvdec: HEVC decoder %s in %s (VTRegisterVideoDecoderWithInfo -> %d, rating 1000, %s)",
st ? "NOT registered" : "REGISTERED", me, (int)st, path);
});
}
// GH #175: with Chrome's GPU sandbox on, decoding runs in VTDecoderXPCService. Metal maps this bundle there (the
// process holds the bundle's mappings but never creates a Metal device), but the decoders were registered only when a Metal
// device came up, so that process never had them and H.264 fell to AppleH264SW. The decoder libraries open NVRM
// themselves (IOKit; nothing from the Vulkan device), as NVIDIA's own decoder is a per-process capability needing no
// render device. So in that one process register them at load, telling Blackwell apart by the GPU's PCI device id
// instead of the Vulkan device name.
static void nvmtl_nvdec_hevc_register(void);
__attribute__((constructor)) static void nvmtl_nvdec_in_decode_service(void)
{
const char *me = getprogname();
if (!me || strcmp(me, "VTDecoderXPCService") || getenv("NVMTL_NO_NVDEC")) return;
// off the loader's thread: the registration dlopens the decoder library
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
uint32_t dev = 0;
io_iterator_t it = IO_OBJECT_NULL;
if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOPCIDevice"), &it) == KERN_SUCCESS) {
for (io_object_t o; !dev && (o = IOIteratorNext(it)); IOObjectRelease(o)) {
CFDataRef v = IORegistryEntryCreateCFProperty(o, CFSTR("vendor-id"), kCFAllocatorDefault, 0);
CFDataRef c = IORegistryEntryCreateCFProperty(o, CFSTR("class-code"), kCFAllocatorDefault, 0);
CFDataRef d = IORegistryEntryCreateCFProperty(o, CFSTR("device-id"), kCFAllocatorDefault, 0);
uint32_t vv = 0, cc = 0, dd = 0;
if (v && CFDataGetLength(v) >= 4) CFDataGetBytes(v, CFRangeMake(0, 4), (UInt8 *)&vv);
if (c && CFDataGetLength(c) >= 4) CFDataGetBytes(c, CFRangeMake(0, 4), (UInt8 *)&cc);
if (d && CFDataGetLength(d) >= 4) CFDataGetBytes(d, CFRangeMake(0, 4), (UInt8 *)&dd);
if ((vv & 0xffff) == 0x10de && (cc >> 16) == 0x03) dev = dd & 0xffff;
if (v) CFRelease(v); if (c) CFRelease(c); if (d) CFRelease(d);
}
IOObjectRelease(it);
}
if (!dev) { nvlog("nvdec: no NVIDIA GPU in the I/O registry - not registering in %s", me); return; }
char layout[32];
if (nvmtl_gpu_profile_string(CFSTR("video-layout"), layout, sizeof layout)) g_video_blackwell = !strcmp(layout, "blackwell");
else g_video_blackwell = dev >= 0x2b00 && dev < 0x3000; // no profile (older NVRM): the GB20x device-id block
nvlog("nvdec: decode service, GPU 10de:%04x (%s): registering the decoders at load", dev,
g_video_blackwell ? "Blackwell" : "before Blackwell");
nvmtl_nvdec_register();
nvmtl_nvdec_hevc_register();
});
}
static void nvmtl_nvenc_hevc_register(void)
{
static dispatch_once_t once;
dispatch_once(&once, ^{
const char *me = getprogname();
if (getenv("NVMTL_NO_NVENC_HEVC")) { nvlog("nvenc: NVMTL_NO_NVENC_HEVC set - not registering HEVC in %s", me); return; }
const char *lib = nvmtl_nvenc_hevc_library_for_this_gpu();
if (!lib) { nvlog("nvenc: no HEVC encoder library for %s - HEVC encode stays on Apple's encoder", nvmtl_vk_device_name()); return; }
if (!strcmp(me, "WindowServer")) return;
typedef int32_t (*RegFn)(uint32_t, CFDictionaryRef, void *);
RegFn reg = (RegFn)dlsym(RTLD_DEFAULT, "VTRegisterVideoEncoderWithInfo");
if (!reg) { nvlog("nvenc: VideoToolbox is not loaded in %s - not registering HEVC", me); return; }
Dl_info di;
if (!dladdr((const void *)nvmtl_nvenc_hevc_register, &di) || !di.dli_fname) { nvlog("nvenc: dladdr failed - not registering HEVC"); return; }
char dir[1024], path[1200];
strlcpy(dir, di.dli_fname, sizeof dir);
snprintf(path, sizeof path, "%s/%s", dirname(dir), lib);
void *h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!h) { nvlog("nvenc: dlopen %s FAILED: %s", path, dlerror()); return; }
void *fac = dlsym(h, "NVEncHEVC_CreateInstance");
if (!fac) { nvlog("nvenc: %s has no NVEncHEVC_CreateInstance", path); return; }
NSDictionary *info = @{ @"CMClassImplementationID": @"com.nvmtl.videoencoder.hevc.nvenc",
@"CMClassImplementationName": @"NVIDIA NVENC HEVC",
@"VTRating": @1000, @"VTIsHardwareAccelerated": @YES };
int32_t st = reg('hvc1', (__bridge CFDictionaryRef)info, fac);
nvlog("nvenc: HEVC encoder %s in %s (VTRegisterVideoEncoderWithInfo -> %d, rating 1000, %s)",
st ? "NOT registered" : "REGISTERED", me, (int)st, path);
});
}
// ANGLE refuses Metal on NVIDIA (disableMetalOnNvidia), and Chromium on macOS has no other GL backend, so without this
// the GPU process exits at start-up and the app draws everything on the CPU. Chrome and Chromium get it by default:
// without it their GPU process cannot start. Electron stays opt-in (NVMTL_ANGLE_METAL=1) because it showed artifacts,
// stutter and lost transparency on several cards. NVMTL_ANGLE_METAL=0 turns the rule off in every process. An existing
// ANGLE override is kept; no sandbox setting is changed.
static bool nvmtl_angle_chrome_family(void)
{
const char *me = getprogname();
if (!me) return false;
return strncmp(me, "Google Chrome", 13) == 0 || strncmp(me, "Chromium", 8) == 0;
}
__attribute__((constructor)) static void nvmtl_angle_allow_nvidia(void)
{
const char *opt = getenv("NVMTL_ANGLE_METAL");
if (opt && !strcmp(opt, "0")) return;
const char *me = getprogname();
if (!(opt && !strcmp(opt, "1")) && !nvmtl_angle_chrome_family()) return;
const char *key = "ANGLE_FEATURE_OVERRIDES_DISABLED", *rule = "disableMetalOnNvidia";
const char *cur = getenv(key);
if (cur && strstr(cur, rule)) return;
// One line per process, outside nvlog's release failure filter: a field report must show whether the rule was
// active in this process.
syslog(LOG_NOTICE, "NullMoth: angle: Metal allowed in %s (%s; NVMTL_ANGLE_METAL=0 disables)", me ? me : "?",
(opt && !strcmp(opt, "1")) ? "NVMTL_ANGLE_METAL=1" : "Chrome family");
char v[1024];
if (cur && *cur) snprintf(v, sizeof v, "%s:%s", cur, rule); else snprintf(v, sizeof v, "%s", rule);
setenv(key, v, 1);
}
static bool nvmtl_process_is_allowed(void)
{
const char *me = getprogname();
if (!me) return false;
// A headless NVIDIA GPU (the display is on the Intel or AMD GPU) is a Metal device for apps only: WindowServer stays
// on the GPU that owns the display, as on Apple's two-GPU Macs. The list below cannot express this: "*" matches
// WindowServer before its "!WindowServer" line is reached.
{ int hv = 0; size_t hn = sizeof hv;
// PhxAccel: an AMD accelerator that drives its own panel (debug.nmxaccel_headless reads 0) composites WindowServer
int ahv = 1; size_t ahn = sizeof ahv;
const bool amdPanel = nvmtl_vk_vendor() == 0x1002 && sysctlbyname("debug.nmxaccel_headless", &ahv, &ahn, NULL, 0) == 0 && !ahv;
if (!strcmp(me, "WindowServer") && !amdPanel && (nvmtl_vk_vendor() != 0x10de ||
(sysctlbyname("debug.nvaccel_headless", &hv, &hn, NULL, 0) == 0 && hv))) {
nvlog(" headless GPU: no device for WindowServer (it composites on the GPU that owns the display)"); return false; } }
if (getenv("NVMTL_ENABLE")) return true;
if (!strcmp(me, "mtlprobe") || !strcmp(me, "nvmtltest") || !strcmp(me, "nvmtlrender")) return true;
FILE *f = fopen("/Library/GPUBundles/nvmtl-allow.txt", "r");
if (!f) f = fopen("/Library/Extensions/nvmtl-allow.txt", "r");
if (!f) { nvlog(" no allow-list readable from this process: no device for %s (cannot read nvmtl-allow.txt)", me); return false; }
char line[256]; bool ok = false;
while (fgets(line, sizeof line, f)) {
char *nl = strpbrk(line, "\r\n"); if (nl) *nl = 0;
char *p = line; while (*p == ' ' || *p == '\t') p++;
if (!*p || *p == '#') continue;
if (*p == '-') { p++; while (*p == ' ' || *p == '\t') p++; if (!strcmp(p, me)) { nvlog(" denied by list: no device for %s", me); fclose(f); return false; } continue; }
bool armedOnly = false;
if (*p == '!') { armedOnly = true; p++; while (*p == ' ' || *p == '\t') p++; }
if (strcmp(p, "*") && strcmp(p, me)) continue;
if (armedOnly && !nvmtl_accel_armed()) {
nvlog(" '%s' is armed-only and debug.nvaccelfb reads 0 -- no device (arm it with sysctl -w debug.nvaccelfb=1)", me);
break;
}
ok = true; break;
}
fclose(f);
if (ok) nvlog(" allow-listed: %s", me);
return ok;
}
@implementation NVMTLDevice
+ (void)load {
char me[1200], ts[40] = "?"; time_t now = time(NULL); struct tm tm;
if (localtime_r(&now, &tm)) strftime(ts, sizeof ts, "%Y-%m-%dT%H:%M:%S%z", &tm);
nvlog("NVMTLDevice +load in pid %d (static class, image-owned) image %s at %s", getpid(),
nvmtl_image_ident((const void *)nvmtl_image_ident, me, sizeof me), ts);
}
static void nvmtl_fill_pool_args(uint8_t *a, int second)
{
memset(a, 0, 2440);
a[0x005] = 0x04; a[0x008] = 0x01; a[0x00a] = 0x01; a[0x00c] = 0x01; a[0x01a] = 0x01;
a[0x020] = 0x01; a[0x021] = 0x01; a[0x023] = 0x01; a[0x024] = 0x40; a[0x05a] = 0x01;
a[0x105] = 0x10;
if (second) { a[0x000] = 0x40; a[0x012] = 0x01; a[0x052] = 0x01; a[0x06a] = 0x04; }
}
static void nvmtl_install_hw_resource_pools(id dev)
{
if (!getenv("NVMTL_HWPOOL")) { nvlog(" hw resource pools: NVMTL_HWPOOL unset, leaving slot 2 NULL"); return; }
Class POOL = objc_getClass("MTLIOAccelResourcePool");
Class RES = objc_getClass("MTLIOAccelPooledResource");
if (!POOL || !RES) { nvlog(" hw resource pools: MTLIOAccelResourcePool/PooledResource missing"); return; }
SEL init = NSSelectorFromString(@"initWithDevice:resourceClass:resourceArgs:resourceArgsSize:options:");
id (*mk)(id, SEL, id, Class, const void *, unsigned long, unsigned long) = (void *)objc_msgSend;
static uint8_t args[3][2440];
__unsafe_unretained id pools[3] = {0};
for (int i = 0; i < 3; i++) {
nvmtl_fill_pool_args(args[i], i == 1);
pools[i] = mk([POOL alloc], init, dev, RES, args[i], 2440, 0);
nvlog(" pool %d -> %p", i, (__bridge void *)pools[i]);
if (!pools[i]) { nvlog(" hw resource pools: pool %d came back nil, NOT installing", i); return; }
}
void (*set)(id, SEL, __unsafe_unretained id *, int) = (void *)objc_msgSend;
set(dev, NSSelectorFromString(@"setHwResourcePool:count:"), pools, 3);
nvlog(" hw resource pools: installed 3 (slot 2 + count)");
}
- (instancetype)initWithAcceleratorPort:(mach_port_t)port {
nvlog("-[NVMTLDevice initWithAcceleratorPort:%u] in %s", port, getprogname());
self = [super initWithAcceleratorPort:port];
if (!self) { nvlog(" super initWithAcceleratorPort: returned nil"); return nil; }
{ /* one GPU per process: the plugin runs a single Vulkan device, so a second Metal device on another vendor's
accelerator (a PC with an NVIDIA card and an AMD or Intel GPU) is refused rather than given the wrong GPU */
uint16_t mine = nvmtl_vk_set_accelerator(port), live = nvmtl_vk_vendor();
if (!mine || mine != live) { nvlog(" accelerator vendor %04x, but this process runs Metal on %04x: no second device", mine, live); return nil; }
nvlog(" GPU vendor %04x (%s)", live, live == 0x1002 ? "AMD, RADV" : live == 0x8086 ? "Intel, ANV" : "NVIDIA, NVK");
}
if (!nvmtl_process_is_allowed()) { nvlog(" not allow-listed: no device for %s", getprogname()); return nil; }
nvlog("MTLIOAccelDevice's initWithAcceleratorPort: -> %p", (__bridge void *)self);
gNVMTLMainDevice = self;
nvmtl_install_hw_resource_pools(self);
[self nvmtlProbeGPUPass];
if (nvmtl_vk_init()) {
nvlog(" NVK did not come up in this process - refusing to be the Metal device for %s", getprogname());
return nil;
}
nvmtl_gl_caps_enable();
if (nvmtl_vk_vendor() == 0x10de) { /* NVDEC/NVENC are NVIDIA engines reached through NVRM */
nvmtl_nvdec_register();
nvmtl_nvenc_register();
nvmtl_nvdec_hevc_register();
nvmtl_nvenc_hevc_register();
nvmtl_nvencvt_register(); // last, so an opt-in external encoder registers above ours
}
SEL il = sel_registerName("initLimits");
if ([self respondsToSelector:il]) {
((void (*)(id, SEL))objc_msgSend)(self, il);
#define NVMTL_U(n) ((unsigned long)((NSUInteger (*)(id, SEL))objc_msgSend)(self, sel_registerName(n)))
nvlog("limits: -initLimits (featureProfile %lu) -> maxTextureWidth2D %lu, maxComputeTextures %lu, maxComputeBuffers %lu",
NVMTL_U("featureProfile"), NVMTL_U("maxTextureWidth2D"), NVMTL_U("maxComputeTextures"), NVMTL_U("maxComputeBuffers"));
#undef NVMTL_U
} else nvlog("limits: -initLimits not found - every table-served limit stays 0 (CoreImage will refuse renders)");
return self;
}
- (void)nvmtlProbeGPUPass {
if (access("/Library/GPUBundles/nvmtl-gpupass-probe", F_OK) != 0) return;
static int done = 0; if (done) return; done = 1;
if (nvmtl_vk_init()) { nvlog("gpupass probe: Vulkan is down in this process — cannot answer"); return; }
NSString *p = @"/System/Library/Frameworks/CoreDisplay.framework/Versions/A/Resources/default.metallib";
NSData *d = [NSData dataWithContentsOfFile:p];
if (!d) { nvlog("gpupass probe: cannot read CoreDisplay's metallib"); return; }
NSDictionary<NSString *, NSData *> *fns = nvmtl_translate_metallib(d, NULL, NULL);
nvlog("gpupass probe: %lu functions translated from CoreDisplay's metallib", (unsigned long)fns.count);
NSData *v = fns[@"ViewportToNDC"];
if (!v) { nvlog("gpupass probe: NO ViewportToNDC — the vertex half is missing"); return; }
for (NSString *fname in @[@"GPUPass", @"ColorFill", @"TextureCopy"]) {
NSData *f = fns[fname];
if (!f) { nvlog("gpupass probe: no %s in the translated set", fname.UTF8String); continue; }
nvk_pipeline pipe; memset(&pipe, 0, sizeof pipe);
int rc = nvmtl_vk_pipeline_create_depth(v.bytes, v.length, f.bytes, f.length, 1, 0, &pipe);
nvlog("gpupass probe: ViewportToNDC + %s -> %s (%lu + %lu bytes of SPIR-V)",
fname.UTF8String, rc ? "*** vkCreateGraphicsPipelines FAILED ***" : "*** PIPELINE BUILT ***",
(unsigned long)v.length, (unsigned long)f.length);
}
}
- (NSString *)vendorName {
static NSMutableSet *seen; static dispatch_once_t once; dispatch_once(&once, ^{ seen = [NSMutableSet new]; });
Dl_info i = {0}; const char *who = dladdr(__builtin_return_address(0), &i) && i.dli_fname ? i.dli_fname : "?";
NSString *v = nvmtl_vk_vendor() == 0x1002 ? @"AMD" : nvmtl_vk_vendor() == 0x8086 ? @"Intel" : @"NVIDIA";
@synchronized(seen) { NSString *k = @(who); if (![seen containsObject:k]) { [seen addObject:k]; nvlog("vendorName -> %s (asked by %s)", v.UTF8String, who); } }
return v;
}
- (NSString *)name {
static int vk = 0; if (!vk) { vk = 1; nvmtl_vk_init(); }
const char *vkname = nvmtl_vk_device_name();
NSString *full = [NSString stringWithUTF8String:(vkname ? vkname : "NVIDIA GPU")];
NSRange cut = [full rangeOfString:@" (NVK "];
NSString *marketing = (cut.location != NSNotFound) ? [full substringToIndex:cut.location] : full;
return [NSString stringWithFormat:@"%@ (NVMTL over %@)", marketing, full];
}
- (id<MTLCommandQueue>)newCommandQueue { return [self newCommandQueueWithMaxCommandBufferCount:64]; }
- (id<MTLCommandQueue>)newCommandQueueWithMaxCommandBufferCount:(NSUInteger)n {
if (nvmtl_vk_init()) { nvlog("newCommandQueue: Vulkan/NVK is down — no queue"); return nil; }
NVMTLCommandQueue *q = [NVMTLCommandQueue new];
q->_capacityCount = n ? n : 64;
q->_dev = self;
if (nvmtl_vk_queue_create(&q->_q)) { nvlog("newCommandQueue: command pool FAILED"); return nil; }
nvlog("newCommandQueue -> %p (NVK command pool)", (__bridge void *)q); return q; }
static void nvmtl_zero_new_buffer(NVMTLBuffer *b, NSUInteger len);
static __thread int gZeroSkip;
- (id<MTLBuffer>)newBufferWithLength:(NSUInteger)len options:(MTLResourceOptions)opt {
if (nvmtl_vk_init()) return nil;
if (nvmtl_alloc_blocked()) return nil;
NVMTLBuffer *b = [NVMTLBuffer new];
b->_storage = (MTLStorageMode)((opt >> MTLResourceStorageModeShift) & 0xF);
b->_ropt = opt & ((MTLResourceOptions)0xF | ((MTLResourceOptions)0x3 << MTLResourceHazardTrackingModeShift));
int hv = (b->_storage == MTLStorageModeShared) || (b->_storage == MTLStorageModeManaged && getenv("NVMTL_MANAGED_SYSMEM"));
if (nvmtl_vk_buffer_create(len, (hv && b->_storage == MTLStorageModeShared) ? 2 : hv, &b->_b)) {
if (hv) { nvmtl_alloc_failed("newBufferWithLength"); nvlog("newBufferWithLength: FAILED"); return nil; }
nvlog("newBufferWithLength:%lu private: VRAM refused - placing it in system memory", (unsigned long)len);
if (nvmtl_vk_buffer_create(len, 1, &b->_b)) { nvmtl_alloc_failed("newBufferWithLength"); nvlog("newBufferWithLength: FAILED"); return nil; }
}
nvmtl_alloc_ok();
if (b->_storage == MTLStorageModeManaged && !b->_b.map && nvmtl_vk_buffer_create(len, 1, &b->_shadow)) {
nvlog("newBufferWithLength:%lu managed: shadow refused - placing it in system memory", (unsigned long)len);
memset(&b->_shadow, 0, sizeof b->_shadow); nvmtl_vk_buffer_destroy(&b->_b);
if (nvmtl_vk_buffer_create(len, 1, &b->_b)) { nvmtl_alloc_failed("newBufferWithLength"); return nil; }
}
if (!gZeroSkip) nvmtl_zero_new_buffer(b, len);
nvlog("newBufferWithLength:%lu storage %d -> %p%s", (unsigned long)len, (int)b->_storage, (__bridge void *)b, b->_b.map ? "" : " VRAM"); return b; }
- (id<MTLBuffer>)newBufferWithBytes:(const void *)bytes length:(NSUInteger)len options:(MTLResourceOptions)opt {
int priv = (((opt >> MTLResourceStorageModeShift) & 0xF) == MTLStorageModePrivate);
MTLResourceOptions o2 = priv ? ((opt & ~(MTLResourceOptions)(0xF << MTLResourceStorageModeShift)) | MTLResourceStorageModeShared) : opt;
gZeroSkip = bytes != NULL;
id<MTLBuffer> b = [self newBufferWithLength:len options:o2];
gZeroSkip = 0;
if (b && b.contents && bytes) memcpy(b.contents, bytes, len);
if (b && priv) ((NVMTLBuffer *)b)->_storage = MTLStorageModePrivate;
if (b && bytes && ((NVMTLBuffer *)b)->_shadow.map) [b didModifyRange:NSMakeRange(0, len)];
return b; }
static int nvmtl_depthfmt(MTLPixelFormat f, uint32_t *vk, uint32_t *aspect)
{
switch (f) {
case MTLPixelFormatDepth16Unorm: *vk = VK_FORMAT_D16_UNORM; *aspect = VK_IMAGE_ASPECT_DEPTH_BIT; return 0;
case MTLPixelFormatDepth32Float: *vk = VK_FORMAT_D32_SFLOAT; *aspect = VK_IMAGE_ASPECT_DEPTH_BIT; return 0;
case MTLPixelFormatStencil8: *vk = VK_FORMAT_S8_UINT; *aspect = VK_IMAGE_ASPECT_STENCIL_BIT; return 0;
case MTLPixelFormatDepth24Unorm_Stencil8: *vk = VK_FORMAT_D24_UNORM_S8_UINT; *aspect = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; return 0;
case MTLPixelFormatDepth32Float_Stencil8: *vk = VK_FORMAT_D32_SFLOAT_S8_UINT; *aspect = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; return 0;
case MTLPixelFormatX32_Stencil8: *vk = VK_FORMAT_D32_SFLOAT_S8_UINT; *aspect = VK_IMAGE_ASPECT_STENCIL_BIT; return 0;
case MTLPixelFormatX24_Stencil8: *vk = VK_FORMAT_D24_UNORM_S8_UINT; *aspect = VK_IMAGE_ASPECT_STENCIL_BIT; return 0;
default: return -1;
}
}
static int nvmtl_pixfmt(MTLPixelFormat f, uint32_t *vk, uint32_t *bpp, int *a8)
{
*a8 = 0;
switch (f) {
case MTLPixelFormatA8Unorm: *vk = 9 ; *bpp = 1; *a8 = 1; return 0;
case MTLPixelFormatR8Unorm: *vk = 9 ; *bpp = 1; return 0;
case MTLPixelFormatR8Unorm_sRGB: *vk = 15 ; *bpp = 1; return 0;
case MTLPixelFormatR8Snorm: *vk = 10 ; *bpp = 1; return 0;
case MTLPixelFormatR8Uint: *vk = 13 ; *bpp = 1; return 0;
case MTLPixelFormatR8Sint: *vk = 14 ; *bpp = 1; return 0;
case MTLPixelFormatR16Unorm: *vk = 70 ; *bpp = 2; return 0;
case MTLPixelFormatR16Snorm: *vk = 71 ; *bpp = 2; return 0;
case MTLPixelFormatR16Uint: *vk = 74 ; *bpp = 2; return 0;
case MTLPixelFormatR16Sint: *vk = 75 ; *bpp = 2; return 0;
case MTLPixelFormatR16Float: *vk = 76 ; *bpp = 2; return 0;
case MTLPixelFormatRG8Unorm: *vk = 16 ; *bpp = 2; return 0;
case MTLPixelFormatRG8Unorm_sRGB: *vk = 16 ; *bpp = 2; return 0;
case MTLPixelFormatRG8Snorm: *vk = 17 ; *bpp = 2; return 0;
case MTLPixelFormatRG8Uint: *vk = 20 ; *bpp = 2; return 0;
case MTLPixelFormatRG8Sint: *vk = 21 ; *bpp = 2; return 0;
case MTLPixelFormatR32Uint: *vk = 98 ; *bpp = 4; return 0;
case MTLPixelFormatR32Sint: *vk = 99 ; *bpp = 4; return 0;
case MTLPixelFormatR32Float: *vk = 100 ; *bpp = 4; return 0;
case MTLPixelFormatRG16Unorm: *vk = 77 ; *bpp = 4; return 0;
case MTLPixelFormatRG16Snorm: *vk = 78 ; *bpp = 4; return 0;
case MTLPixelFormatRG16Uint: *vk = 81 ; *bpp = 4; return 0;
case MTLPixelFormatRG16Sint: *vk = 82 ; *bpp = 4; return 0;
case MTLPixelFormatRG16Float: *vk = 83 ; *bpp = 4; return 0;
case MTLPixelFormatRGBA8Unorm: *vk = 37 ; *bpp = 4; return 0;
case MTLPixelFormatRGBA8Unorm_sRGB: *vk = 43 ; *bpp = 4; return 0;
case MTLPixelFormatRGBA8Snorm: *vk = 38 ; *bpp = 4; return 0;
case MTLPixelFormatRGBA8Uint: *vk = 41 ; *bpp = 4; return 0;
case MTLPixelFormatRGBA8Sint: *vk = 42 ; *bpp = 4; return 0;
case MTLPixelFormatBGRA8Unorm: *vk = 44 ; *bpp = 4; return 0;
case MTLPixelFormatBGRA8Unorm_sRGB: *vk = 50 ; *bpp = 4; return 0;
case MTLPixelFormatRGB10A2Unorm: *vk = 64 ; *bpp = 4; return 0;
case MTLPixelFormatRGB10A2Uint: *vk = 68 ; *bpp = 4; return 0;
case MTLPixelFormatBGR10A2Unorm: *vk = 58 ; *bpp = 4; return 0;
case MTLPixelFormatRG11B10Float: *vk = 122 ; *bpp = 4; return 0;
case MTLPixelFormatRGB9E5Float: *vk = 123 ; *bpp = 4; return 0;
case MTLPixelFormatRG32Uint: *vk = 101 ; *bpp = 8; return 0;
case MTLPixelFormatRG32Sint: *vk = 102 ; *bpp = 8; return 0;
case MTLPixelFormatRG32Float: *vk = 103 ; *bpp = 8; return 0;
case MTLPixelFormatRGBA16Unorm: *vk = 91 ; *bpp = 8; return 0;
case MTLPixelFormatRGBA16Snorm: *vk = 92 ; *bpp = 8; return 0;
case MTLPixelFormatRGBA16Uint: *vk = 95 ; *bpp = 8; return 0;
case MTLPixelFormatRGBA16Sint: *vk = 96 ; *bpp = 8; return 0;
case MTLPixelFormatRGBA16Float: *vk = 97 ; *bpp = 8; return 0;
case MTLPixelFormatRGBA32Uint: *vk = 107 ; *bpp = 16; return 0;
case MTLPixelFormatRGBA32Sint: *vk = 108 ; *bpp = 16; return 0;
case MTLPixelFormatRGBA32Float: *vk = 109 ; *bpp = 16; return 0;
case MTLPixelFormatBC1_RGBA: *vk = 133 ; *bpp = 8; return 0;
case MTLPixelFormatBC1_RGBA_sRGB: *vk = 134 ; *bpp = 8; return 0;
case MTLPixelFormatBC2_RGBA: *vk = 135 ; *bpp = 16; return 0;
case MTLPixelFormatBC2_RGBA_sRGB: *vk = 136 ; *bpp = 16; return 0;
case MTLPixelFormatBC3_RGBA: *vk = 137 ; *bpp = 16; return 0;
case MTLPixelFormatBC3_RGBA_sRGB: *vk = 138 ; *bpp = 16; return 0;
case MTLPixelFormatBC4_RUnorm: *vk = 139 ; *bpp = 8; return 0;
case MTLPixelFormatBC4_RSnorm: *vk = 140 ; *bpp = 8; return 0;
case MTLPixelFormatBC5_RGUnorm: *vk = 141 ; *bpp = 16; return 0;
case MTLPixelFormatBC5_RGSnorm: *vk = 142 ; *bpp = 16; return 0;
case MTLPixelFormatBC6H_RGBUfloat: *vk = 143 ; *bpp = 16; return 0;
case MTLPixelFormatBC6H_RGBFloat: *vk = 144 ; *bpp = 16; return 0;
case MTLPixelFormatBC7_RGBAUnorm: *vk = 145 ; *bpp = 16; return 0;
case MTLPixelFormatBC7_RGBAUnorm_sRGB: *vk = 146 ; *bpp = 16; return 0;
case MTLPixelFormatInvalid: *vk = 37 ; *bpp = 4; return 0;
default: break;
}
static MTLPixelFormat seen[32]; static int nseen;
int dup = 0; for (int i = 0; i < nseen; i++) if (seen[i] == f) dup = 1;
if (!dup) { if (nseen < 32) seen[nseen++] = f; nvlog("pixel format %lu is NOT carried by this driver yet (compressed / depth-stencil / packed YUV) — nil", (unsigned long)f); }
return -1;
}
int nvmtl_pixfmt_public(MTLPixelFormat f, uint32_t *vk, uint32_t *bpp, int *a8) { return nvmtl_pixfmt(f, vk, bpp, a8); }
int nvmtl_depthfmt_public(MTLPixelFormat f, uint32_t *vk, uint32_t *aspect) { return nvmtl_depthfmt(f, vk, aspect); }
static NSString *nvmtl_varying_key(id v) {
if (![v isKindOfClass:[NSDictionary class]]) return nil;
id s = ((NSDictionary *)v)[@"user_semantic"]; if ([s isKindOfClass:[NSString class]]) return s;
id n = ((NSDictionary *)v)[@"name"]; return [n isKindOfClass:[NSString class]] ? n : nil;
}
static int nvmtl_varying_one_location(id v) {
id t = [v isKindOfClass:[NSDictionary class]] ? ((NSDictionary *)v)[@"type_name"] : nil;
return ![t isKindOfClass:[NSString class]] || ([(NSString *)t rangeOfString:@"x"].location == NSNotFound && [(NSString *)t rangeOfString:@"["].location == NSNotFound);
}
static NSData *nvmtl_varying_link(NVMTLFunction *vf, NVMTLFunction *ff) {
NSDictionary *vr = nvmtl_function_reflection(vf), *fr = nvmtl_function_reflection(ff);
NSArray *vv = [vr isKindOfClass:[NSDictionary class]] ? vr[@"varyings"] : nil, *fv = [fr isKindOfClass:[NSDictionary class]] ? fr[@"varyings"] : nil;
if (![fv isKindOfClass:[NSArray class]] || !fv.count) return nil;
if (![vv isKindOfClass:[NSArray class]]) { static int said; if (!said++) nvlog("varylink: %s has no reflected varyings - %s keeps its own Locations", vf->_fname.UTF8String ?: "?", ff->_fname.UTF8String ?: "?"); return nil; }
enum { NL = 128 };
uint8_t used[NL] = { 0 }, have[NL] = { 0 }; uint32_t remap[NL]; for (uint32_t i = 0; i < NL; i++) remap[i] = i;
NSMutableDictionary<NSString *, NSNumber *> *out = [NSMutableDictionary new];
for (id v in vv) {
NSNumber *l = [v isKindOfClass:[NSDictionary class]] ? ((NSDictionary *)v)[@"location"] : nil;
if (![l isKindOfClass:[NSNumber class]] || l.unsignedIntValue >= NL || !nvmtl_varying_one_location(v)) { static int said; if (!said++) nvlog("varylink: a vertex varying of %s is not one Location in 0..127 - pipeline keeps its Locations", vf->_fname.UTF8String ?: "?"); return nil; }
used[l.unsignedIntValue] = 1; NSString *k = nvmtl_varying_key(v); if (k) out[k] = l;
}
uint32_t next = 0; int change = 0, unmatched = 0;
for (id f in fv) {
NSNumber *l = [f isKindOfClass:[NSDictionary class]] ? ((NSDictionary *)f)[@"location"] : nil;
if (![l isKindOfClass:[NSNumber class]] || l.unsignedIntValue >= NL || !nvmtl_varying_one_location(f)) { static int said; if (!said++) nvlog("varylink: a fragment varying of %s is not one Location in 0..127 - pipeline keeps its Locations", ff->_fname.UTF8String ?: "?"); return nil; }
uint32_t L = l.unsignedIntValue, T; NSString *k = nvmtl_varying_key(f); NSNumber *to = k ? out[k] : nil;
if (to) T = to.unsignedIntValue;
else { while (next < NL && used[next]) next++; if (next >= NL) return nil; T = next; used[next] = 1; unmatched++; }
if (have[L]) return nil;
have[L] = 1; remap[L] = T; if (T != L) change = 1;
}
if (!change) return nil;
const uint32_t *w = (const uint32_t *)ff->_spirv.bytes; size_t n = ff->_spirv.length / 4;
if (n < 5 || w[0] != 0x07230203u) return nil;
NSMutableData *md = [ff->_spirv mutableCopy]; uint32_t *m = (uint32_t *)md.mutableBytes;
NSMutableIndexSet *inputs = [NSMutableIndexSet indexSet]; int memberLoc = 0;
for (size_t i = 5; i < n; ) { uint32_t op = m[i] & 0xffffu, wc = m[i] >> 16; if (!wc || i + wc > n) return nil;
if (op == 59 && wc >= 4 && m[i + 3] == 1 ) [inputs addIndex:m[i + 2]];
if (op == 72 && wc >= 5 && m[i + 3] == 30 ) memberLoc = 1;
i += wc; }
if (memberLoc) { static int said; if (!said++) nvlog("varylink: %s decorates Locations on block members - not linked (said once)", ff->_fname.UTF8String ?: "?"); return nil; }
int moved = 0;
for (size_t i = 5; i < n; ) { uint32_t op = m[i] & 0xffffu, wc = m[i] >> 16;
if (op == 71 && wc >= 4 && m[i + 2] == 30 && [inputs containsIndex:m[i + 1]]) {
uint32_t L = m[i + 3];
if (L >= NL || !have[L]) { static int said; if (!said++) nvlog("varylink: %s reads Input Location %u that its reflection does not name - not linked", ff->_fname.UTF8String ?: "?", L); return nil; }
if (remap[L] != L) { m[i + 3] = remap[L]; moved++; } }
i += wc; }
static unsigned told; if (told++ < 8 || told % 4096 == 0)
nvlog("varylink: %s -> %s: %d fragment input(s) moved onto the vertex output of the same name, %d written by no vertex output (#%u)",
vf->_fname.UTF8String ?: "?", ff->_fname.UTF8String ?: "?", moved, unmatched, told);
return md;
}
static BOOL nvmtl_desc_fbo(MTLTextureDescriptor *d) {
SEL s = sel_registerName("framebufferOnly");
return d && [d respondsToSelector:s] && ((BOOL (*)(id, SEL))objc_msgSend)(d, s);
}
// CoreImage uses this CAMetalLayer descriptor flag to orient drawable output.
static BOOL nvmtl_desc_drawable(MTLTextureDescriptor *d) {
SEL s = sel_registerName("isDrawable");
return d && [d respondsToSelector:s] && ((BOOL (*)(id, SEL))objc_msgSend)(d, s);
}
- (id<MTLTexture>)newTextureWithDescriptor:(MTLTextureDescriptor *)d {
if (nvmtl_vk_init()) return nil;
if (d.textureType == MTLTextureTypeTextureBuffer) {
extern int nvmtl_pixfmt_public(MTLPixelFormat f, uint32_t *vk, uint32_t *bpp, int *a8);
uint32_t vkf = 0, bpp = 0; int a8 = 0;
if (!nvmtl_vk_texel_on() || !d.width || nvmtl_pixfmt_public(d.pixelFormat, &vkf, &bpp, &a8) || !bpp) {
nvlog("newTextureWithDescriptor: texture buffer %lu x fmt %lu not carried -> nil", (unsigned long)d.width, (unsigned long)d.pixelFormat); return nil; }
id<MTLBuffer> b = [self newBufferWithLength:(NSUInteger)d.width * bpp options:d.resourceOptions];
return b ? [b newTextureWithDescriptor:d offset:0 bytesPerRow:(NSUInteger)d.width * bpp] : nil;
}
if (nvmtl_alloc_blocked()) return nil;
NVMTLTexture *t = [NVMTLTexture new];
t->_ropt = (MTLResourceOptions)d.cpuCacheMode | ((MTLResourceOptions)d.hazardTrackingMode << MTLResourceHazardTrackingModeShift)
| ((MTLResourceOptions)d.storageMode << MTLResourceStorageModeShift);
t->_fbo = nvmtl_desc_fbo(d);
t->_drawable = nvmtl_desc_drawable(d);
t->_fmt = d.pixelFormat;
uint32_t dvk = 0, dasp = 0;
if (nvmtl_depthfmt(d.pixelFormat, &dvk, &dasp) == 0) {
t->_q = nvmtl_device_queue();
const uint32_t dtt = (uint32_t)d.textureType, dms = (d.textureType == MTLTextureType2DMultisample || dtt == 8) ? (uint32_t)d.sampleCount : 1u;
if (nvmtl_vk_depth_create_full((uint32_t)d.width, (uint32_t)d.height, dvk, dasp, dms, dtt,
nvmtl_vk_layers_for_desc(dtt, (uint32_t)d.arrayLength, 1u), (uint32_t)(d.mipmapLevelCount ? d.mipmapLevelCount : 1), &t->_i)) { nvlog("depth texture FAILED (format %lu)", (unsigned long)d.pixelFormat); return nil; }
t->_usage = d.usage;
nvlog("newTextureWithDescriptor: %lux%lu DEPTH32F type %lu layers %u mips %u -> %p", (unsigned long)d.width, (unsigned long)d.height, (unsigned long)d.textureType, t->_i.layers, t->_i.mips, (__bridge void *)t);
return t;
}
uint32_t vkf = 0, bpp = 0; int a8 = 0;
if (nvmtl_pixfmt(d.pixelFormat, &vkf, &bpp, &a8)) return nil;
int wantStex = (d.usage & MTLTextureUsageShaderWrite) != 0;
if (d.textureType == MTLTextureType2DMultisample || d.textureType == MTLTextureType2DMultisampleArray) {
if (d.mipmapLevelCount != 1 || d.depth != 1) { nvlog("newTextureWithDescriptor: invalid multisample color descriptor"); return nil; }
if (wantStex) { static _Atomic unsigned long msw; const unsigned long k = atomic_fetch_add(&msw, 1) + 1;
if (!(k & (k - 1))) nvlog("newTextureWithDescriptor: %lu multisample texture(s) asked for ShaderWrite - created like Apple (M1/D300 create them); no storage view", k); }
if (nvmtl_vk_image_create_ms_full((uint32_t)d.width, (uint32_t)d.height, vkf, bpp, (uint32_t)d.sampleCount, (uint32_t)d.textureType, (uint32_t)d.arrayLength, &t->_i)) { nvmtl_alloc_failed("newTextureWithDescriptor"); nvlog("newTextureWithDescriptor: FAILED (multisample)"); return nil; }
} else
if (nvmtl_vk_image_create_typed((uint32_t)d.width, (uint32_t)d.height, vkf, bpp, a8, (uint32_t)d.mipmapLevelCount, wantStex, (uint32_t)d.textureType, nvmtl_vk_layers_for_desc((uint32_t)d.textureType, (uint32_t)d.arrayLength, (uint32_t)d.depth), &t->_i)) { nvmtl_alloc_failed("newTextureWithDescriptor"); nvlog("newTextureWithDescriptor: FAILED"); return nil; }
nvmtl_alloc_ok();
t->_q = nvmtl_device_queue();
t->_stex = t->_i.storage != 0;
t->_usage = d.usage;
if (wantStex && !t->_stex) { static unsigned long lost; lost++;
if (!(lost & (lost - 1))) nvlog("newTextureWithDescriptor: pixel format %lu asked for ShaderWrite and NVK cannot make it a storage image — shader writes to it will be LOST (%lu texture(s) so far in this process)", (unsigned long)d.pixelFormat, lost); }
nvmtl_texture_desc_swizzle(t, d);
nvlog("newTextureWithDescriptor: %lux%lu%s -> %p", (unsigned long)d.width, (unsigned long)d.height, t->_stex ? " +storage" : "", (__bridge void *)t); return t; }
typedef struct { uint32_t magic, seed, gen; } nvmtl_vram_tag;
#define NVMTL_VRAM_MAGIC 0x564d5634u
static unsigned long long g_surf_vram, g_surf_private, g_surfin_skip, g_surfin_copy;
static CFStringRef nvmtl_vram_tag_key(NSUInteger plane) { return CFStringCreateWithFormat(NULL, NULL, CFSTR("NVMTLVramAt:p%lu"), (unsigned long)plane); }
static int nvmtl_vram_tag_current(IOSurfaceRef surf, NSUInteger plane, uint32_t seed)
{
CFStringRef k = nvmtl_vram_tag_key(plane); CFTypeRef v = IOSurfaceCopyValue(surf, k); CFRelease(k);
nvmtl_vram_tag t = { 0, 0, 0 };
int ok = v && CFGetTypeID(v) == CFDataGetTypeID() && CFDataGetLength((CFDataRef)v) == (CFIndex)sizeof t;
if (ok) memcpy(&t, CFDataGetBytePtr((CFDataRef)v), sizeof t);
if (v) CFRelease(v);
return ok && t.magic == NVMTL_VRAM_MAGIC && t.seed == seed;
}
static uint32_t nvmtl_vram_gen(IOSurfaceRef surf, NSUInteger plane)
{
CFStringRef k = nvmtl_vram_tag_key(plane); CFTypeRef v = IOSurfaceCopyValue(surf, k); CFRelease(k);
nvmtl_vram_tag t = { 0, 0, 0 };
if (v && CFGetTypeID(v) == CFDataGetTypeID() && CFDataGetLength((CFDataRef)v) == (CFIndex)sizeof t) memcpy(&t, CFDataGetBytePtr((CFDataRef)v), sizeof t);
if (v) CFRelease(v);
return t.magic == NVMTL_VRAM_MAGIC ? t.gen : 0;
}
static void nvmtl_vram_tag_write(IOSurfaceRef surf, NSUInteger plane, uint32_t seed, uint32_t gen)
{
nvmtl_vram_tag t = { NVMTL_VRAM_MAGIC, seed, gen };
CFDataRef dd = CFDataCreate(NULL, (const UInt8 *)&t, sizeof t); CFStringRef k = nvmtl_vram_tag_key(plane);
IOSurfaceSetValue(surf, k, dd); CFRelease(k); CFRelease(dd);
}
static uint32_t nvmtl_vram_tag_bump(IOSurfaceRef surf, NSUInteger plane, uint32_t seed)
{
const uint32_t g = nvmtl_vram_gen(surf, plane) + 1; nvmtl_vram_tag_write(surf, plane, seed, g); return g;
}
static void nvmtl_vram_tag_set(IOSurfaceRef surf, NSUInteger plane, uint32_t seed)
{
nvmtl_vram_tag t = { NVMTL_VRAM_MAGIC, seed, nvmtl_vram_gen(surf, plane) };
CFDataRef d = CFDataCreate(NULL, (const UInt8 *)&t, sizeof t); CFStringRef k = nvmtl_vram_tag_key(plane);
IOSurfaceSetValue(surf, k, d); CFRelease(k); CFRelease(d);
}
static int nvmtl_surface_image_create(NVMTLTexture *t, IOSurfaceRef surf, NSUInteger plane, uint32_t w, uint32_t h,
uint32_t vkf, uint32_t bpp, int a8, int stex)
{
// AMD APU (Radeon 780M): the GPU renders and samples the IOSurface's own pages, a linear image over the surface's
// allocation imported as host memory (VK_EXT_external_memory_host), so nothing is copied in or out. Without it
// WindowServer read each composited 2560x1600 frame back with memmove: ~12 ms and ~1.3 GB/s of its CPU, and the
// panel then copied the write-combined result again (2026-10-20). NVMTL_NO_SURFACE_HOST=1 keeps the copies.
static int hostOn = -1;
if (hostOn < 0) hostOn = nvmtl_vk_vendor() == 0x1002 && !getenv("NVMTL_NO_SURFACE_HOST");
nvk_buffer copyBuf = { 0 }; size_t copyRow = 0; // the imported pages, kept for a private image's GPU copies
if (hostOn && surf && plane == 0 && IOSurfaceGetPlaneCount(surf) <= 1) {
void *base = IOSurfaceGetBaseAddress(surf);
const size_t row = IOSurfaceGetBytesPerRow(surf), sh = IOSurfaceGetHeight(surf), al = nvmtl_vk_host_import_align();
// the surface is mapped in whole pages: its allocation rounded up to the import alignment is still its own
const size_t alloc = IOSurfaceGetAllocSize(surf), span = al ? (alloc + al - 1) & ~(al - 1) : 0;
if (base && al && !((uintptr_t)base & (al - 1)) && alloc && (size_t)w * (bpp ? bpp : 4) <= row
&& h <= sh && row % 32 == 0 && row * (h - 1) + (size_t)w * (bpp ? bpp : 4) <= alloc) {
nvk_buffer hb;
if (!nvmtl_vk_buffer_import_host(base, span, &hb)) {
if (!nvmtl_vk_image_create_buffer_alias(w, h, vkf, bpp, a8, stex, 1, &hb, 0, row, &t->_i)) {
t->_hostBuf = hb; t->_hostOn = YES; t->_surfSeed = IOSurfaceGetSeed(surf); t->_surfSynced = YES;
static unsigned long long nh; static unsigned said;
if (said++ < 8 || ++nh % 2000 == 0)
nvlog("surface %u %ux%u pitch %zu -> its own pages (host import, no copies)", (unsigned)IOSurfaceGetID(surf), w, h, row);
return 0;
}
copyBuf = hb; copyRow = row; // no linear image at this pitch (RADV wants 256-byte rows)
}
}
}
if (surf && plane == 0 && IOSurfaceGetPlaneCount(surf) <= 1 && nvmtl_vk_surface_share_on()) {
size_t row = IOSurfaceGetBytesPerRow(surf), sh = IOSurfaceGetHeight(surf);
if ((size_t)w * (bpp ? bpp : 4) <= row && h <= sh && row % 32 == 0) {
nvk_buffer vb;
if (!nvmtl_vk_surface_vram(IOSurfaceGetID(surf), 0, row * h, &vb)) {
if (!nvmtl_vk_image_create_buffer_alias(w, h, vkf, bpp, a8, stex, 1, &vb, 0, row, &t->_i)) {
if (copyBuf.buf) nvmtl_vk_buffer_destroy(©Buf);
t->_vramBuf = vb; t->_vramOn = YES; g_surf_vram++;
uint32_t seed = IOSurfaceGetSeed(surf);
int current = nvmtl_vram_tag_current(surf, 0, seed);
if (current) { t->_surfSeed = seed; t->_surfSynced = YES; }
static unsigned n; if (n++ < 8 || n % 2000 == 0)
nvlog("item 7: surface %u %ux%u pitch %zu -> the family's VRAM%s (vram %llu, private %llu)", (unsigned)IOSurfaceGetID(surf),
w, h, row, current ? ", already current (no upload)" : "", g_surf_vram, g_surf_private);
return 0;
}
nvmtl_vk_buffer_destroy(&vb);
}
}
}
g_surf_private++;
// A private image stands for the whole surface: wrappers that read it and wrappers that write it must share ONE image
// (nvmtlNewSurfaceTexture caches it), or what one writes the other never sees. So it is made writable whenever the
// format can be, whatever the first wrapper asked for.
if (!stex && nvmtl_vk_format_is_storage(vkf)) stex = 1;
if (surf) {
const size_t prow = IOSurfaceGetBytesPerRow(surf), pplanes = IOSurfaceGetPlaneCount(surf);
nvlog("item 7: surface %u %ux%u plane %lu -> a private image, copied in and out %s (%s; row %zu bytes, %zu plane(s))",
(unsigned)IOSurfaceGetID(surf), w, h, (unsigned long)plane, copyBuf.buf ? "by the GPU over the surface's imported pages" : "through the CPU",
(plane != 0 || pplanes > 1) ? "more than one plane" : ((size_t)w * (bpp ? bpp : 4) > prow || h > IOSurfaceGetHeight(surf)) ? "image larger than the surface"
: (prow % 32) ? "the row is not a multiple of 32 bytes" : copyBuf.buf ? "no linear image at this row pitch" : "the family VRAM could not be used", prow, pplanes);
}
const int rc = nvmtl_vk_image_create_typed(w, h, vkf, bpp, a8, 1, stex, 2u, 1u, &t->_i);
if (copyBuf.buf) {
if (rc) nvmtl_vk_buffer_destroy(©Buf);
else { t->_hostBuf = copyBuf; t->_hostCopy = YES; t->_hostRow = copyRow; }
}
return rc;
}
static char nvmtl_surface_cache_key, nvmtl_surface_keep_key;
// A surface's backing (a private image, or the surface's own pages imported for the GPU) lives as long as the application
// keeps the surface, not just as long as one of its wrappers: CoreImage makes a new MTLTexture for every pass over a
// pooled IOSurface and lets the previous one go first, and with only the weak cache entry the next pass would get a fresh
// image uploaded from the surface's memory rather than the image the previous pass wrote. CoreAnimation's flatten cache
// does the same every frame, and each new wrapper imported 0.5-4 MB again (wired, GPU-mapped, unmapped, freed: ~2.5 per
// frame, a sixth of WindowServer's frame time, 2026-10-21). The backing holds the surface, so its ID cannot be reused
// while the entry stands; entries whose surface only the backing still holds are dropped at the next insert.
// Called under @synchronized(device).
static void nvmtl_surface_keep(id dev, NSString *key, NVMTLTexture *t) {
NSMutableDictionary *keep = objc_getAssociatedObject(dev, &nvmtl_surface_keep_key);
if (!keep) { keep = [NSMutableDictionary new]; objc_setAssociatedObject(dev, &nvmtl_surface_keep_key, keep, OBJC_ASSOCIATION_RETAIN_NONATOMIC); }
for (NSString *k in keep.allKeys) {
NVMTLTexture *b = keep[k];
if (!b->_surf || CFGetRetainCount(b->_surf) <= 1) [keep removeObjectForKey:k];
}
keep[key] = t;
}
- (id<MTLTexture>)newTextureWithDescriptor:(MTLTextureDescriptor *)d iosurface:(IOSurfaceRef)surf plane:(NSUInteger)plane {