-
Notifications
You must be signed in to change notification settings - Fork 611
/
kern_igfx.cpp
executable file
·2651 lines (2290 loc) · 128 KB
/
kern_igfx.cpp
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
//
// kern_igfx.cpp
// WhateverGreen
//
// Copyright © 2018 vit9696. All rights reserved.
//
#include "kern_igfx.hpp"
#include "kern_fb.hpp"
#include "kern_guc.hpp"
#include "kern_agdc.hpp"
#include <Headers/kern_api.hpp>
#include <Headers/kern_cpu.hpp>
#include <Headers/kern_file.hpp>
#include <Headers/kern_iokit.hpp>
static const char *pathIntelHD[] { "/System/Library/Extensions/AppleIntelHDGraphics.kext/Contents/MacOS/AppleIntelHDGraphics" };
static const char *pathIntelHDFb[] { "/System/Library/Extensions/AppleIntelHDGraphicsFB.kext/Contents/MacOS/AppleIntelHDGraphicsFB" };
static const char *pathIntelHD3000[] { "/System/Library/Extensions/AppleIntelHD3000Graphics.kext/Contents/MacOS/AppleIntelHD3000Graphics" };
static const char *pathIntelSNBFb[] { "/System/Library/Extensions/AppleIntelSNBGraphicsFB.kext/Contents/MacOS/AppleIntelSNBGraphicsFB" };
static const char *pathIntelHD4000[] { "/System/Library/Extensions/AppleIntelHD4000Graphics.kext/Contents/MacOS/AppleIntelHD4000Graphics" };
static const char *pathIntelCapriFb[] { "/System/Library/Extensions/AppleIntelFramebufferCapri.kext/Contents/MacOS/AppleIntelFramebufferCapri" };
static const char *pathIntelHD5000[] { "/System/Library/Extensions/AppleIntelHD5000Graphics.kext/Contents/MacOS/AppleIntelHD5000Graphics" };
static const char *pathIntelAzulFb[] { "/System/Library/Extensions/AppleIntelFramebufferAzul.kext/Contents/MacOS/AppleIntelFramebufferAzul" };
static const char *pathIntelBDW[] { "/System/Library/Extensions/AppleIntelBDWGraphics.kext/Contents/MacOS/AppleIntelBDWGraphics" };
static const char *pathIntelBDWFb[] { "/System/Library/Extensions/AppleIntelBDWGraphicsFramebuffer.kext/Contents/MacOS/AppleIntelBDWGraphicsFramebuffer" };
static const char *pathIntelSKL[] { "/System/Library/Extensions/AppleIntelSKLGraphics.kext/Contents/MacOS/AppleIntelSKLGraphics" };
static const char *pathIntelSKLFb[] { "/System/Library/Extensions/AppleIntelSKLGraphicsFramebuffer.kext/Contents/MacOS/AppleIntelSKLGraphicsFramebuffer" };
static const char *pathIntelKBL[] { "/System/Library/Extensions/AppleIntelKBLGraphics.kext/Contents/MacOS/AppleIntelKBLGraphics" };
static const char *pathIntelKBLFb[] { "/System/Library/Extensions/AppleIntelKBLGraphicsFramebuffer.kext/Contents/MacOS/AppleIntelKBLGraphicsFramebuffer" };
static const char *pathIntelCFLFb[] { "/System/Library/Extensions/AppleIntelCFLGraphicsFramebuffer.kext/Contents/MacOS/AppleIntelCFLGraphicsFramebuffer" };
static const char *pathIntelCNL[] { "/System/Library/Extensions/AppleIntelCNLGraphics.kext/Contents/MacOS/AppleIntelCNLGraphics" };
static const char *pathIntelCNLFb[] { "/System/Library/Extensions/AppleIntelCNLGraphicsFramebuffer.kext/Contents/MacOS/AppleIntelCNLGraphicsFramebuffer" };
static const char *pathIntelICL[] { "/System/Library/Extensions/AppleIntelICLGraphics.kext/Contents/MacOS/AppleIntelICLGraphics" };
static const char *pathIntelICLLPFb[] { "/System/Library/Extensions/AppleIntelICLLPGraphicsFramebuffer.kext/Contents/MacOS/AppleIntelICLLPGraphicsFramebuffer" };
static const char *pathIntelICLHPFb[] { "/System/Library/Extensions/AppleIntelICLHPGraphicsFramebuffer.kext/Contents/MacOS/AppleIntelICLHPGraphicsFramebuffer" };
static KernelPatcher::KextInfo kextIntelHD { "com.apple.driver.AppleIntelHDGraphics", pathIntelHD, arrsize(pathIntelHD), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelHDFb { "com.apple.driver.AppleIntelHDGraphicsFB", pathIntelHDFb, arrsize(pathIntelHDFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelHD3000 { "com.apple.driver.AppleIntelHD3000Graphics", pathIntelHD3000, arrsize(pathIntelHD3000), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelSNBFb { "com.apple.driver.AppleIntelSNBGraphicsFB", pathIntelSNBFb, arrsize(pathIntelSNBFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelHD4000 { "com.apple.driver.AppleIntelHD4000Graphics", pathIntelHD4000, arrsize(pathIntelHD4000), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelCapriFb { "com.apple.driver.AppleIntelFramebufferCapri", pathIntelCapriFb, arrsize(pathIntelCapriFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelHD5000 { "com.apple.driver.AppleIntelHD5000Graphics", pathIntelHD5000, arrsize(pathIntelHD5000), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelAzulFb { "com.apple.driver.AppleIntelFramebufferAzul", pathIntelAzulFb, arrsize(pathIntelAzulFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelBDW { "com.apple.driver.AppleIntelBDWGraphics", pathIntelBDW, arrsize(pathIntelBDW), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelBDWFb { "com.apple.driver.AppleIntelBDWGraphicsFramebuffer", pathIntelBDWFb, arrsize(pathIntelBDWFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelSKL { "com.apple.driver.AppleIntelSKLGraphics", pathIntelSKL, arrsize(pathIntelSKL), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelSKLFb { "com.apple.driver.AppleIntelSKLGraphicsFramebuffer", pathIntelSKLFb, arrsize(pathIntelSKLFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelKBL { "com.apple.driver.AppleIntelKBLGraphics", pathIntelKBL, arrsize(pathIntelKBL), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelKBLFb { "com.apple.driver.AppleIntelKBLGraphicsFramebuffer", pathIntelKBLFb, arrsize(pathIntelKBLFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelCFLFb { "com.apple.driver.AppleIntelCFLGraphicsFramebuffer", pathIntelCFLFb, arrsize(pathIntelCFLFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelCNL { "com.apple.driver.AppleIntelCNLGraphics", pathIntelCNL, arrsize(pathIntelCNL), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelCNLFb { "com.apple.driver.AppleIntelCNLGraphicsFramebuffer", pathIntelCNLFb, arrsize(pathIntelCNLFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelICL { "com.apple.driver.AppleIntelICLGraphics", pathIntelICL, arrsize(pathIntelICL), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelICLLPFb { "com.apple.driver.AppleIntelICLLPGraphicsFramebuffer", pathIntelICLLPFb, arrsize(pathIntelICLLPFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
static KernelPatcher::KextInfo kextIntelICLHPFb { "com.apple.driver.AppleIntelICLHPGraphicsFramebuffer", pathIntelICLHPFb, arrsize(pathIntelICLHPFb), {}, {}, KernelPatcher::KextInfo::Unloaded };
IGFX *IGFX::callbackIGFX;
void IGFX::init() {
callbackIGFX = this;
auto &bdi = BaseDeviceInfo::get();
auto generation = bdi.cpuGeneration;
auto family = bdi.cpuFamily;
auto model = bdi.cpuModel;
switch (generation) {
case CPUInfo::CpuGeneration::Penryn:
case CPUInfo::CpuGeneration::Nehalem:
// Do not warn about legacy processors (e.g. Xeon).
break;
case CPUInfo::CpuGeneration::Westmere:
currentGraphics = &kextIntelHD;
currentFramebuffer = &kextIntelHDFb;
break;
case CPUInfo::CpuGeneration::SandyBridge: {
int tmp = 1;
PE_parse_boot_argn("igfxsnb", &tmp, sizeof(tmp));
moderniseAccelerator = tmp == 1;
currentGraphics = &kextIntelHD3000;
currentFramebuffer = &kextIntelSNBFb;
break;
}
case CPUInfo::CpuGeneration::IvyBridge:
currentGraphics = &kextIntelHD4000;
currentFramebuffer = &kextIntelCapriFb;
break;
case CPUInfo::CpuGeneration::Haswell:
currentGraphics = &kextIntelHD5000;
currentFramebuffer = &kextIntelAzulFb;
break;
case CPUInfo::CpuGeneration::Broadwell:
currentGraphics = &kextIntelBDW;
currentFramebuffer = &kextIntelBDWFb;
break;
case CPUInfo::CpuGeneration::Skylake:
supportsGuCFirmware = true;
currentGraphics = &kextIntelSKL;
currentFramebuffer = &kextIntelSKLFb;
forceCompleteModeset.supported = forceCompleteModeset.legacy = true; // not enabled, as on legacy operating systems it casues crashes.
break;
case CPUInfo::CpuGeneration::KabyLake:
supportsGuCFirmware = true;
currentGraphics = &kextIntelKBL;
currentFramebuffer = &kextIntelKBLFb;
forceCompleteModeset.supported = forceCompleteModeset.enable = true;
RPSControl.enabled = true;
ForceWakeWorkaround.enabled = true;
disableTypeCCheck = true;
break;
case CPUInfo::CpuGeneration::CoffeeLake:
supportsGuCFirmware = true;
currentGraphics = &kextIntelKBL;
currentFramebuffer = &kextIntelCFLFb;
// Allow faking ask KBL
currentFramebufferOpt = &kextIntelKBLFb;
// Note, several CFL GPUs are completely broken. They freeze in IGMemoryManager::initCache due to incompatible
// configuration, supposedly due to Apple not supporting new MOCS table and forcing Skylake-based format.
// See: https://github.com/torvalds/linux/blob/135c5504a600ff9b06e321694fbcac78a9530cd4/drivers/gpu/drm/i915/intel_mocs.c#L181
forceCompleteModeset.supported = forceCompleteModeset.enable = true;
RPSControl.enabled = true;
ForceWakeWorkaround.enabled = true;
disableTypeCCheck = true;
break;
case CPUInfo::CpuGeneration::CannonLake:
supportsGuCFirmware = true;
currentGraphics = &kextIntelCNL;
currentFramebuffer = &kextIntelCNLFb;
forceCompleteModeset.supported = forceCompleteModeset.enable = true;
disableTypeCCheck = true;
break;
case CPUInfo::CpuGeneration::IceLake:
supportsGuCFirmware = true;
currentGraphics = &kextIntelICL;
currentFramebuffer = &kextIntelICLLPFb;
currentFramebufferOpt = &kextIntelICLHPFb;
forceCompleteModeset.supported = forceCompleteModeset.enable = true;
disableTypeCCheck = true;
break;
case CPUInfo::CpuGeneration::CometLake:
supportsGuCFirmware = true;
currentGraphics = &kextIntelKBL;
currentFramebuffer = &kextIntelCFLFb;
// Allow faking ask KBL
currentFramebufferOpt = &kextIntelKBLFb;
// Note, several CFL GPUs are completely broken. They freeze in IGMemoryManager::initCache due to incompatible
// configuration, supposedly due to Apple not supporting new MOCS table and forcing Skylake-based format.
// See: https://github.com/torvalds/linux/blob/135c5504a600ff9b06e321694fbcac78a9530cd4/drivers/gpu/drm/i915/intel_mocs.c#L181
forceCompleteModeset.supported = forceCompleteModeset.enable = true;
disableTypeCCheck = true;
break;
default:
SYSLOG("igfx", "found an unsupported processor 0x%X:0x%X, please report this!", family, model);
break;
}
if (currentGraphics)
lilu.onKextLoadForce(currentGraphics);
if (currentFramebuffer)
lilu.onKextLoadForce(currentFramebuffer);
if (currentFramebufferOpt)
lilu.onKextLoadForce(currentFramebufferOpt);
}
void IGFX::deinit() {
for (auto &con : lspcons) {
LSPCON::deleter(con.lspcon);
con.lspcon = nullptr;
}
}
void IGFX::processKernel(KernelPatcher &patcher, DeviceInfo *info) {
bool switchOffGraphics = false;
bool switchOffFramebuffer = false;
framebufferPatch.framebufferId = info->reportedFramebufferId;
auto cpuGeneration = BaseDeviceInfo::get().cpuGeneration;
if (info->videoBuiltin) {
applyFramebufferPatch = loadPatchesFromDevice(info->videoBuiltin, info->reportedFramebufferId);
#ifdef DEBUG
dumpFramebufferToDisk = checkKernelArgument("-igfxdump");
dumpPlatformTable = checkKernelArgument("-igfxfbdump");
debugFramebuffer = checkKernelArgument("-igfxfbdbg");
#endif
uint32_t nrpsc = 0;
if (PE_parse_boot_argn("igfxnorpsc", &nrpsc, sizeof(nrpsc)) ||
WIOKit::getOSDataValue(info->videoBuiltin, "no-rps-control", nrpsc)) {
DBGLOG("weg", "RPS control patch overriden (%u)", nrpsc);
RPSControl.enabled &= !nrpsc;
}
uint32_t forceCompleteModeSet = 0;
if (PE_parse_boot_argn("igfxfcms", &forceCompleteModeSet, sizeof(forceCompleteModeSet))) {
forceCompleteModeset.enable = forceCompleteModeset.supported && forceCompleteModeSet != 0;
DBGLOG("weg", "force complete-modeset overriden by boot-argument %u -> %d", forceCompleteModeSet, forceCompleteModeset.enable);
} else if (WIOKit::getOSDataValue(info->videoBuiltin, "complete-modeset", forceCompleteModeSet)) {
forceCompleteModeset.enable = forceCompleteModeset.supported && forceCompleteModeSet != 0;
DBGLOG("weg", "force complete-modeset overriden by device property %u -> %d", forceCompleteModeSet, forceCompleteModeset.enable);
} else if (info->firmwareVendor == DeviceInfo::FirmwareVendor::Apple) {
forceCompleteModeset.enable = false; // may interfere with FV2
DBGLOG("weg", "force complete-modeset overriden by Apple firmware -> %d", forceCompleteModeset.enable);
}
if (forceCompleteModeset.enable) {
uint64_t fbs;
if (PE_parse_boot_argn("igfxfcmsfbs", &fbs, sizeof(fbs)) ||
WIOKit::getOSDataValue(info->videoBuiltin, "complete-modeset-framebuffers", fbs)) {
for (size_t i = 0; i < arrsize(forceCompleteModeset.fbs); i++)
forceCompleteModeset.fbs[i] = (fbs >> (8 * i)) & 0xffU;
forceCompleteModeset.customised = true;
}
}
uint32_t forceOnline = 0;
if (PE_parse_boot_argn("igfxonln", &forceOnline, sizeof(forceOnline))) {
forceOnlineDisplay.enable = forceOnline != 0;
DBGLOG("weg", "force online overriden by boot-argument %u", forceOnline);
} else if (WIOKit::getOSDataValue(info->videoBuiltin, "force-online", forceOnline)) {
forceOnlineDisplay.enable = forceOnline != 0;
DBGLOG("weg", "force online overriden by device property %u", forceOnline);
}
if (forceOnlineDisplay.enable) {
uint64_t fbs;
if (PE_parse_boot_argn("igfxonlnfbs", &fbs, sizeof(fbs)) ||
WIOKit::getOSDataValue(info->videoBuiltin, "force-online-framebuffers", fbs)) {
for (size_t i = 0; i < arrsize(forceOnlineDisplay.fbs); i++)
forceOnlineDisplay.fbs[i] = (fbs >> (8 * i)) & 0xffU;
forceOnlineDisplay.customised = true;
}
}
if (supportsGuCFirmware && getKernelVersion() >= KernelVersion::HighSierra) {
if (!PE_parse_boot_argn("igfxfw", &fwLoadMode, sizeof(fwLoadMode)))
WIOKit::getOSDataValue<int32_t>(info->videoBuiltin, "igfxfw", fwLoadMode);
if (fwLoadMode == FW_AUTO)
fwLoadMode = info->firmwareVendor == DeviceInfo::FirmwareVendor::Apple ? FW_APPLE : FW_DISABLE;
} else {
fwLoadMode = FW_APPLE; /* Do nothing, GuC is either unsupported due to low OS or Apple */
}
// Enable the fix for computing HDMI dividers on SKL, KBL, CFL platforms if the corresponding boot argument is found
hdmiP0P1P2Patch = checkKernelArgument("-igfxhdmidivs");
// Of if "enable-hdmi-dividers-fix" is set in IGPU property
if (!hdmiP0P1P2Patch)
hdmiP0P1P2Patch = info->videoBuiltin->getProperty("enable-hdmi-dividers-fix") != nullptr;
// Enable the LSPCON driver support if the corresponding boot argument is found
supportLSPCON = checkKernelArgument("-igfxlspcon");
// Or if "enable-lspcon-support" is set in IGPU property
if (!supportLSPCON)
supportLSPCON = info->videoBuiltin->getProperty("enable-lspcon-support") != nullptr;
// Read the user-defined IGPU properties to know whether a connector has an onboard LSPCON chip
if (supportLSPCON) {
char name[48];
uint32_t pmode = 0x01; // PCON mode as a fallback value
for (size_t index = 0; index < arrsize(lspcons); index++) {
bzero(name, sizeof(name));
snprintf(name, sizeof(name), "framebuffer-con%lu-has-lspcon", index);
(void)WIOKit::getOSDataValue(info->videoBuiltin, name, lspcons[index].hasLSPCON);
snprintf(name, sizeof(name), "framebuffer-con%lu-preferred-lspcon-mode", index);
(void)WIOKit::getOSDataValue(info->videoBuiltin, name, pmode);
// Assuming PCON mode if invalid mode value (i.e. > 1) specified by the user
lspcons[index].preferredMode = LSPCON::parseMode(pmode != 0);
}
}
// Enable the verbose output in I2C-over-AUX transactions if the corresponding boot argument is found
verboseI2C = checkKernelArgument("-igfxi2cdbg");
// Enable maximum link rate patch if the corresponding boot argument is found
maxLinkRatePatch = checkKernelArgument("-igfxmlr");
// Or if "enable-dpcd-max-link-rate-fix" is set in IGPU property
if (!maxLinkRatePatch)
maxLinkRatePatch = info->videoBuiltin->getProperty("enable-dpcd-max-link-rate-fix") != nullptr;
disableAccel = checkKernelArgument("-igfxvesa");
disableTypeCCheck &= !checkKernelArgument("-igfxtypec");
// Read the custom maximum link rate if present
if (WIOKit::getOSDataValue(info->videoBuiltin, "dpcd-max-link-rate", maxLinkRate)) {
// Guard: Verify the custom link rate before using it
switch (maxLinkRate) {
case 0x1E: // HBR3 8.1 Gbps
case 0x14: // HBR2 5.4 Gbps
case 0x0C: // 3_24 3.24 Gbps Used by Apple internally
case 0x0A: // HBR 2.7 Gbps
case 0x06: // RBR 1.62 Gbps
DBGLOG("igfx", "MLR: Found a valid custom maximum link rate value 0x%02x", maxLinkRate);
break;
default:
// Invalid link rate value
SYSLOG("igfx", "MLR: Found an invalid custom maximum link rate value. Will use 0x14 as a fallback value.");
maxLinkRate = 0x14;
break;
}
} else {
DBGLOG("igfx", "MLR: No custom max link rate specified. Will use 0x14 as the default value.");
}
// Enable CFL backlight patch on mobile CFL or if IGPU propery enable-cfl-backlight-fix is set
int bkl = 0;
if (PE_parse_boot_argn("igfxcflbklt", &bkl, sizeof(bkl)))
cflBacklightPatch = bkl == 1 ? CoffeeBacklightPatch::On : CoffeeBacklightPatch::Off;
else if (info->videoBuiltin->getProperty("enable-cfl-backlight-fix"))
cflBacklightPatch = CoffeeBacklightPatch::On;
else if (currentFramebuffer == &kextIntelCFLFb && BaseDeviceInfo::get().modelType == WIOKit::ComputerModel::ComputerLaptop)
cflBacklightPatch = CoffeeBacklightPatch::Auto;
if (WIOKit::getOSDataValue(info->videoBuiltin, "max-backlight-freq", targetBacklightFrequency))
DBGLOG("igfx", "read custom backlight frequency %u", targetBacklightFrequency);
bool connectorLessFrame = info->reportedFramebufferIsConnectorLess;
// Black screen (ComputeLaneCount) happened from 10.12.4
// It only affects SKL, KBL, and CFL drivers with a frame with connectors.
if (!connectorLessFrame && cpuGeneration >= CPUInfo::CpuGeneration::Skylake &&
((getKernelVersion() == KernelVersion::Sierra && getKernelMinorVersion() >= 5) || getKernelVersion() >= KernelVersion::HighSierra)) {
blackScreenPatch = info->firmwareVendor != DeviceInfo::FirmwareVendor::Apple;
}
// PAVP patch is only necessary when we have no discrete GPU.
int pavpMode = connectorLessFrame || info->firmwareVendor == DeviceInfo::FirmwareVendor::Apple;
if (!PE_parse_boot_argn("igfxpavp", &pavpMode, sizeof(pavpMode)))
WIOKit::getOSDataValue(info->videoBuiltin, "igfxpavp", pavpMode);
pavpDisablePatch = pavpMode == 0 && cpuGeneration >= CPUInfo::CpuGeneration::SandyBridge;
int gl = info->videoBuiltin->getProperty("disable-metal") != nullptr;
PE_parse_boot_argn("igfxgl", &gl, sizeof(gl));
forceOpenGL = gl == 1;
int metal = info->videoBuiltin->getProperty("enable-metal") != nullptr;
PE_parse_boot_argn("igfxmetal", &metal, sizeof(metal));
forceMetal = metal == 1;
int agdc = info->videoBuiltin->getProperty("disable-agdc") != nullptr ? 0 : 1;
PE_parse_boot_argn("igfxagdc", &agdc, sizeof(agdc));
disableAGDC = agdc == 0;
// Starting from 10.14.4b1 Skylake+ graphics randomly kernel panics on GPU usage
readDescriptorPatch = cpuGeneration >= CPUInfo::CpuGeneration::Skylake && getKernelVersion() >= KernelVersion::Mojave;
// Automatically enable HDMI -> DP patches
bool nohdmi = info->videoBuiltin->getProperty("disable-hdmi-patches") != nullptr;
hdmiAutopatch = !applyFramebufferPatch && !connectorLessFrame && getKernelVersion() >= Yosemite &&
cpuGeneration >= CPUInfo::CpuGeneration::SandyBridge && !checkKernelArgument("-igfxnohdmi") && !nohdmi;
// Set AAPL00,DualLink to zero on Westmere if applying single link patches.
if (cpuGeneration == CPUInfo::CpuGeneration::Westmere && framebufferWestmerePatches.SingleLink) {
uint8_t dualLinkBytes[] { 0x00, 0x00, 0x00, 0x00 };
info->videoBuiltin->setProperty("AAPL00,DualLink", dualLinkBytes, sizeof(dualLinkBytes));
}
auto requresFramebufferPatches = [this]() {
if (blackScreenPatch)
return true;
if (applyFramebufferPatch || hdmiAutopatch)
return true;
if (dumpFramebufferToDisk || dumpPlatformTable || debugFramebuffer)
return true;
if (cflBacklightPatch != CoffeeBacklightPatch::Off)
return true;
if (maxLinkRatePatch)
return true;
if (hdmiP0P1P2Patch)
return true;
if (supportLSPCON)
return true;
if (forceCompleteModeset.enable)
return true;
if (forceOnlineDisplay.enable)
return true;
if (disableAGDC)
return true;
if (RPSControl.enabled)
return true;
if (ForceWakeWorkaround.enabled)
return true;
if (disableTypeCCheck)
return true;
return false;
};
auto requiresGraphicsPatches = [this]() {
if (pavpDisablePatch)
return true;
if (forceOpenGL)
return true;
if (forceMetal)
return true;
if (moderniseAccelerator)
return true;
if (fwLoadMode != FW_APPLE)
return true;
if (readDescriptorPatch)
return true;
if (RPSControl.enabled)
return true;
if (disableAccel)
return true;
return false;
};
// Disable kext patching if we have nothing to do.
switchOffFramebuffer = !requresFramebufferPatches();
switchOffGraphics = !requiresGraphicsPatches();
} else {
switchOffGraphics = switchOffFramebuffer = true;
}
if (switchOffGraphics && currentGraphics)
currentGraphics->switchOff();
if (switchOffFramebuffer) {
if (currentFramebuffer)
currentFramebuffer->switchOff();
if (currentFramebufferOpt)
currentFramebufferOpt->switchOff();
}
if (moderniseAccelerator) {
KernelPatcher::RouteRequest request("__ZN9IOService20copyExistingServicesEP12OSDictionaryjj", wrapCopyExistingServices, orgCopyExistingServices);
patcher.routeMultiple(KernelPatcher::KernelID, &request, 1);
}
}
bool IGFX::processKext(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) {
auto cpuGeneration = BaseDeviceInfo::get().cpuGeneration;
if (currentGraphics && currentGraphics->loadIndex == index) {
if (pavpDisablePatch) {
auto callbackSym = "__ZN16IntelAccelerator19PAVPCommandCallbackE22PAVPSessionCommandID_tjPjb";
if (cpuGeneration == CPUInfo::CpuGeneration::SandyBridge)
callbackSym = "__ZN15Gen6Accelerator19PAVPCommandCallbackE22PAVPSessionCommandID_t18PAVPSessionAppID_tPjb";
else if (cpuGeneration == CPUInfo::CpuGeneration::IvyBridge)
callbackSym = "__ZN16IntelAccelerator19PAVPCommandCallbackE22PAVPSessionCommandID_t18PAVPSessionAppID_tPjb";
KernelPatcher::RouteRequest request(callbackSym, wrapPavpSessionCallback, orgPavpSessionCallback);
patcher.routeMultiple(index, &request, 1, address, size);
}
if (forceOpenGL || forceMetal || moderniseAccelerator || fwLoadMode != FW_APPLE || disableAccel) {
KernelPatcher::RouteRequest request("__ZN16IntelAccelerator5startEP9IOService", wrapAcceleratorStart, orgAcceleratorStart);
patcher.routeMultiple(index, &request, 1, address, size);
if (fwLoadMode == FW_GENERIC && getKernelVersion() <= KernelVersion::Mojave)
loadIGScheduler4Patches(patcher, index, address, size);
}
if (readDescriptorPatch) {
KernelPatcher::RouteRequest request("__ZNK25IGHardwareGlobalPageTable4readEyRyS0_", globalPageTableRead);
patcher.routeMultiple(index, &request, 1, address, size);
}
if (RPSControl.enabled)
RPSControl.initGraphics(patcher, index, address, size);
if (ForceWakeWorkaround.enabled)
ForceWakeWorkaround.initGraphics(*this, patcher, index, address, size);
return true;
}
if ((currentFramebuffer && currentFramebuffer->loadIndex == index) ||
(currentFramebufferOpt && currentFramebufferOpt->loadIndex == index)) {
// Find actual framebuffer used (kaby or coffee)
auto realFramebuffer = (currentFramebuffer && currentFramebuffer->loadIndex == index) ? currentFramebuffer : currentFramebufferOpt;
// Accept Coffee FB and enable backlight patches unless Off (Auto turns them on by default).
bool bklCoffeeFb = realFramebuffer == &kextIntelCFLFb && cflBacklightPatch != CoffeeBacklightPatch::Off;
// Accept Kaby FB and enable backlight patches if On (Auto is irrelevant here).
bool bklKabyFb = realFramebuffer == &kextIntelKBLFb && cflBacklightPatch == CoffeeBacklightPatch::On;
// Solve ReadRegister32 just once as it is sahred
if (bklCoffeeFb || bklKabyFb ||
RPSControl.enabled || ForceWakeWorkaround.enabled) {
AppleIntelFramebufferController__ReadRegister32 = patcher.solveSymbol<decltype(AppleIntelFramebufferController__ReadRegister32)>
(index, "__ZN31AppleIntelFramebufferController14ReadRegister32Em", address, size);
if (!AppleIntelFramebufferController__ReadRegister32)
SYSLOG("igfx", "Failed to find ReadRegister32");
}
if (bklCoffeeFb || bklKabyFb ||
RPSControl.enabled || ForceWakeWorkaround.enabled) {
AppleIntelFramebufferController__WriteRegister32 = patcher.solveSymbol<decltype(AppleIntelFramebufferController__WriteRegister32)>
(index, "__ZN31AppleIntelFramebufferController15WriteRegister32Emj", address, size);
if (!AppleIntelFramebufferController__WriteRegister32)
SYSLOG("igfx", "Failed to find WriteRegister32");
}
if (RPSControl.enabled || ForceWakeWorkaround.enabled)
gFramebufferController = patcher.solveSymbol<decltype(gFramebufferController)>(index, "_gController", address, size);
if (bklCoffeeFb || bklKabyFb) {
// Intel backlight is modeled via pulse-width modulation (PWM). See page 144 of:
// https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-kbl-vol12-display.pdf
// Singal-wise it looks as a cycle of signal levels on the timeline:
// 22111100221111002211110022111100 (4 cycles)
// 0 - no signal, 1 - no value (no pulse), 2 - pulse (light on)
// - Physical Cycle (0+1+2) defines maximum backlight frequency, limited by HW precision.
// - Base Cycle (1+2) defines [1/PWM Base Frequency], limited by physical cycle, see BXT_BLC_PWM_FREQ1.
// - Duty Cycle (2) defines [1/PWM Increment] - backlight level,
// [PWM Frequency Divider] - backlight max, see BXT_BLC_PWM_DUTY1.
// - Duty Cycle position (first vs last) is [PWM Polarity]
//
// Duty cycle = PWM Base Frequeny * (1 / PWM Increment) / PWM Frequency Divider
//
// On macOS there are extra limitations:
// - All values and operations are u32 (32-bit unsigned)
// - [1/PWM Increment] has 0 to 0xFFFF range
// - [PWM Frequency Divider] is fixed to be 0xFFFF
// - [PWM Base Frequency] is capped by 0xFFFF (to avoid u32 wraparound), and is hardcoded
// either in Framebuffer data (pre-CFL) or in the code (CFL: 7777 or 22222).
//
// On CFL the following patches have to be applied:
// - Hardcoded [PWM Base Frequency] should be patched or set after the hardcoded value is written by patching
// hardcoded frequencies. 65535 is used by default.
// - If [PWM Base Frequency] is > 65535, to avoid a wraparound code calculating BXT_BLC_PWM_DUTY1
// should be replaced to use 64-bit arithmetics.
// [PWM Base Frequency] can be specified via igfxbklt=1 boot-arg or backlight-base-frequency property.
// This patch will overwrite WriteRegister32 function to rescale all the register writes of backlight controller.
// Slightly different methods are used for CFL hardware running on KBL and CFL drivers.
if (AppleIntelFramebufferController__ReadRegister32 &&
AppleIntelFramebufferController__WriteRegister32) {
(bklCoffeeFb ? orgCflReadRegister32 : orgKblReadRegister32) = AppleIntelFramebufferController__ReadRegister32;
patcher.eraseCoverageInstPrefix(reinterpret_cast<mach_vm_address_t>(AppleIntelFramebufferController__WriteRegister32));
auto orgRegWrite = reinterpret_cast<decltype(orgCflWriteRegister32)>
(patcher.routeFunction(reinterpret_cast<mach_vm_address_t>(AppleIntelFramebufferController__WriteRegister32), reinterpret_cast<mach_vm_address_t>(bklCoffeeFb ? wrapCflWriteRegister32 : wrapKblWriteRegister32), true));
if (orgRegWrite) {
(bklCoffeeFb ? orgCflWriteRegister32 : orgKblWriteRegister32) = orgRegWrite;
} else {
SYSLOG("igfx", "failed to route WriteRegister32 for cfl %d", bklCoffeeFb);
patcher.clearError();
}
} else {
SYSLOG("igfx", "failed to find ReadRegister32 for cfl %d", bklCoffeeFb);
patcher.clearError();
}
}
if (maxLinkRatePatch) {
auto readAUXAddress = patcher.solveSymbol(index, "__ZN31AppleIntelFramebufferController7ReadAUXEP21AppleIntelFramebufferjtPvP21AppleIntelDisplayPath", address, size);
if (readAUXAddress) {
patcher.eraseCoverageInstPrefix(readAUXAddress);
orgReadAUX = reinterpret_cast<decltype(orgReadAUX)>(patcher.routeFunction(readAUXAddress, reinterpret_cast<mach_vm_address_t>(wrapReadAUX), true));
if (orgReadAUX) {
DBGLOG("igfx", "MLR: ReadAUX() has been routed successfully");
} else {
patcher.clearError();
SYSLOG("igfx", "MLR: Failed to route ReadAUX()");
}
} else {
SYSLOG("igfx", "MLR: Failed to find ReadAUX()");
patcher.clearError();
}
}
if (forceCompleteModeset.enable) {
const char *sym = "__ZN31AppleIntelFramebufferController16hwRegsNeedUpdateEP21AppleIntelFramebufferP21AppleIntelDisplayPathPNS_10CRTCParamsEPK29IODetailedTimingInformationV2";
if (forceCompleteModeset.legacy)
sym = "__ZN31AppleIntelFramebufferController16hwRegsNeedUpdateEP21AppleIntelFramebufferP21AppleIntelDisplayPathPNS_10CRTCParamsE";
KernelPatcher::RouteRequest request(sym, wrapHwRegsNeedUpdate, orgHwRegsNeedUpdate);
if (!patcher.routeMultiple(index, &request, 1, address, size))
SYSLOG("igfx", "failed to route hwRegsNeedUpdate");
}
if (forceOnlineDisplay.enable) {
KernelPatcher::RouteRequest request("__ZN21AppleIntelFramebuffer16getDisplayStatusEP21AppleIntelDisplayPath", wrapGetDisplayStatus, orgGetDisplayStatus);
if (!patcher.routeMultiple(index, &request, 1, address, size))
SYSLOG("igfx", "failed to route getDisplayStatus");
}
if (disableTypeCCheck) {
KernelPatcher::RouteRequest req("__ZN31AppleIntelFramebufferController17IsTypeCOnlySystemEv", wrapIsTypeCOnlySystem);
if (!patcher.routeMultiple(index, &req, 1, address, size))
SYSLOG("igfx", "failed to route IsTypeCOnlySystem");
}
if (RPSControl.enabled)
RPSControl.initFB(*this, patcher, index, address, size);
if (disableAGDC) {
KernelPatcher::RouteRequest request {"__ZN20IntelFBClientControl11doAttributeEjPmmS0_S0_P25IOExternalMethodArguments", wrapFBClientDoAttribute, orgFBClientDoAttribute};
if (!patcher.routeMultiple(index, &request, 1, address, size))
SYSLOG("igfx", "failed to route FBClientControl::doAttribute");
}
if (debugFramebuffer)
loadFramebufferDebug(patcher, index, address, size);
if (hdmiP0P1P2Patch) {
KernelPatcher::RouteRequest request("__ZN31AppleIntelFramebufferController17ComputeHdmiP0P1P2EjP21AppleIntelDisplayPathPNS_10CRTCParamsE", wrapComputeHdmiP0P1P2);
if (!patcher.routeMultiple(index, &request, 1, address, size))
SYSLOG("igfx", "failed to route ComputeHdmiP0P1P2");
}
if (supportLSPCON) {
auto roa = patcher.solveSymbol(index, "__ZN31AppleIntelFramebufferController14ReadI2COverAUXEP21AppleIntelFramebufferP21AppleIntelDisplayPathjtPhbh", address, size);
auto woa = patcher.solveSymbol(index, "__ZN31AppleIntelFramebufferController15WriteI2COverAUXEP21AppleIntelFramebufferP21AppleIntelDisplayPathjtPhb", address, size);
auto gdi = patcher.solveSymbol(index, "__ZN31AppleIntelFramebufferController11GetDPCDInfoEP21AppleIntelFramebufferP21AppleIntelDisplayPath", address, size);
if (roa && woa && gdi) {
patcher.eraseCoverageInstPrefix(roa);
patcher.eraseCoverageInstPrefix(woa);
patcher.eraseCoverageInstPrefix(gdi);
orgReadI2COverAUX = reinterpret_cast<decltype(orgReadI2COverAUX)>(patcher.routeFunction(roa, reinterpret_cast<mach_vm_address_t>(wrapReadI2COverAUX), true));
orgWriteI2COverAUX = reinterpret_cast<decltype(orgWriteI2COverAUX)>(patcher.routeFunction(woa, reinterpret_cast<mach_vm_address_t>(wrapWriteI2COverAUX), true));
orgGetDPCDInfo = reinterpret_cast<decltype(orgGetDPCDInfo)>(patcher.routeFunction(gdi, reinterpret_cast<mach_vm_address_t>(wrapGetDPCDInfo), true));
if (orgReadI2COverAUX && orgWriteI2COverAUX && orgGetDPCDInfo) {
DBGLOG("igfx", "SC: ReadI2COverAUX(), etc. have been routed successfully");
} else {
patcher.clearError();
SYSLOG("igfx", "SC: ReadI2COverAUX(), etc. cannot be routed");
}
} else {
SYSLOG("igfx", "SC: Failed to find ReadI2COverAUX(), etc");
patcher.clearError();
}
}
if (blackScreenPatch) {
bool foundSymbol = false;
// Currently it is 10.14.1 and Kaby+...
if (getKernelVersion() >= KernelVersion::Mojave && cpuGeneration >= CPUInfo::CpuGeneration::KabyLake) {
KernelPatcher::RouteRequest request("__ZN31AppleIntelFramebufferController16ComputeLaneCountEPK29IODetailedTimingInformationV2jPj", wrapComputeLaneCountNouveau, orgComputeLaneCount);
foundSymbol = patcher.routeMultiple(index, &request, 1, address, size);
}
if (!foundSymbol) {
KernelPatcher::RouteRequest request("__ZN31AppleIntelFramebufferController16ComputeLaneCountEPK29IODetailedTimingInformationV2jjPj", wrapComputeLaneCount, orgComputeLaneCount);
patcher.routeMultiple(index, &request, 1, address, size);
}
}
if (applyFramebufferPatch || dumpFramebufferToDisk || dumpPlatformTable || hdmiAutopatch) {
framebufferStart = reinterpret_cast<uint8_t *>(address);
framebufferSize = size;
if (cpuGeneration >= CPUInfo::CpuGeneration::SandyBridge) {
if (cpuGeneration == CPUInfo::CpuGeneration::SandyBridge) {
gPlatformListIsSNB = true;
gPlatformInformationList = patcher.solveSymbol<void *>(index, "_PlatformInformationList", address, size);
} else {
gPlatformListIsSNB = false;
gPlatformInformationList = patcher.solveSymbol<void *>(index, "_gPlatformInformationList", address, size);
}
DBGLOG("igfx", "platform is snb %d and list " PRIKADDR, gPlatformListIsSNB, CASTKADDR(gPlatformInformationList));
}
if ((gPlatformInformationList && cpuGeneration >= CPUInfo::CpuGeneration::SandyBridge) || cpuGeneration == CPUInfo::CpuGeneration::Westmere) {
auto fbGetOSInformation = "__ZN31AppleIntelFramebufferController16getOSInformationEv";
if (cpuGeneration == CPUInfo::CpuGeneration::Westmere)
fbGetOSInformation = "__ZN22AppleIntelHDGraphicsFB16getOSInformationEv";
else if (cpuGeneration == CPUInfo::CpuGeneration::SandyBridge)
fbGetOSInformation = "__ZN23AppleIntelSNBGraphicsFB16getOSInformationEv";
else if (cpuGeneration == CPUInfo::CpuGeneration::IvyBridge)
fbGetOSInformation = "__ZN25AppleIntelCapriController16getOSInformationEv";
else if (cpuGeneration == CPUInfo::CpuGeneration::Haswell)
fbGetOSInformation = "__ZN24AppleIntelAzulController16getOSInformationEv";
else if (cpuGeneration == CPUInfo::CpuGeneration::Broadwell)
fbGetOSInformation = "__ZN22AppleIntelFBController16getOSInformationEv";
KernelPatcher::RouteRequest request(fbGetOSInformation, wrapGetOSInformation, orgGetOSInformation);
patcher.routeMultiple(index, &request, 1, address, size);
} else if (cpuGeneration >= CPUInfo::CpuGeneration::SandyBridge) {
SYSLOG("igfx", "failed to obtain gPlatformInformationList pointer with code %d", patcher.getError());
patcher.clearError();
}
if (applyFramebufferPatch && cpuGeneration == CPUInfo::CpuGeneration::Westmere)
applyWestmerePatches(patcher);
}
return true;
}
return false;
}
IOReturn IGFX::wrapPavpSessionCallback(void *intelAccelerator, int32_t sessionCommand, uint32_t sessionAppId, uint32_t *a4, bool flag) {
//DBGLOG("igfx, "pavpCallback: cmd = %d, flag = %d, app = %u, a4 = %s", sessionCommand, flag, sessionAppId, a4 == nullptr ? "null" : "not null");
if (sessionCommand == 4) {
DBGLOG("igfx", "pavpSessionCallback: enforcing error on cmd 4 (send to ring?)!");
return kIOReturnTimeout; // or kIOReturnSuccess
}
return FunctionCast(wrapPavpSessionCallback, callbackIGFX->orgPavpSessionCallback)(intelAccelerator, sessionCommand, sessionAppId, a4, flag);
}
bool IGFX::globalPageTableRead(void *hardwareGlobalPageTable, uint64_t address, uint64_t &physAddress, uint64_t &flags) {
uint64_t pageNumber = address >> PAGE_SHIFT;
uint64_t pageEntry = getMember<uint64_t *>(hardwareGlobalPageTable, 0x28)[pageNumber];
// PTE: Page Table Entry for 4KB Page, page 82:
// https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-kbl-vol05-memory_views.pdf.
physAddress = pageEntry & 0x7FFFFFF000ULL; // HAW-1:12, where HAW is 39.
flags = pageEntry & PAGE_MASK; // 11:0
// Relevant flag bits are as follows:
// 2 Ignored Ignored (h/w does not care about values behind ignored registers)
// 1 R/W: Read/Write Write permission rights. If 0, write permission not granted for requests with user-level privilege
// (and requests with supervisor-level privilege, if WPE=1 in the relevant extended-context-entry) to
// the memory region controlled by this entry. See a later section for access rights.
// GPU does not support Supervisor mode contexts.
// 0 P: Present This bit must be “1” to point to a valid Page.
//
// In 10.14.4b1 the return condition changed from (flags & 7U) != 0 to (flags & 1U) != 0. The change makes good sense to me, but
// it results in crashes on 10.14.4b1 on many ASUS Z170 and Z270 boards with connector-less IGPU framebuffer.
// The reason for that is that __ZNK31IGHardwarePerProcessPageTable6422readDescriptorForRangeERK14IGAddressRangePPN10IGPagePool14PageDescriptorE
// unconditionally returns true but actually returns NULL PageDescriptor, which subsequently results in OSAddAtomic64(&this->counter)
// __ZN31IGHardwarePerProcessPageTable6421mapDescriptorForRangeERK14IGAddressRangePN10IGPagePool14PageDescriptorE writing to invalid address.
//
// Fault CR2: 0x0000000000000028, Error code: 0x0000000000000002, Fault CPU: 0x1, PL: 0, VF: 0
// 0xffffff821885b8f0 : 0xffffff801d3c7dc4 mach_kernel : _OSAddAtomic64 + 0x4
// 0xffffff821885b9e0 : 0xffffff7f9f3f1845 com.apple.driver.AppleIntelKBLGraphics :
// __ZN31IGHardwarePerProcessPageTable6421mapDescriptorForRangeERK14IGAddressRangePN10IGPagePool14PageDescriptorE + 0x6b
// 0xffffff821885ba20 : 0xffffff7f9f40a3c3 com.apple.driver.AppleIntelKBLGraphics :
// __ZN29IGHardwarePerProcessPageTable25synchronizePageDescriptorEPKS_RK14IGAddressRangeb + 0x51
// 0xffffff821885ba50 : 0xffffff7f9f40a36b com.apple.driver.AppleIntelKBLGraphics :
// __ZN29IGHardwarePerProcessPageTable15synchronizeWithIS_EEvPKT_RK14IGAddressRangeb + 0x37
// 0xffffff821885ba70 : 0xffffff7f9f3b1716 com.apple.driver.AppleIntelKBLGraphics : __ZN15IGMemoryManager19newPageTableForTaskEP11IGAccelTask + 0x98
// 0xffffff821885baa0 : 0xffffff7f9f40a716 com.apple.driver.AppleIntelKBLGraphics : __ZN11IGAccelTask15initWithOptionsEP16IntelAccelerator + 0x108
// 0xffffff821885bad0 : 0xffffff7f9f40a5f7 com.apple.driver.AppleIntelKBLGraphics : __ZN11IGAccelTask11withOptionsEP16IntelAccelerator + 0x31
// 0xffffff821885baf0 : 0xffffff7f9f3bfaf0 com.apple.driver.AppleIntelKBLGraphics : __ZN16IntelAccelerator17createUserGPUTaskEv + 0x30
// 0xffffff821885bb10 : 0xffffff7f9f2f7520 com.apple.iokit.IOAcceleratorFamily2 : __ZN14IOAccelShared24initEP22IOGraphicsAccelerator2P4task + 0x2e
// 0xffffff821885bb50 : 0xffffff7f9f30c157 com.apple.iokit.IOAcceleratorFamily2 : __ZN22IOGraphicsAccelerator212createSharedEP4task + 0x33
// 0xffffff821885bb80 : 0xffffff7f9f2faa95 com.apple.iokit.IOAcceleratorFamily2 : __ZN24IOAccelSharedUserClient211sharedStartEv + 0x2b
// 0xffffff821885bba0 : 0xffffff7f9f401ca2 com.apple.driver.AppleIntelKBLGraphics : __ZN23IGAccelSharedUserClient11sharedStartEv + 0x16
// 0xffffff821885bbc0 : 0xffffff7f9f2f8aaa com.apple.iokit.IOAcceleratorFamily2 : __ZN24IOAccelSharedUserClient25startEP9IOService + 0x9c
// 0xffffff821885bbf0 : 0xffffff7f9f30ba3c com.apple.iokit.IOAcceleratorFamily2 : __ZN22IOGraphicsAccelerator213newUserClientEP4taskPvjPP12IOUserClient + 0x43e
// 0xffffff821885bc80 : 0xffffff801d42a040 mach_kernel : __ZN9IOService13newUserClientEP4taskPvjP12OSDictionaryPP12IOUserClient + 0x30
// 0xffffff821885bcd0 : 0xffffff801d48ef9a mach_kernel : _is_io_service_open_extended + 0x10a
// 0xffffff821885bd30 : 0xffffff801ce96b52 mach_kernel : _iokit_server_routine + 0x58d2
// 0xffffff821885bd80 : 0xffffff801cdb506c mach_kernel : _ipc_kobject_server + 0x12c
// 0xffffff821885bdd0 : 0xffffff801cd8fa91 mach_kernel : _ipc_kmsg_send + 0xd1
// 0xffffff821885be50 : 0xffffff801cda42fe mach_kernel : _mach_msg_overwrite_trap + 0x3ce
// 0xffffff821885bef0 : 0xffffff801cec3e87 mach_kernel : _mach_call_munger64 + 0x257
// 0xffffff821885bfa0 : 0xffffff801cd5d2c6 mach_kernel : _hndl_mach_scall64 + 0x16
//
// Even so the change makes good sense to me, and most likely the real bug is elsewhere. The change workarounds the issue by also checking
// for the W (writeable) bit in addition to P (present). Presumably this works because some code misuses ::read method to iterate
// over page table instead of obtaining valid mapped physical address.
return (flags & 3U) != 0;
}
bool IGFX::wrapComputeLaneCount(void *that, void *timing, uint32_t bpp, int32_t availableLanes, int32_t *laneCount) {
DBGLOG("igfx", "computeLaneCount: bpp = %u, available = %d", bpp, availableLanes);
// It seems that AGDP fails to properly detect external boot monitors. As a result computeLaneCount
// is mistakengly called for any boot monitor (e.g. HDMI/DVI), while it is only meant to be used for
// DP (eDP) displays. More details could be found at:
// https://github.com/vit9696/Lilu/issues/27#issuecomment-372103559
// Since the only problematic function is AppleIntelFramebuffer::validateDetailedTiming, there are
// multiple ways to workaround it.
// 1. In 10.13.4 Apple added an additional extended timing validation call, which happened to be
// guardded by a HDMI 2.0 enable boot-arg, which resulted in one bug fixing the other, and 10.13.5
// broke it again.
// 2. Another good way is to intercept AppleIntelFramebufferController::RegisterAGDCCallback and
// make sure AppleGraphicsDevicePolicy::_VendorEventHandler returns mode 2 (not 0) for event 10.
// 3. Disabling AGDC by nopping AppleIntelFramebufferController::RegisterAGDCCallback is also fine.
// Simply returning true from computeLaneCount and letting 0 to be compared against zero so far was
// least destructive and most reliable. Let's stick with it until we could solve more problems.
bool r = FunctionCast(wrapComputeLaneCount, callbackIGFX->orgComputeLaneCount)(that, timing, bpp, availableLanes, laneCount);
if (!r && *laneCount == 0) {
DBGLOG("igfx", "reporting worked lane count (legacy)");
r = true;
}
return r;
}
bool IGFX::wrapComputeLaneCountNouveau(void *that, void *timing, int32_t availableLanes, int32_t *laneCount) {
bool r = FunctionCast(wrapComputeLaneCountNouveau, callbackIGFX->orgComputeLaneCount)(that, timing, availableLanes, laneCount);
if (!r && *laneCount == 0) {
DBGLOG("igfx", "reporting worked lane count (nouveau)");
r = true;
}
return r;
}
OSObject *IGFX::wrapCopyExistingServices(OSDictionary *matching, IOOptionBits inState, IOOptionBits options) {
if (matching && inState == kIOServiceMatchedState && options == 0) {
auto name = OSDynamicCast(OSString, matching->getObject(gIONameMatchKey));
if (name) {
DBGLOG("igfx", "found matching request by name %s", name->getCStringNoCopy());
if (name->isEqualTo("Gen6Accelerator")) {
DBGLOG("igfx", "found and fixed Gen6Accelerator request");
auto accel = OSString::withCString("IntelAccelerator");
if (accel) {
matching->setObject(gIONameMatchKey, accel);
accel->release();
}
}
}
}
return FunctionCast(wrapCopyExistingServices, callbackIGFX->orgCopyExistingServices)(matching, inState, options);
}
bool IGFX::wrapAcceleratorStart(IOService *that, IOService *provider) {
if (callbackIGFX->disableAccel)
return false;
OSDictionary* developmentDictCpy {};
if (callbackIGFX->fwLoadMode != FW_APPLE || callbackIGFX->ForceWakeWorkaround.enabled) {
auto developmentDict = OSDynamicCast(OSDictionary, that->getProperty("Development"));
if (developmentDict) {
auto c = developmentDict->copyCollection();
if (c)
developmentDictCpy = OSDynamicCast(OSDictionary, c);
if (c && !developmentDictCpy)
c->release();
}
}
// By default Apple drivers load Apple-specific firmware, which is incompatible.
// On KBL they do it unconditionally, which causes infinite loop.
// On 10.13 there is an option to ignore/load a generic firmware, which we set here.
// On 10.12 it is not necessary.
// On 10.15 an option is differently named but still there.
// There are some laptops that support Apple firmware, for them we want it to be loaded explicitly.
// REF: https://github.com/acidanthera/bugtracker/issues/748
if (callbackIGFX->fwLoadMode != FW_APPLE && developmentDictCpy) {
// 1 - Automatic scheduler (Apple -> fallback to disabled)
// 2 - Force disable via plist (removed as of 10.15)
// 3 - Apple Scheduler
// 4 - Reference Scheduler
// 5 - Host Preemptive (as of 10.15)
uint32_t scheduler;
if (callbackIGFX->fwLoadMode == FW_GENERIC)
scheduler = 4;
else if (getKernelVersion() >= KernelVersion::Catalina)
scheduler = 5;
else
scheduler = 2;
auto num = OSNumber::withNumber(scheduler, 32);
if (num) {
developmentDictCpy->setObject("GraphicsSchedulerSelect", num);
num->release();
}
}
// 0: Framebuffer's SafeForceWake
// 1: IntelAccelerator::SafeForceWakeMultithreaded (or ForceWakeWorkaround when enabled)
// The default is 1. Forcing 0 will result in hangs (due to misbalanced number of calls?)
if (callbackIGFX->ForceWakeWorkaround.enabled && developmentDictCpy) {
auto num = OSNumber::withNumber(1ull, 32);
if (num) {
developmentDictCpy->setObject("MultiForceWakeSelect", num);
num->release();
}
}
if (developmentDictCpy) {
that->setProperty("Development", developmentDictCpy);
developmentDictCpy->release();
}
OSObject *metalPluginName = that->getProperty("MetalPluginName");
if (metalPluginName) {
metalPluginName->retain();
}
if (callbackIGFX->forceOpenGL) {
DBGLOG("igfx", "disabling metal support");
that->removeProperty("MetalPluginClassName");
that->removeProperty("MetalPluginName");
that->removeProperty("MetalStatisticsName");
}
if (callbackIGFX->moderniseAccelerator)
that->setName("IntelAccelerator");
bool ret = FunctionCast(wrapAcceleratorStart, callbackIGFX->orgAcceleratorStart)(that, provider);
if (metalPluginName) {
if (callbackIGFX->forceMetal) {
DBGLOG("igfx", "enabling metal support");
that->setProperty("MetalPluginName", metalPluginName);
}
metalPluginName->release();
}
return ret;
}
bool IGFX::wrapHwRegsNeedUpdate(void *controller, IOService *framebuffer, void *displayPath, void *crtParams, void *detailedInfo) {
// The framebuffer controller can perform panel fitter, partial, or a
// complete modeset (see AppleIntelFramebufferController::hwSetMode).
// In a dual-monitor CFL DVI+HDMI setup, only HDMI output was working after
// boot: it was observed that for HDMI framebuffer a complete modeset
// eventually occured, but for DVI it never did until after sleep and wake
// sequence.
//
// Function AppleIntelFramebufferController::hwRegsNeedUpdate checks
// whether a complete modeset needs to be issued. It does so by comparing
// sets of pipes and transcoder parameters. For some reason, the result was
// never true in the above scenario, so a complete modeset never occured.
// Consequently, AppleIntelFramebufferController::LightUpTMDS was never
// called for that framebuffer.
//
// Patching hwRegsNeedUpdate to always return true seems to be a rather
// safe solution to that. Note that the root cause of the problem is
// somewhere deeper.
// On older Skylake versions this function has no detailedInfo and does not use framebuffer argument.
// As a result the compiler does not pass framebuffer to the target function. Since the fix is disabled
// by default for Skylake, just force complete modeset on all framebuffers when actually requested.
if (callbackIGFX->forceCompleteModeset.legacy)
return true;
// Either this framebuffer is in override list
if (callbackIGFX->forceCompleteModeset.customised) {
return callbackIGFX->forceCompleteModeset.inList(framebuffer)
|| FunctionCast(callbackIGFX->wrapHwRegsNeedUpdate, callbackIGFX->orgHwRegsNeedUpdate)(
controller, framebuffer, displayPath, crtParams, detailedInfo);
}
// Or it is not built-in, as indicated by AppleBacklightDisplay setting property "built-in" for
// this framebuffer.
// Note we need to check this at every invocation, as this property may reappear
return !framebuffer->getProperty("built-in")
|| FunctionCast(callbackIGFX->wrapHwRegsNeedUpdate, callbackIGFX->orgHwRegsNeedUpdate)(
controller, framebuffer, displayPath, crtParams, detailedInfo);
}
IOReturn IGFX::wrapFBClientDoAttribute(void *fbclient, uint32_t attribute, unsigned long *unk1, unsigned long unk2, unsigned long *unk3, unsigned long *unk4, void *externalMethodArguments) {
if (attribute == kAGDCRegisterCallback) {
DBGLOG("igfx", "ignoring AGDC registration in FBClientControl::doAttribute");
return kIOReturnUnsupported;
}
return FunctionCast(wrapFBClientDoAttribute, callbackIGFX->orgFBClientDoAttribute)(fbclient, attribute, unk1, unk2, unk3, unk4, externalMethodArguments);
}
/**
* Apparently, platforms with (ig-platform-id & 0xf != 0) have only Type C connectivity.
* Framebuffer kext uses this fact to sanitise connector type, forcing it to DP.
* This breaks many systems, so we undo this check.
* Affected drivers: KBL and newer?
*/
uint64_t IGFX::wrapIsTypeCOnlySystem(void*) {
DBGLOG("igfx", "Forcing IsTypeCOnlySystem 0");
return 0;
}
uint32_t IGFX::wrapGetDisplayStatus(IOService *framebuffer, void *displayPath) {
// 0 - offline, 1 - online, 2 - empty dongle.
uint32_t ret = FunctionCast(wrapGetDisplayStatus, callbackIGFX->orgGetDisplayStatus)(framebuffer, displayPath);
if (ret != 1) {
if (callbackIGFX->forceOnlineDisplay.customised)
ret = callbackIGFX->forceOnlineDisplay.inList(framebuffer) ? 1 : ret;
else
ret = 1;
}
DBGLOG("igfx", "getDisplayStatus forces %u", ret);
return ret;
}
IOReturn IGFX::wrapReadAUX(void *that, IORegistryEntry *framebuffer, uint32_t address, uint16_t length, void *buffer, void *displayPath) {
//
// Abstract:
//
// Several fields in an `AppleIntelFramebuffer` instance are left zeroed because of
// an invalid value of maximum link rate reported by DPCD of the builtin display.
//
// One of those fields, namely the number of lanes, is later used as a divisor during
// the link training, resulting in a kernel panic triggered by a divison-by-zero.
//
// DPCD are retrieved from the display via a helper function named ReadAUX().
// This wrapper function checks whether the driver is reading receiver capabilities
// from DPCD of the builtin display and then provides a custom maximum link rate value,
// so that we don't need to update the binary patch on each system update.
//
// If you are interested in the story behind this fix, take a look at my blog posts.
// Phase 1: https://www.firewolf.science/2018/10/coffee-lake-intel-uhd-graphics-630-on-macos-mojave-a-compromise-solution-to-the-kernel-panic-due-to-division-by-zero-in-the-framebuffer-driver/
// Phase 2: https://www.firewolf.science/2018/11/coffee-lake-intel-uhd-graphics-630-on-macos-mojave-a-nearly-ultimate-solution-to-the-kernel-panic-due-to-division-by-zero-in-the-framebuffer-driver/
// Call the original ReadAUX() function to read from DPCD
IOReturn retVal = callbackIGFX->orgReadAUX(that, framebuffer, address, length, buffer, displayPath);
// Guard: Check the DPCD register address
// The first 16 fields of the receiver capabilities reside at 0x0 (DPCD Register Address)
if (address != DPCD_DEFAULT_ADDRESS && address != DPCD_EXTENDED_ADDRESS)
return retVal;
// The driver tries to read the first 16 bytes from DPCD (0x0000) or extended DPCD (0x2200)
// Get the current framebuffer index (An UInt32 field at 0x1dc in a framebuffer instance)
// We read the value of "IOFBDependentIndex" instead of accessing that field directly