Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

The wallpaper as one picture, the panel written behind its scan

yehorkaa348613f22856
diff --git a/userland/build.sh b/userland/build.sh
index e7afb01..cd9ae90 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -240,7 +240,7 @@ if [ -d $DARWIN/rootfs/usr/lib ]; then
# our library for inside stock Darwin programs (the jobs in INJECT are started with it)
$DYN -dynamiclib -install_name /redwood/lib/libhakios.dylib -framework CoreFoundation -framework IOKit -lobjc \
-o obj/libhakios.dylib src/inject.c
- $DYN -dynamiclib -install_name /redwood/lib/libhakios.sb.dylib -framework CoreFoundation -framework CoreGraphics -framework IOKit -lobjc \
+ $DYN -dynamiclib -install_name /redwood/lib/libhakios.sb.dylib -framework CoreFoundation -framework CoreGraphics -framework IOKit -framework IOSurface -lobjc \
-o obj/libhakios.sb.dylib src/inject_sb.c
# ... the tweak loader of the package manager's prefix (src/inject_tweaks.c): it goes into a
# program either as the one library the kernel inserts or opened by a library of ours
diff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.c
index afc2f54..6eed30f 100644
--- a/userland/src/inject_sb.c
+++ b/userland/src/inject_sb.c
@@ -33,6 +33,7 @@
*/
#include <CoreFoundation/CoreFoundation.h>
#include <CoreGraphics/CoreGraphics.h>
+#include <IOSurface/IOSurfaceRef.h>
#include <time.h>
#include <IOKit/IOKitLib.h>
#include <dispatch/dispatch.h>
@@ -904,101 +905,192 @@ wallpaper_cache_pass(void)
/*
* Boot-arg wallpaper_freeze=1: the wallpaper as one still picture. Rasterizing its window (wallpaper_cache=1) did not
- * keep it from being composed again: the poster is another process's layers (PosterBoard's, through a layer host),
- * and the window server rasterizes them again whenever that process commits -- the Collections poster's gradients
- * (a 256 x 1 half-float ramp and a 32 x 32 dither each) were still drawn 3509 times in a run, at 0.6 ms each, and the
- * rasterized copy 1460 times at 1.2 to 3.2 ms (3 November, metal_fps=draws). So once the poster has been drawn (30 s
- * on), the window is drawn into an image by the window server (-drawViewHierarchyInRect:afterScreenUpdates:, which
- * renders other processes' layers too), the image is put in the window as one opaque view, and what was there is
- * hidden: one full-screen texture a frame instead of eight to twelve layers. What that gives up: the wallpaper does
- * not change any more until the next boot (nothing here changes it), nor do the effects drawn in it.
+ * keep it from being composed again: the poster is another process's layers (PosterBoard's, through a layer host), and
+ * its gradients (a 256 x 1 half-float ramp and a 32 x 32 dither each) were still drawn 3509 times in a run at 0.6 ms
+ * each, the rasterized copy 1460 times at 1.2 to 3.2 ms (3 November, metal_fps=draws). The home button's animation came
+ * at 28 frames a second with it and 78 with the wallpaper hidden (wallpaper_freeze=2).
+ *
+ * -drawViewHierarchyInRect: answers one colour for it here, secure window or not. So the picture is what is really on
+ * the panel: at the home screen, with the window of the icons hidden for a moment (they blink once per boot), the pixels of the IOSurface the window server last showed (kern.hakios.fb_surface) become one opaque view in
+ * the wallpaper's window, and what was there is hidden. What that gives up: the wallpaper does not change until the
+ * next boot, and the lock screen shows the same picture.
*/
typedef struct { double x, y, width, height; } hk_rect;
-typedef struct { double width, height; } hk_size;
static bool wallpaper_hide_only; /* wallpaper_freeze=2: no picture, the wallpaper hidden (what it costs, measured) */
+static const void *wallpaper_frozen_key = &wallpaper_frozen_key;
-static void
-wallpaper_freeze_pass(unsigned attempt)
+static id
+wallpaper_window(void)
{
- void *uikit = dlopen("/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore", RTLD_NOW | RTLD_NOLOAD);
- void (*begin)(hk_size, bool, double) = uikit ? (void (*)(hk_size, bool, double))dlsym(uikit, "UIGraphicsBeginImageContextWithOptions") : NULL;
- id (*grab)(void) = uikit ? (id (*)(void))dlsym(uikit, "UIGraphicsGetImageFromCurrentImageContext") : NULL;
- void (*end)(void) = uikit ? (void (*)(void))dlsym(uikit, "UIGraphicsEndImageContext") : NULL;
id app = SEND(id, objc_getClass("UIApplication"), "sharedApplication");
id windows = app != NULL ? SEND(id, app, "windows") : NULL;
unsigned long count = windows != NULL ? SEND(unsigned long, windows, "count") : 0;
- id screen = SEND(id, objc_getClass("UIScreen"), "mainScreen");
- double scale = screen != NULL ? ((double (*)(id, SEL))objc_msgSend)(screen, sel_registerName("scale")) : 3.0;
- unsigned frozen = 0;
- if (begin == NULL || grab == NULL || end == NULL) {
- say("hakios: SpringBoard: wallpaper_freeze=1: no UIGraphics image context\n");
- return;
- }
for (unsigned long i = 0; i < count; i++) {
id window = ((id (*)(id, SEL, unsigned long))objc_msgSend)(windows, sel_registerName("objectAtIndex:"), i);
const char *name = object_getClassName(window);
- if (strcasestr(name, "wallpaper") == NULL && strcasestr(name, "poster") == NULL) {
- continue;
- }
- if (objc_getAssociatedObject(window, (const void *)wallpaper_freeze_pass) != NULL) {
- continue; /* (frozen already) */
+ if (strcasestr(name, "wallpaper") != NULL || strcasestr(name, "poster") != NULL) {
+ return window;
}
- hk_rect bounds = ((hk_rect (*)(id, SEL))objc_msgSend)(window, sel_registerName("bounds"));
- if (bounds.width < 100 || bounds.height < 100) {
- continue;
- }
- /* a secure window is left out of every picture taken of the screen (and so of this one): not this one */
- if (class_respondsToSelector(object_getClass(window), sel_registerName("_setSecure:"))) {
- ((void (*)(id, SEL, BOOL))objc_msgSend)(window, sel_registerName("_setSecure:"), NO);
- }
- begin((hk_size){ bounds.width, bounds.height }, true, scale);
- BOOL drawn = ((BOOL (*)(id, SEL, hk_rect, BOOL))objc_msgSend)(window, sel_registerName("drawViewHierarchyInRect:afterScreenUpdates:"),
- bounds, attempt > 0); /* (from the second on, after the window server has drawn it as not secure) */
- id image = grab();
- end();
- /* a picture that is all one colour is no wallpaper (nothing was drawn yet, or the window server could not): later */
- unsigned long distinct = 0;
- CGImageRef cg = image != NULL ? SEND(CGImageRef, image, "CGImage") : NULL;
- CFDataRef data = cg != NULL ? CGDataProviderCopyData(CGImageGetDataProvider(cg)) : NULL;
- if (data != NULL) {
- const uint32_t *px = (const uint32_t *)CFDataGetBytePtr(data);
- size_t n = (size_t)CFDataGetLength(data) / 4;
- uint32_t first = n ? px[0] : 0;
-
- for (size_t k = 0; k < n; k += n / 97 + 1) {
- distinct += px[k] != first;
- }
- CFRelease(data);
+ }
+ return NULL;
+}
+
+/* A picture of the surface on the panel, opaque, in points of the screen's scale; NULL: none, or all one colour. */
+static id
+wallpaper_picture(double scale)
+{
+ uint32_t sid = 0;
+ size_t size = sizeof(sid);
+ IOSurfaceRef surface;
+ id image = NULL;
+
+ if (sysctlbyname("kern.hakios.fb_surface", &sid, &size, NULL, 0) != 0 || sid == 0 ||
+ (surface = IOSurfaceLookup(sid)) == NULL) {
+ say("hakios: SpringBoard: wallpaper_freeze=1: no surface on the panel to read (%u)\n", sid);
+ return NULL;
+ }
+ size_t width = IOSurfaceGetWidth(surface), height = IOSurfaceGetHeight(surface), row = IOSurfaceGetBytesPerRow(surface);
+
+ IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL);
+ CFDataRef pixels = CFDataCreate(NULL, IOSurfaceGetBaseAddress(surface), (CFIndex)(row * height));
+ IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL);
+ unsigned distinct = 0;
+ if (pixels != NULL) {
+ const uint8_t *at = CFDataGetBytePtr(pixels);
+ uint32_t first = *(const uint32_t *)at;
+
+ for (unsigned k = 0; k < 97; k++) {
+ distinct += *(const uint32_t *)(at + (height * k / 97) * row + (width * k / 97) * 4) != first;
}
- say("hakios: SpringBoard: wallpaper_freeze=1: %s (%gx%g) drawn %s, %lu of 97 samples unlike the first\n", name,
- bounds.width, bounds.height, drawn ? "yes" : "no", distinct);
- if (!wallpaper_hide_only && (!drawn || distinct < 10)) {
- continue;
+ }
+ say("hakios: SpringBoard: wallpaper_freeze=1: surface %u, %zux%zu, %zu bytes a row, format %#x: %u of 97 samples unlike the first (%#x)\n",
+ sid, width, height, row, IOSurfaceGetPixelFormat(surface), distinct, pixels != NULL ? *(const uint32_t *)CFDataGetBytePtr(pixels) : 0);
+ if (pixels != NULL && distinct >= 10) {
+ CGDataProviderRef provider = CGDataProviderCreateWithCFData(pixels);
+ CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
+ CGImageRef cg = CGImageCreate(width, height, 8, 32, row, space, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
+ provider, NULL, false, kCGRenderingIntentDefault);
+
+ if (cg != NULL) {
+ image = ((id (*)(id, SEL, CGImageRef, double, long))objc_msgSend)((id)objc_getClass("UIImage"),
+ sel_registerName("imageWithCGImage:scale:orientation:"), cg, scale, 0L);
+ CGImageRelease(cg);
}
- id view = ((id (*)(id, SEL, id))objc_msgSend)(SEND(id, objc_getClass("UIImageView"), "alloc"), sel_registerName("initWithImage:"), image);
+ CGColorSpaceRelease(space);
+ CGDataProviderRelease(provider);
+ }
+ if (pixels != NULL) {
+ CFRelease(pixels);
+ }
+ CFRelease(surface);
+ return image;
+}
+
+/* The picture into the wallpaper's window, in place of what was shown there (none: only hidden). */
+static void
+wallpaper_put(id window, id image)
+{
+ id layer = SEND(id, window, "layer");
+ id sublayers = SEND(id, SEND(id, layer, "sublayers"), "copy");
+ unsigned long count = sublayers != NULL ? SEND(unsigned long, sublayers, "count") : 0;
+ hk_rect bounds = ((hk_rect (*)(id, SEL))objc_msgSend)(window, sel_registerName("bounds"));
+
+ if (image != NULL) {
+ id view = ((id (*)(id, SEL, id))objc_msgSend)(SEND(id, objc_getClass("UIImageView"), "alloc"),
+ sel_registerName("initWithImage:"), image);
+
((void (*)(id, SEL, hk_rect))objc_msgSend)(view, sel_registerName("setFrame:"), bounds);
((void (*)(id, SEL, BOOL))objc_msgSend)(view, sel_registerName("setOpaque:"), YES);
- id layer = SEND(id, window, "layer");
- id sublayers = SEND(id, SEND(id, layer, "sublayers"), "copy");
- unsigned long nsub = sublayers != NULL ? SEND(unsigned long, sublayers, "count") : 0;
((void (*)(id, SEL, id))objc_msgSend)(window, sel_registerName("addSubview:"), view);
- for (unsigned long k = 0; k < nsub; k++) {
- id sub = ((id (*)(id, SEL, unsigned long))objc_msgSend)(sublayers, sel_registerName("objectAtIndex:"), k);
- ((void (*)(id, SEL, BOOL))objc_msgSend)(sub, sel_registerName("setHidden:"), YES);
+ objc_setAssociatedObject(window, wallpaper_frozen_key, view, OBJC_ASSOCIATION_RETAIN);
+ } else {
+ objc_setAssociatedObject(window, wallpaper_frozen_key, window, OBJC_ASSOCIATION_ASSIGN);
+ }
+ for (unsigned long k = 0; k < count; k++) {
+ id sub = ((id (*)(id, SEL, unsigned long))objc_msgSend)(sublayers, sel_registerName("objectAtIndex:"), k);
+
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(sub, sel_registerName("setHidden:"), YES);
+ }
+ say("hakios: SpringBoard: wallpaper_freeze: %s %s (%lu layers hidden)\n", object_getClassName(window),
+ image != NULL ? "is one picture now" : "hidden", count);
+}
+
+/* Whether the home screen is what is showing: unlocked, no application in front. */
+static bool
+wallpaper_home_showing(void)
+{
+ Class manager = objc_getClass("SBLockScreenManager");
+ id shared = manager != NULL ? SEND(id, manager, "sharedInstance") : NULL;
+ id app = SEND(id, objc_getClass("UIApplication"), "sharedApplication");
+
+ if (shared == NULL || SEND(BOOL, shared, "isUILocked")) {
+ return false;
+ }
+ /* (a selector nobody answers would abort SpringBoard: unlocked is then all that is known) */
+ if (app == NULL || !class_respondsToSelector(object_getClass(app), sel_registerName("_accessibilityFrontMostApplication"))) {
+ return app != NULL;
+ }
+ return SEND(id, app, "_accessibilityFrontMostApplication") == NULL;
+}
+
+static void
+wallpaper_freeze_pass(unsigned attempt)
+{
+ id window = wallpaper_window();
+ id screen = SEND(id, objc_getClass("UIScreen"), "mainScreen");
+ double scale = screen != NULL ? ((double (*)(id, SEL))objc_msgSend)(screen, sel_registerName("scale")) : 3.0;
+
+ if (window != NULL && objc_getAssociatedObject(window, wallpaper_frozen_key) != NULL) {
+ return;
+ }
+ if (window == NULL || !wallpaper_home_showing()) {
+ if (attempt < 720) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ wallpaper_freeze_pass(attempt + 1);
+ });
+ }
+ return;
+ }
+ if (wallpaper_hide_only) {
+ wallpaper_put(window, NULL);
+ return;
+ }
+ /* the icons out of the way until the window server has drawn the wallpaper without them */
+ id app = SEND(id, objc_getClass("UIApplication"), "sharedApplication");
+ id windows = SEND(id, app, "windows");
+ unsigned long count = SEND(unsigned long, windows, "count");
+ CFMutableArrayRef hidden = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
+
+ for (unsigned long i = 0; i < count; i++) {
+ id other = ((id (*)(id, SEL, unsigned long))objc_msgSend)(windows, sel_registerName("objectAtIndex:"), i);
+
+ /*
+ * Only the window of the icons and the dock: with SpringBoard's other windows hidden as well the screen was all
+ * black (0xff000000 in all 97 samples, 4 November), the wallpaper gone with them.
+ */
+ if (strcmp(object_getClassName(other), "SBHomeScreenWindow") == 0 && !SEND(BOOL, other, "isHidden")) {
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(other, sel_registerName("setHidden:"), YES);
+ CFArrayAppendValue(hidden, other);
}
- ((void (*)(id, SEL, BOOL))objc_msgSend)(layer, sel_registerName("setShouldRasterize:"), NO);
- objc_setAssociatedObject(window, (const void *)wallpaper_freeze_pass, view, OBJC_ASSOCIATION_RETAIN);
- say("hakios: SpringBoard: wallpaper_freeze=1: %s is one picture now (%lu layers hidden)\n", name, nsub);
- frozen++;
- }
- if (attempt < 12) {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
- wallpaper_freeze_pass(attempt + 1);
- });
}
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 300 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
+ id image = wallpaper_picture(scale);
+
+ for (CFIndex i = 0; i < CFArrayGetCount(hidden); i++) {
+ ((void (*)(id, SEL, BOOL))objc_msgSend)((id)CFArrayGetValueAtIndex(hidden, i), sel_registerName("setHidden:"), NO);
+ }
+ CFRelease(hidden);
+ if (image != NULL) {
+ wallpaper_put(window, image);
+ } else if (attempt < 720) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ wallpaper_freeze_pass(attempt + 1);
+ });
+ }
+ });
}
static void
@@ -1014,7 +1106,7 @@ wallpaper_freeze(void)
return;
}
wallpaper_hide_only = argument[17] == '2';
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
wallpaper_freeze_pass(0);
});
}
diff --git a/userland/src/rwtouch.c b/userland/src/rwtouch.c
index 9dd7411..db138ad 100644
--- a/userland/src/rwtouch.c
+++ b/userland/src/rwtouch.c
@@ -63,11 +63,8 @@ button(uint32_t which, int ms)
}
/*
- * A sample every so many milliseconds. Once 8, what the touch screen was polled at (touch_poll_us=8000): 125 samples a
- * second for a display of 120 refreshes, each arriving 4.6 to 11.9 ms after the last, and a page dragged by them was
- * drawn only when one had come -- a quarter of the frames of a swipe came a refresh late, 100 frames a second where
- * the window server had time for 120 (3 November, touch_lat=1). 4 (touch_poll_us=4000 for the touch screen itself):
- * a sample in every refresh.
+ * A sample every so many milliseconds: 4, a sample in every refresh at 120 Hz (touch_poll_us=4000 for the touch screen
+ * itself). Once 8. Measured (4 November): the frame rate of a swipe is the same with either, 100 to 104 a second.
*/
#define SAMPLE_MS 4
diff --git a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
index dd8e942..4be0e2f 100644
--- a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
+++ b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
@@ -22,6 +22,7 @@
#include <libkern/c++/OSArray.h>
#include <libkern/c++/OSBoolean.h>
#include <kern/thread_call.h>
+#include <sys/sysctl.h>
#include <kern/thread.h>
#include <kern/clock.h>
#include <pexpert/pexpert.h>
@@ -202,6 +203,11 @@ panel_thread_start(thread_continue_t continuation, void * parameter, thread_t *
}
return kernel_thread_start(continuation, parameter, thread);
}
+/* kern.hakios.fb_surface: the IOSurface on the panel, for a picture of what is there (SpringBoard's wallpaper_freeze=1) */
+SYSCTL_DECL(_kern_hakios);
+static uint32_t gShownSurface;
+SYSCTL_UINT(_kern_hakios, OID_AUTO, fb_surface, CTLFLAG_RD | CTLFLAG_LOCKED, &gShownSurface, 0, "the IOSurface last put on the panel");
+
#define SWAP_QUEUE 2 /* frames that may wait for the panel at most (fb_queue) */
static TUNABLE(uint32_t, gQueue, "fb_queue", 2);
static inline unsigned
@@ -239,6 +245,18 @@ static TUNABLE(uint32_t, gMeasure, "fb_measure", 0);
#define DPU_INTF1_OFFSET 0x2000
#define INTF_TIMING_ENGINE_EN 0x000
#define INTF_FRAME_COUNT 0x0ac
+#define INTF_LINE_COUNT 0x0b0 /* the line the interface is scanning (Linux's dpu_hw_intf.c) */
+/*
+ * Boot-arg fb_beam=0: frames written to the panel's memory whenever their beat comes, as before. The panel reads the
+ * very memory this driver writes (one buffer, and it takes the scan 8.3 ms to read it, this driver 3 to write it): a
+ * frame written across the line being read came out torn, a piece of the last frame and a piece of this one, moving
+ * bands with doubled icons and text wherever something moved (3 November, seen on the phone and in screenshots).
+ * Now each thread's share of the rows waits for the scan to have passed it and is written behind the line being read,
+ * in time for the next scan to read all of the new frame: that scan shows the whole frame, nothing is ever read half
+ * written. The line comes from the interface's own counter; reads only. It is looked at a minute after the driver
+ * starts, with fb_measure's reads, and if it does not count as a line counter should, frames stay on their beat.
+ */
+static TUNABLE(uint32_t, gBeam, "fb_beam", 1);
extern "C" vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
static inline uint32_t refreshHz(void);
@@ -338,6 +356,12 @@ public:
* their beat: neither a slow one nor a quick one then lands on the wrong side of it.
*/
uint64_t fBeat; /* the beat the last frame was shown on */
+ vm_offset_t fBeamIntf; /* fb_beam: the DSI interface's registers, once they were seen to count */
+ uint32_t fBeamLines; /* ... lines of a scan, blanking included */
+ uint64_t fBeamPeriod; /* ... how long a scan takes */
+ uint64_t fBeamScan; /* ... when the scan that shows the frame being written begins */
+ uint64_t fBeamShare; /* ... how long a thread's share of the rows takes to write */
+ uint32_t fStatScans, fStatScansMissed; /* ... frames in time for the next scan, and those that were not */
uint64_t fReady; /* when the last frame was ready to be shown */
uint32_t fStatOnBeat; /* frames that waited for a refresh, and for how long together */
uint32_t fStatSettled; /* frames drawn again, filtered, once they stood still (fb_filter=2) */
@@ -384,6 +408,10 @@ public:
void drawLayer(MiniIOSurface * s, const int32_t * src, const int32_t * dst);
void drawRows(const struct RowJob * job, int32_t y0, int32_t y1, uint32_t * blendRow);
static void helperMain(void * self, wait_result_t result);
+ static void beamProbeMain(void * self, wait_result_t result);
+ void beamProbe(void);
+ uint64_t beamNextScan(uint64_t now);
+ void beamWait(const struct RowJob * job, int32_t lastRow);
/* the scaling shared out (fb_threads): fThreads drawers, the presenter and fThreads - 1 helpers */
unsigned fThreads;
IOLock * fHelperLock;
@@ -514,6 +542,10 @@ IOMobileFramebuffer::start(IOService * provider)
vinfo.v_depth);
return false;
}
+ if (gBeam != 0 && kernel_thread_start(beamProbeMain, this, &thread) == KERN_SUCCESS) {
+ thread_set_thread_name(thread, "the panel's scan: looked at");
+ thread_deallocate(thread);
+ }
if (gMeasure && kernel_thread_start(measurePanel, NULL, &thread) == KERN_SUCCESS) {
thread_deallocate(thread);
}
@@ -754,6 +786,7 @@ struct RowJob {
int32_t sx, sy, sw, sh, px0, py0, px1, py1, cx0, cx1;
int32_t ry0, ry1; /* the rows of the rectangle that are on the panel: all that is looked at, whatever its size */
bool filter, unscaled;
+ uint64_t scan; /* fb_beam: when the scan that is to show the frame begins (0: write at once) */
};
void
@@ -861,6 +894,7 @@ IOMobileFramebuffer::helperMain(void * self, wait_result_t result __unused)
y0 = job->ry0 + (int32_t) ((int64_t) rows * (index + 1) / fb->fThreads);
y1 = job->ry0 + (int32_t) ((int64_t) rows * (index + 2) / fb->fThreads);
blend = fb->fHelperBlend[index];
+ fb->beamWait(job, y1);
fb->drawRows(job, y0, y1, blend);
IOLockLock(fb->fHelperLock);
fb->fHelpersBusy--;
@@ -871,6 +905,106 @@ IOMobileFramebuffer::helperMain(void * self, wait_result_t result __unused)
}
}
+/* fb_beam: whether the interface's counters count as they should, and how many lines and how long a scan is. */
+void
+IOMobileFramebuffer::beamProbeMain(void * self, wait_result_t result __unused)
+{
+ ((IOMobileFramebuffer *) self)->beamProbe();
+}
+
+void
+IOMobileFramebuffer::beamProbe(void)
+{
+ vm_offset_t intf;
+ uint32_t first, frames, line, lines = 0, smallest = ~0u;
+ uint64_t began, ended, until;
+
+ IOSleep(60000);
+ intf = ml_io_map(DPU_INTF1_PAGE, 0x4000) + DPU_INTF1_OFFSET;
+ if (!(*(volatile uint32_t *)(intf + INTF_TIMING_ENGINE_EN) & 1)) {
+ IOLog("MiniIOMobileFramebuffer: fb_beam: the interface's timing engine is off: frames stay on their beat\n");
+ return;
+ }
+ /* a whole number of scans, from one frame's start to another's */
+ first = *(volatile uint32_t *)(intf + INTF_FRAME_COUNT);
+ nanoseconds_to_absolutetime(100 * NSEC_PER_MSEC, &until);
+ until += mach_absolute_time();
+ while (*(volatile uint32_t *)(intf + INTF_FRAME_COUNT) == first && mach_absolute_time() < until) {
+ }
+ began = mach_absolute_time();
+ first = *(volatile uint32_t *)(intf + INTF_FRAME_COUNT);
+ nanoseconds_to_absolutetime(50 * NSEC_PER_MSEC, &until);
+ until += began;
+ while (mach_absolute_time() < until) {
+ line = *(volatile uint32_t *)(intf + INTF_LINE_COUNT);
+ lines = line > lines ? line : lines;
+ smallest = line < smallest ? line : smallest;
+ }
+ IOSleep(450);
+ frames = *(volatile uint32_t *)(intf + INTF_FRAME_COUNT);
+ nanoseconds_to_absolutetime(100 * NSEC_PER_MSEC, &until);
+ until += mach_absolute_time();
+ while (*(volatile uint32_t *)(intf + INTF_FRAME_COUNT) == frames && mach_absolute_time() < until) {
+ }
+ ended = mach_absolute_time();
+ frames = *(volatile uint32_t *)(intf + INTF_FRAME_COUNT) - first;
+ if (frames == 0 || lines < fPanelHeight || lines > fPanelHeight * 2 || smallest > fPanelHeight / 4) {
+ IOLog("MiniIOMobileFramebuffer: fb_beam: the interface's counters do not count as they should (%u frames, lines %u to %u): "
+ "frames stay on their beat\n", frames, smallest, lines);
+ return;
+ }
+ fBeamLines = lines + 1;
+ fBeamPeriod = (ended - began) / frames;
+ absolutetime_to_nanoseconds(fBeamPeriod, &began);
+ IOLog("MiniIOMobileFramebuffer: fb_beam: the panel's scan is %u lines, %llu us: frames are written behind it from now on\n",
+ fBeamLines, began / NSEC_PER_USEC);
+ __atomic_thread_fence(__ATOMIC_RELEASE);
+ fBeamIntf = intf;
+}
+
+/* When the next scan the frame can be whole for begins: the first share has to be written before that scan reaches it. */
+uint64_t
+IOMobileFramebuffer::beamNextScan(uint64_t now)
+{
+ uint32_t line = *(volatile uint32_t *)(fBeamIntf + INTF_LINE_COUNT);
+ uint64_t scan = now - fBeamPeriod * (line < fBeamLines ? line : fBeamLines - 1) / fBeamLines + fBeamPeriod;
+ /*
+ * The first share is written from its top down about as fast as the scan reads it, so it may begin just before the
+ * scan does: by what it takes longer than the scan takes over the same rows, and a little. (Its whole time as a
+ * margin lost a frame in eight: each too late for one scan waits for the next, and all behind it with it.)
+ */
+ uint64_t over = fThreads != 0 ? fBeamPeriod / fThreads : 0;
+ uint64_t margin = (fBeamShare > over ? fBeamShare - over : 0) + fBeamPeriod / 16;
+ bool missed = false;
+
+ if (now + margin > scan) {
+ scan += fBeamPeriod;
+ missed = true;
+ }
+ /* (one frame a scan: the last frame's scan has its own) */
+ while (fBeamScan != 0 && scan < fBeamScan + fBeamPeriod / 2) {
+ scan += fBeamPeriod;
+ }
+ fStatScans++;
+ fStatScansMissed += missed;
+ return scan;
+}
+
+/* fb_beam: a share of the rows that ends at lastRow waits for the scan before the frame's to have passed it. */
+void
+IOMobileFramebuffer::beamWait(const struct RowJob * job, int32_t lastRow)
+{
+ if (job->scan != 0) {
+ /* (the lines of the blanking are counted before the first row, as far as one can tell: taken as a margin either way) */
+ uint64_t lines = (uint64_t) lastRow + (fBeamLines - fPanelHeight);
+ uint64_t passed = job->scan - fBeamPeriod + fBeamPeriod * lines / fBeamLines;
+
+ if (mach_absolute_time() < passed) {
+ clock_delay_until(passed);
+ }
+ }
+}
+
/*
* Put a rectangle of a 32-bit surface on the screen. `dst` is in display coordinates; the
* panel may be of another size, and the layer itself may be scaled: both are done in one
@@ -988,6 +1122,7 @@ IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int
job.ry1 = py1 > (int32_t) fPanelHeight ? (int32_t) fPanelHeight : py1;
job.filter = filter;
job.unscaled = px1 - px0 == sw && py1 - py0 == sh && px0 >= 0 && (uint32_t) px1 <= fPanelWidth;
+ job.scan = fSettling ? 0 : fBeamScan;
if (fThreads <= 1 || fDiff || fHelpersStarted + 1 < fThreads) {
drawRows(&job, job.ry0, job.ry1, fBlendRow);
return;
@@ -999,7 +1134,17 @@ IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int
fHelperGeneration++;
IOLockWakeup(fHelperLock, &fHelperGeneration, false);
IOLockUnlock(fHelperLock);
- drawRows(&job, job.ry0, job.ry0 + (int32_t) ((int64_t) (job.ry1 - job.ry0) / fThreads), fBlendRow);
+ {
+ int32_t last = job.ry0 + (int32_t) ((int64_t) (job.ry1 - job.ry0) / fThreads);
+ uint64_t wrote;
+
+ beamWait(&job, last);
+ wrote = mach_absolute_time();
+ drawRows(&job, job.ry0, last, fBlendRow);
+ wrote = mach_absolute_time() - wrote;
+ /* (on the average, lately: one preempted now and then is no reason to give up a scan every time) */
+ fBeamShare += (int64_t) (wrote - fBeamShare) / 8;
+ }
IOLockLock(fHelperLock);
while (fHelpersBusy != 0) {
IOLockSleep(fHelperLock, &fHelpersBusy, THREAD_UNINT);
@@ -1202,7 +1347,11 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
}
fStatWaiting += mach_absolute_time() - began;
began = ready = mach_absolute_time();
- if (gOnTheBeat) {
+ fBeamScan = fBeamIntf != 0 ? beamNextScan(began) : 0;
+ if (fBeamIntf != 0) {
+ /* (on the panel when that scan reads it: that is the beat now, kept by the panel) */
+ fStatOnBeat++;
+ } else if (gOnTheBeat) {
uint64_t period, aim, next;
nanoseconds_to_absolutetime(NSEC_PER_SEC / refreshHz(), &period);
@@ -1296,6 +1445,7 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
drawLayer(s, src, dst);
if (layer == 0) {
recorded = s; /* (recorded once the frame is in the panel's memory: see below) */
+ gShownSurface = sid;
}
}
}
@@ -1331,10 +1481,11 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
absolutetime_to_nanoseconds(fStatBeatWait, &beat);
IOLog("MiniIOMobileFramebuffer: %u frames in %llu ms (%llu a second), %llu us each in the driver, after %llu us "
"waiting for the GPU and, %u of them, %llu us for the next refresh; %u swaps waited for the frame before, "
- "%u gave up; %u swaps came a refresh late themselves; %u frames drawn again filtered\n", fStatFrames, nanos / NSEC_PER_MSEC,
+ "%u gave up; %u swaps came a refresh late themselves; %u frames drawn again filtered; %u of %u too late for the next scan\n", fStatFrames, nanos / NSEC_PER_MSEC,
fStatFrames * NSEC_PER_SEC / nanos, drawing / fStatFrames / NSEC_PER_USEC,
waiting / fStatFrames / NSEC_PER_USEC, fStatOnBeat, fStatOnBeat ? beat / fStatOnBeat / NSEC_PER_USEC : 0,
- fStatHeld, fStatLost, fStatSwapsLate, fStatSettled);
+ fStatHeld, fStatLost, fStatSwapsLate, fStatSettled, fStatScansMissed, fStatScans);
+ fStatScans = fStatScansMissed = 0;
fStatSwapsLate = 0;
for (different = 0; different < 8 && fStatSurfaces[different] != 0; different++) {
}