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
GPU path: frames on a 60 Hz beat from the display driver's own thread
vcvkk56f87829e72c
diff --git a/README.md b/README.mdindex 7563b55..cbcb46d 100644--- a/README.md+++ b/README.md@@ -174,21 +174,21 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #```shtools/mk-mesa.shGL=1 REST=1 userland/build.sh-XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4 adreno=21 adreno_skip=0x1c00 adreno_pause=0 adreno_keep=1 adreno_speed=3" ./xl run+XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4 adreno=21 adreno_skip=0x1c00 adreno_pause=0 adreno_keep=1" ./xl run```-`adreno_speed=3` — частота GPU 550 МГц (без него 315). При втором и следующих запусках за одну загрузку телефона-добавлять `adreno_zap=0`. Без параметров `adreno…`+При втором и следующих запусках за одну загрузку телефона добавлять `adreno_zap=0`. Без параметров `adreno…`тот же образ рисует программным драйвером Mesa (в QEMU — всегда так).Состояние — опытный режим, не по умолчанию. GPU рисует прямо в память поверхностей (IOSurface экрана и-полноэкранных слоёв — общая с GPU, без копий); на коротком сценарии (разблокировка, прокрутка Настроек, Часы)-это 1277–1319 кадров против 929 у программного рендера на четырёх ядрах, лучшие пять секунд — 52–57 кадров/с-против 35 (`adreno_speed=3`, 550 МГц; без него 315 МГц и 46 кадров/с). Кадр при прокрутке стоит около 19 мс, до-ровных 60 кадров/с ещё не дотянуто. Известные дефекты: приложение «Часы» рисуется чёрным, на домашнем экране под-некоторыми значками бывают лишние треугольники. Прерываний нет (ожидание опросом). GPU выключается при любом-штатном конце сеанса (таймер, `./xl stop`, пять пальцев); после паники с включённым GPU — `./xl reboot`. Приложения, использующие-Metal сами, от этого ничего не получают.+полноэкранных слоёв — общая с GPU, без копий); готовый кадр ждёт GPU и уходит на панель в потоке драйвера экрана,+по его собственному такту 60 Гц. Прокрутка Настроек на телефоне: 56–58 кадров/с, 95–97 % кадров с шагом 16,7 мс+(программный рендер на четырёх ядрах — около 28–35). Короткий сценарий (разблокировка, прокрутка, Часы) — 1383 кадра+против 929. Известные дефекты: на домашнем экране под некоторыми значками торчат лишние треугольные фрагменты;+нет размытой подложки под листом FaceTime; кадр может рваться (копирование в панель не привязано к развёртке).+Прерываний нет (ожидание опросом). GPU выключается при любом штатном конце сеанса (таймер, `./xl stop`, пять+пальцев); после паники с включённым GPU — `./xl reboot`. Приложения, использующие Metal сами, от этого ничего не+получают.## Сборка из исходниковdiff --git a/prebuilt/SHA256SUMS b/prebuilt/SHA256SUMSindex 054d885..2018a53 100644--- a/prebuilt/SHA256SUMS+++ b/prebuilt/SHA256SUMS@@ -1,6 +1,6 @@-Built 2026-10-13 05:22 from this tree.+Built 2026-10-13 07:12 from this tree.-8d9b6f3faec637b1f6e9dce8023db3cb150ad2a311067d575160bdcf5dec1a9c prebuilt/mach.development.bcm2837+2fbbc672ca9eb5ca06ff84aca5ee2b2fcf7eea02198a17bd3e4f10afa51f8e9d prebuilt/mach.development.bcm28371332a598d2dec00a1d8e930044e4f00a12ad44c6e5e50eecf4b7fe7fae803bf2 prebuilt/loader.efid2a35a4a1d6658ffb3696914f727661b52c9333de8a3af8a31642b8023ce03ac prebuilt/userland/child1a413befd511384052e1962c1394adce20f718e1f2657ce63ab09828ebc4bd1b prebuilt/userland/cpu_testdiff --git a/prebuilt/mach.development.bcm2837 b/prebuilt/mach.development.bcm2837index b8c0094..60b4618 100755Binary files a/prebuilt/mach.development.bcm2837 and b/prebuilt/mach.development.bcm2837 differdiff --git a/xnu/files/bsd/dev/redwood_adreno.c b/xnu/files/bsd/dev/redwood_adreno.cindex 061f87b..f78139a 100644--- a/xnu/files/bsd/dev/redwood_adreno.c+++ b/xnu/files/bsd/dev/redwood_adreno.c@@ -3608,19 +3608,32 @@ display_probe(void)announce("turn the bus clock of the display's clock controller on (gcc 0x127004 bit 0: THE ONE WRITE)");put(&gcc, "disp_ahb_cbcr", GCC_DISP_AHB_CBCR, rd(gcc.base + GCC_DISP_AHB_CBCR) | CBCR_ENABLE);sleep_ms(10);- if (get(&gcc, "disp_ahb_cbcr", GCC_DISP_AHB_CBCR) & CBCR_OFF) {- printf("adreno: 0: the display's clock controller has no bus clock, and does not get one: nothing more is read\n");- goto out;- }+ }+ /*+ * Turned on, the register still says the clock is off (seen: 0x8000000b). Its bit 1 is+ * set as the firmware left it: the clock is gated by the hardware itself while nobody+ * talks to the block, and that is what "off" then means. Linux turns the clock on the same+ * way, never looks at this bit and reads the clock controller next; so does this, if the+ * clock is at least asked for.+ */+ if (!(get(&gcc, "disp_ahb_cbcr", GCC_DISP_AHB_CBCR) & CBCR_ENABLE)) {+ printf("adreno: 0: the display's clock controller has no bus clock, and does not get one: nothing more is read\n");+ goto out;}announce("the display block's power switch and clocks, in its clock controller (0xaf00000: NOT READ BEFORE)");+ get(&dispcc, "mdss_mdp_cbcr", DISPCC_MDSS_MDP_CBCR);+ get(&dispcc, "mdss_pclk0_cbcr", DISPCC_MDSS_PCLK0_CBCR);if (!(get(&dispcc, "mdss_core_gdscr", DISPCC_MDSS_CORE_GDSCR) & GDSC_POWER_ON) ||(get(&dispcc, "mdss_ahb_cbcr", DISPCC_MDSS_AHB_CBCR) & CBCR_OFF)) {+ /*+ * (Seen: the power switch on, the display's own clock and the pixel clock running, and+ * the bus clock of its registers off: the firmware set the panel going and took the+ * clock it had spoken to the block with away. To read the timing that clock would have+ * to be turned on: a write to the display's clock controller, which this does not do.)+ */printf("adreno: 0: the display block is without power or without its bus clock: nothing more is read\n");goto out;}- get(&dispcc, "mdss_mdp_cbcr", DISPCC_MDSS_MDP_CBCR);- get(&dispcc, "mdss_pclk0_cbcr", DISPCC_MDSS_PCLK0_CBCR);announce("the timing of the interface the panel hangs on (0xae36000: NOT READ BEFORE)");get(&disp_intf, "timing_engine_en", INTF_TIMING_ENGINE_EN);line = get(&disp_intf, "hsync_ctl", INTF_HSYNC_CTL) >> 16;@@ -3641,6 +3654,15 @@ display_probe(void)}printf("adreno: 0: the interface's counters (%s, frame_line_count_en %#x): frames %u then %u a second later, ""lines %u then %u\n", (counting & 1) ? "counting" : "not counting", counting, frames[0], frames[1], lines[0], lines[1]);+ /* where the scan is, read eight times a millisecond and a bit apart: how fast it goes down the panel */+ for (int i = 0; i < 8; i++) {+ uint64_t nanos;++ absolutetime_to_nanoseconds(mach_absolute_time(), &nanos);+ printf("adreno: 0: the scan: at %llu us line %u of frame %u\n", nanos / 1000 % 1000000, rd(disp_intf.base + INTF_LINE_COUNT),+ rd(disp_intf.base + INTF_FRAME_COUNT));+ sleep_us(1300);+ }out:fine = saved_fine;newest_step = 0;diff --git a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cppindex 773cf66..e1d699a 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 <kern/thread.h>#include <kern/clock.h>#include <pexpert/pexpert.h>#include <sys/systm.h>@@ -77,6 +78,8 @@ enum {#define FRAME_TIMES 64 /* milliseconds told apart between two frames */#define FRAME_PAUSE 90 /* from so many on, nothing was moving: not a slow frame */+#define SWAP_GPU_MS 500 /* a frame the GPU has not drawn by then is shown as it is */+#define SWAP_HELD_MS 700 /* a swap that cannot be taken by then is not shown at all */#define FOURCC(a, b, c, d) ((uint32_t)(a) << 24 | (uint32_t)(b) << 16 | (uint32_t)(c) << 8 | (uint32_t)(d))@@ -125,6 +128,7 @@ static TUNABLE(uint32_t, gRecStart, "rec_start", 0);static TUNABLE(uint32_t, gRecMegabytes, "rec_mb", 480);static TUNABLE(uint32_t, gDiff, "fb_diff", 0);static TUNABLE(uint32_t, gRefreshHz, "fb_hz", kFBRefreshHz);+static TUNABLE(uint32_t, gOnTheBeat, "fb_beat", 1);static inline uint32_trefreshHz(void)@@ -170,6 +174,39 @@ public:uint32_t fSwapsShown;uint32_t fLayersShown; /* which layers the last swap had a surface in */bool fGraphics; /* the text console has been told to stop */+ /*+ * A frame goes to the panel when the GPU is done with it: a thread of ours waits for that+ * and copies it there, and whoever made the frame is back at the next one meanwhile. One+ * frame waits at a time: the swap after it is held, in SwapEnd, until this one is being+ * copied to the panel. Whoever draws is so at most two frames ahead of the panel, and+ * needs a third surface to be that: CoreAnimation makes itself a new one for every frame.+ */+ IOLock * fSwapLock; /* around the next five */+ uint8_t fSwap[SWAP_SIZE]; /* the swap that is on its way to the panel */+ MiniIOSurface * fSwapSurfaces[SWAP_LAYERS]; /* ... its surfaces, held from SwapEnd on: their maker may let go of them */+ bool fSwapThere;+ /*+ * ... and not whenever the GPU happens to be done, but on a beat of the refresh rate+ * (boot-arg fb_beat=0: at once): frames then follow each other at an even pace whatever+ * each took to draw, as long as there is one for every beat. The beat is this driver's own.+ * (CoreAnimation does not go by the refresh notifications of this driver -- it never asks+ * for them -- but by a clock of its own at the rate it reads here; and where the panel's+ * scan is nobody can read: the display block's register clock is off.) It starts with a+ * frame that comes later than a beat and a half after the one before -- the first after a+ * pause, or every one of a renderer that does not keep up, the software one: such a frame+ * is shown at once, a beat would only make it later still -- and gives way by an eighth of+ * what a frame is early or late, so that frames are ready some six milliseconds before+ * 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 */+ 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 */+ uint64_t fStatBeatWait;+ uint32_t fStatSurfaces[8]; /* the first different surfaces the bottom layer was given */+ uint32_t fStatHeld, fStatLost; /* swaps that waited for the one before; that gave up waiting */+ uint64_t fSwapTime; /* when the last swap was handed over */+ uint32_t fStatSwapsLate; /* swaps that came more than a refresh and a quarter after the one before (and no pause) */+ uint64_t fStatWaiting; /* how long frames waited for the GPU here *//* how the display is doing: frames and time spent drawing them here since fStatSince */uint32_t fStatFrames;uint64_t fStatSince, fStatDrawing;@@ -191,6 +228,9 @@ public:void publishModes(void);MiniIOSurface * defaultSurface(void);void present(const uint8_t * swap);+ void show(const uint8_t * swap, MiniIOSurface ** surfaces);+ void presenter(void);+ static void presenterMain(void * self, wait_result_t result);void reportFrameTimes(void);void drawLayer(MiniIOSurface * s, const int32_t * src, const int32_t * dst);void record(MiniIOSurface * s);@@ -272,6 +312,8 @@ IOMobileFramebuffer::publishModes(void)boolIOMobileFramebuffer::start(IOService * provider){+ thread_t thread;+if (!IOService::start(provider)) {return false;}@@ -281,6 +323,13 @@ IOMobileFramebuffer::start(IOService * provider)return false;}fLock = IOLockAlloc();+ fSwapLock = IOLockAlloc();+ if (kernel_thread_start(&IOMobileFramebuffer::presenterMain, this, &thread) != KERN_SUCCESS) {+ IOLog("MiniIOMobileFramebuffer: no thread to put frames on the panel with\n");+ return false;+ }+ thread_set_thread_name(thread, "frames to the panel");+ thread_deallocate(thread);fBase = (uint8_t *) vinfo.v_baseaddr;fPanelWidth = vinfo.v_width;fPanelHeight = vinfo.v_height;@@ -335,6 +384,8 @@ IOMobileFramebuffer::start(IOService * provider)}setProperty(kIOUserClientClassKey, "IOMobileFramebufferUserClient");+ /* for who draws with the GPU (userland/src/eagl.c): a frame need not be waited for before it is handed over */+ setProperty("RedwoodWaitsForGPU", kOSBooleanTrue);publishModes();setName("disp0");registerService();@@ -509,14 +560,116 @@ IOMobileFramebuffer::reportFrameTimes(void)fFramePauses = fFrameLongest = 0;}+/* SwapEnd: the swap is handed to the thread that puts frames on the panel, as soon as that has no other waiting. */voidIOMobileFramebuffer::present(const uint8_t * swap)+{+ AbsoluteTime deadline;++ uint64_t now = mach_absolute_time(), period, pause;++ /* (a frame that is late on the panel was late here already, or it was not: for telling whose it is) */+ nanoseconds_to_absolutetime(NSEC_PER_SEC / refreshHz() * 5 / 4, &period);+ nanoseconds_to_absolutetime(FRAME_PAUSE * NSEC_PER_MSEC, &pause);+ clock_interval_to_deadline(SWAP_HELD_MS, kMillisecondScale, &deadline);+ IOLockLock(fSwapLock);+ fStatSwapsLate += fSwapTime != 0 && now - fSwapTime > period && now - fSwapTime < pause;+ fSwapTime = now;+ fStatHeld += fSwapThere;+ while (fSwapThere) {+ if (IOLockSleepDeadline(fSwapLock, &fSwapThere, deadline, THREAD_UNINT) == THREAD_TIMED_OUT && fSwapThere) {+ fStatLost++; /* (the GPU has stopped answering: the frame before is waiting for it) */+ IOLockUnlock(fSwapLock);+ return;+ }+ }+ memcpy(fSwap, swap, SWAP_SIZE);+ for (unsigned layer = 0; layer < SWAP_LAYERS; layer++) {+ uint32_t sid = swapWord(swap, SWAP_SURFACE(layer));++ fSwapSurfaces[layer] = sid != 0 ? MiniIOSurfaceCopy(sid) : NULL;+ }+ fSwapThere = true;+ IOLockWakeup(fSwapLock, fSwap, true);+ IOLockUnlock(fSwapLock);+}++void+IOMobileFramebuffer::presenterMain(void * self, wait_result_t result __unused)+{+ ((IOMobileFramebuffer *) self)->presenter();+}++void+IOMobileFramebuffer::presenter(void)+{+ static uint8_t swap[SWAP_SIZE]; /* (one thread) */+ MiniIOSurface * surfaces[SWAP_LAYERS];++ for (;;) {+ IOLockLock(fSwapLock);+ while (!fSwapThere) {+ IOLockSleep(fSwapLock, fSwap, THREAD_UNINT);+ }+ memcpy(swap, fSwap, SWAP_SIZE);+ memcpy(surfaces, fSwapSurfaces, sizeof(surfaces));+ IOLockUnlock(fSwapLock);+ show(swap, surfaces);+ for (unsigned layer = 0; layer < SWAP_LAYERS; layer++) {+ if (surfaces[layer] != NULL) {+ MiniIOSurfaceDrop(surfaces[layer]);+ }+ }+ MiniIOSurfaceClearKept(); /* (the next frame is some milliseconds away) */+ }+}++/* A swap's surfaces onto the panel, once the GPU is done with them. */+void+IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces){uint32_t set = swapWord(swap, SWAP_LAYERS_SET);uint64_t began = mach_absolute_time(), nanos;uint32_t layers = 0;bool report;+ for (unsigned layer = 0; layer < SWAP_LAYERS; layer++) {+ if (surfaces[layer] != NULL && !MiniIOSurfaceDrawn(surfaces[layer], SWAP_GPU_MS)) {+ IOLog("MiniIOMobileFramebuffer: swap %u: the GPU is not done with surface %u after %u ms; shown as it is\n",+ swapWord(swap, SWAP_ID), swapWord(swap, SWAP_SURFACE(layer)), SWAP_GPU_MS);+ }+ }+ fStatWaiting += mach_absolute_time() - began;+ began = mach_absolute_time();+ if (gOnTheBeat) {+ uint64_t period, aim, next;++ nanoseconds_to_absolutetime(NSEC_PER_SEC / refreshHz(), &period);+ aim = period * 3 / 8;+ next = fReady;+ fReady = began;+ if (fBeat == 0 || began - next > period * 3 / 2) {+ fBeat = began;+ } else {+ for (next = fBeat + period; next < began; next += period) {+ }+ if (next - began > aim) {+ next -= (next - began - aim) / 8;+ } else {+ next += (aim - (next - began)) / 8;+ }+ clock_delay_until(next);+ fBeat = next;+ fStatOnBeat++;+ fStatBeatWait += mach_absolute_time() - began;+ began = mach_absolute_time();+ }+ }+ /* its turn has come: the swap after it may be handed over */+ IOLockLock(fSwapLock);+ fSwapThere = false;+ IOLockWakeup(fSwapLock, &fSwapThere, true);+ IOLockUnlock(fSwapLock);IOLockLock(fLock);if (fLastFrame != 0) {absolutetime_to_nanoseconds(began - fLastFrame, &nanos);@@ -541,6 +694,13 @@ IOMobileFramebuffer::present(const uint8_t * swap)MiniIOSurface * s;layers |= sid != 0 ? 1u << layer : 0;+ /* the frames' surfaces: is it a few, in turn? */+ for (unsigned i = 0; layer == 0 && sid != 0 && i < 8; i++) {+ if (fStatSurfaces[i] == 0 || fStatSurfaces[i] == sid) {+ fStatSurfaces[i] = sid;+ break;+ }+ }if (sid == 0) {/* the bottom layer taken away: nothing is shown, the screen is black */if (layer == 0 && (set & 1) && fGraphics) {@@ -552,7 +712,7 @@ IOMobileFramebuffer::present(const uint8_t * swap)}memcpy(src, swap + SWAP_SOURCE(layer), sizeof(src));memcpy(dst, swap + SWAP_DEST(layer), sizeof(dst));- s = MiniIOSurfaceCopy(sid);+ s = surfaces[layer];if (report) {IOLog("MiniIOMobileFramebuffer: swap %u layer %u: surface %u%s (%ux%u '%c%c%c%c') ""from %d,%d %dx%d to %d,%d %dx%d, layers set 0x%x\n", swapWord(swap, SWAP_ID), layer, sid,@@ -575,7 +735,6 @@ IOMobileFramebuffer::present(const uint8_t * swap)record(s);}}- MiniIOSurfaceDrop(s);}fSwapsShown++;if (layers != fLayersShown) {@@ -593,11 +752,35 @@ IOMobileFramebuffer::present(const uint8_t * swap)}absolutetime_to_nanoseconds(mach_absolute_time() - fStatSince, &nanos);if (nanos >= 5 * NSEC_PER_SEC) {- uint64_t drawing;+ uint64_t drawing, waiting, beat;+ unsigned different;absolutetime_to_nanoseconds(fStatDrawing, &drawing);- IOLog("MiniIOMobileFramebuffer: %u frames in %llu ms (%llu a second), %llu us each in the driver\n", fStatFrames,- nanos / NSEC_PER_MSEC, fStatFrames * NSEC_PER_SEC / nanos, drawing / fStatFrames / NSEC_PER_USEC);+ absolutetime_to_nanoseconds(fStatWaiting, &waiting);+ 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\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);+ fStatSwapsLate = 0;+ for (different = 0; different < 8 && fStatSurfaces[different] != 0; different++) {+ }+ if (different == 8 && fStatFrames > 8) {+ uint32_t made, freed, again;+ uint64_t making, freeing;++ /* (CoreAnimation has made itself a new surface for every frame: see "the frames' surfaces" above) */+ MiniIOSurfaceCost(&made, &making, &freed, &freeing, &again);+ IOLog("MiniIOMobileFramebuffer: the frames came in surfaces %u, %u, %u, %u, %u and on, none twice; in that time "+ "%u surfaces of all kinds were made, in %llu us each (%u of them of memory kept from one before), and %u "+ "freed, in %llu us each\n", fStatSurfaces[0], fStatSurfaces[1], fStatSurfaces[2], fStatSurfaces[3],+ fStatSurfaces[4], made, making, again, freed, freeing);+ }+ bzero(fStatSurfaces, sizeof(fStatSurfaces));+ fStatHeld = fStatLost = fStatOnBeat = 0;+ fStatWaiting = fStatBeatWait = 0;reportFrameTimes();if (fDiff) {IOLog("MiniIOMobileFramebuffer: %llu pixels of the panel changed a frame, all within %u,%u to %u,%u\n",diff --git a/xnu/files/iokit/Kernel/MiniIOSurface.cpp b/xnu/files/iokit/Kernel/MiniIOSurface.cppindex cfa201e..e27e463 100644--- a/xnu/files/iokit/Kernel/MiniIOSurface.cpp+++ b/xnu/files/iokit/Kernel/MiniIOSurface.cpp@@ -21,6 +21,7 @@#include <libkern/c++/OSBoolean.h>#include <libkern/c++/OSString.h>#include <libkern/c++/OSSymbol.h>+#include <kern/thread_call.h>#include <sys/systm.h>#include <sys/proc.h>@@ -83,6 +84,9 @@ static uint32_t gSurfaceNext = 1;static uint32_t gSurfaceCount;static uint64_t gSurfaceBytes;static uint32_t gSurfaceUnheld; /* surfaces around client memory that could not be made (said a few times) */+/* what making surfaces and taking them away has cost since it was last asked (MiniIOSurfaceCost()) */+static uint64_t gSurfaceMaking, gSurfaceFreeing;+static uint32_t gSurfacesMade, gSurfacesFreed;static uint64_t gSurfaceLogged[2]; /* selectors already complained about *//* Boot-arg surftrace=N: log the first N surfaces created (default 24). */static TUNABLE(uint32_t, gSurfaceTrace, "surftrace", 24);@@ -92,9 +96,128 @@ static uint32_t gSurfaceTraced; /* (a tunable isOSDefineMetaClassAndStructors(MiniIOSurface, OSObject);+/*+ * The memory of the big surfaces is kept when they go, a few pieces of it, and given to the+ * next surface of the same size. CoreAnimation makes a surface of the whole display for every+ * frame and frees one: 14 MB got, cleared, entered into the kernel's map and taken out of it+ * again, sixty times a second -- 2.8 ms to make and 2 ms to free each, a quarter of the time+ * there is for a frame, on the thread that draws it. A piece that is kept is cleared again+ * before it is given out: a new surface is all zeroes, whoever makes it. The clearing is done+ * by the display's driver between two frames (MiniIOSurfaceClearKept(): while it copies a+ * frame to the panel the memory is busy enough, and the copy took half as long again when+ * this ran beside it), or a moment later by a thread of this file's if no frames are going+ * out, or by whoever asks for the memory if that comes first.+ */+#define SURFACE_KEEP_FROM (4u << 20) /* bytes: smaller ones are not worth it */+#define SURFACE_KEPT 4+#define SURFACE_CLEAR_MS 40 /* kept memory is cleared this long after, if the display's driver has not done it */++static struct {+ IOBufferMemoryDescriptor * memory;+ bool clear; /* cleared since it was last a surface's */+ bool busy; /* being cleared right now */+} gSurfaceKept[SURFACE_KEPT];+static IOLock * gSurfaceKeptLock;+static thread_call_t gSurfaceClearing;+static uint32_t gSurfacesGivenAgain; /* for MiniIOSurfaceCost() */+/* boot-arg surf_clear=0: kept memory is given out as it is (to see what the clearing costs; a surface is then not all zeroes) */+static TUNABLE(uint32_t, gSurfaceClear, "surf_clear", 1);++void+MiniIOSurfaceClearKept(void)+{+ if (gSurfaceKeptLock == NULL || !gSurfaceClear) {+ return;+ }+ IOLockLock(gSurfaceKeptLock);+ for (unsigned i = 0; i < SURFACE_KEPT; i++) {+ IOBufferMemoryDescriptor * memory = gSurfaceKept[i].memory;++ if (memory == NULL || gSurfaceKept[i].clear || gSurfaceKept[i].busy) {+ continue;+ }+ gSurfaceKept[i].busy = true;+ IOLockUnlock(gSurfaceKeptLock);+ bzero(memory->getBytesNoCopy(), memory->getCapacity());+ IOLockLock(gSurfaceKeptLock);+ gSurfaceKept[i].busy = false;+ gSurfaceKept[i].clear = true;+ }+ IOLockUnlock(gSurfaceKeptLock);+}++static void+surfaceMemoryClear(thread_call_param_t unused0 __unused, thread_call_param_t unused1 __unused)+{+ MiniIOSurfaceClearKept();+}++/* Memory for a surface: the state page and `bytes` after it, all zeroes. */+static IOBufferMemoryDescriptor *+surfaceMemory(vm_size_t bytes)+{+ IOBufferMemoryDescriptor * memory = NULL;+ bool clear = false;++ if (bytes >= SURFACE_KEEP_FROM && gSurfaceKeptLock != NULL) {+ IOLockLock(gSurfaceKeptLock);+ for (int pass = 0; pass < 2 && memory == NULL; pass++) {+ /* one that is clear already, if there is one */+ for (unsigned i = 0; i < SURFACE_KEPT && memory == NULL; i++) {+ if (gSurfaceKept[i].memory != NULL && !gSurfaceKept[i].busy && (pass == 1 || gSurfaceKept[i].clear) &&+ gSurfaceKept[i].memory->getCapacity() == bytes) {+ memory = gSurfaceKept[i].memory;+ clear = gSurfaceKept[i].clear;+ gSurfaceKept[i].memory = NULL;+ }+ }+ }+ gSurfacesGivenAgain += memory != NULL;+ IOLockUnlock(gSurfaceKeptLock);+ if (memory != NULL && !clear) {+ bzero(memory->getBytesNoCopy(), gSurfaceClear ? bytes : PAGE_SIZE);+ }+ }+ if (memory == NULL) {+ memory = IOBufferMemoryDescriptor::inTaskWithOptions(kernel_task, kIODirectionInOut | kIOMemoryKernelUserShared, bytes,+ PAGE_SIZE);+ }+ return memory;+}++/* A surface is gone: its memory is kept for the next, if it is big and nobody else has it. */+static void+surfaceMemoryBack(IOBufferMemoryDescriptor * memory)+{+ if (memory->getCapacity() >= SURFACE_KEEP_FROM && memory->getRetainCount() == 1 && gSurfaceKeptLock != NULL) {+ IOLockLock(gSurfaceKeptLock);+ for (unsigned i = 0; i < SURFACE_KEPT; i++) {+ if (gSurfaceKept[i].memory == NULL) {+ gSurfaceKept[i].memory = memory;+ gSurfaceKept[i].clear = gSurfaceKept[i].busy = false;+ memory = NULL;+ break;+ }+ }+ IOLockUnlock(gSurfaceKeptLock);+ if (memory == NULL) {+ if (gSurfaceClear) {+ AbsoluteTime deadline;++ clock_interval_to_deadline(SURFACE_CLEAR_MS, kMillisecondScale, &deadline);+ thread_call_enter_delayed(gSurfaceClearing, deadline);+ }+ return;+ }+ }+ memory->release();+}+voidMiniIOSurface::free(void){+ uint64_t began = mach_absolute_time();+OSSafeReleaseNULL(values);OSSafeReleaseNULL(clientMap);if (client != NULL) {@@ -102,8 +225,30 @@ MiniIOSurface::free(void)client->release();client = NULL;}- OSSafeReleaseNULL(memory);+ if (memory != NULL) {+ surfaceMemoryBack(memory);+ memory = NULL;+ }OSObject::free();+ OSAddAtomic64((SInt64) (mach_absolute_time() - began), (SInt64 *) &gSurfaceFreeing);+ OSIncrementAtomic(&gSurfacesFreed);+}++/* How many surfaces were made and freed since this was last asked, and the microseconds each took on average. */+void+MiniIOSurfaceCost(uint32_t * made, uint64_t * making, uint32_t * freed, uint64_t * freeing, uint32_t * again)+{+ uint64_t nanos;++ *again = OSBitAndAtomic(0, &gSurfacesGivenAgain);++ *made = OSBitAndAtomic(0, &gSurfacesMade);+ *freed = OSBitAndAtomic(0, &gSurfacesFreed);+ absolutetime_to_nanoseconds(gSurfaceMaking, &nanos);+ *making = *made ? nanos / NSEC_PER_USEC / *made : 0;+ absolutetime_to_nanoseconds(gSurfaceFreeing, &nanos);+ *freeing = *freed ? nanos / NSEC_PER_USEC / *freed : 0;+ gSurfaceMaking = gSurfaceFreeing = 0;}/* The values changed: a new seed, and how much room a client needs to fetch them. */@@ -402,8 +547,7 @@ surfaceCreate(OSDictionary * props, IOReturn * error)alloc = dictNumber(props, "IOSurfaceAllocSize", (uint32_t) needed);}- s->memory = IOBufferMemoryDescriptor::inTaskWithOptions(kernel_task,- kIODirectionInOut | kIOMemoryKernelUserShared, (vm_size_t) PAGE_SIZE + (wrapped ? 0 : alloc), PAGE_SIZE);+ s->memory = surfaceMemory((vm_size_t) PAGE_SIZE + (wrapped ? 0 : alloc));if (s->memory == NULL) {IOLog("MiniIOSurface: no memory for %u bytes (%u surfaces, %llu MB in use)\n", alloc, gSurfaceCount,gSurfaceBytes >> 20);@@ -632,6 +776,8 @@ MiniIOSurfaceStart(IOService * provider)IOCoreSurfaceRoot * root;gSurfaceLock = IOLockAlloc();+ gSurfaceKeptLock = IOLockAlloc();+ gSurfaceClearing = thread_call_allocate(surfaceMemoryClear, NULL);root = OSTypeAlloc(IOCoreSurfaceRoot);if (root == NULL || !root->init() || !root->attach(provider)) {OSSafeReleaseNULL(root);@@ -905,6 +1051,7 @@ IOSurfaceRootUserClient::methodCreate(IOExternalMethodArguments * args)OSDictionary * props;MiniIOSurface * s;struct minisurf_client_ref * ref;+ uint64_t began = mach_absolute_time();if (args->scalarInputCount >= 1 && args->scalarInput[0] != 0) {IOLog("MiniIOSurface: child surfaces are not supported (parent %llu)\n", args->scalarInput[0]);@@ -953,6 +1100,8 @@ IOSurfaceRootUserClient::methodCreate(IOExternalMethodArguments * args)}surfaceUnhold(s); /* the creator's hold; the client's own is in the ref */IOLockUnlock(gSurfaceLock);+ OSAddAtomic64((SInt64) (mach_absolute_time() - began), (SInt64 *) &gSurfaceMaking);+ OSIncrementAtomic(&gSurfacesMade);return ret;}diff --git a/xnu/files/iokit/Kernel/MiniIOSurface.h b/xnu/files/iokit/Kernel/MiniIOSurface.hindex 2109fbb..21f1f0f 100644--- a/xnu/files/iokit/Kernel/MiniIOSurface.h+++ b/xnu/files/iokit/Kernel/MiniIOSurface.h@@ -117,6 +117,7 @@ public:task_t clientTask; /* whose memory it is (not held: only compared) */mach_vm_address_t clientAddress; /* ... and where it is there */uint8_t * kpixels; /* where the pixel memory starts in the kernel, either way */+ uint32_t drawn; /* the GPU's last submission that names the pixels (0: none; RedwoodGPU.cpp) */struct minisurf_result info; /* addresses not filled in */struct minisurf_plane planes[MINISURF_MAX_PLANES];OSDictionary * values;@@ -154,6 +155,15 @@ public:* A surface found or made here is held until MiniIOSurfaceDrop().*/MiniIOSurface * MiniIOSurfaceCopy(uint32_t sid);+/*+ * What making and freeing surfaces has cost since this was last asked: how many, microseconds+ * each; how many got memory that was kept from one before.+ */+void MiniIOSurfaceCost(uint32_t * made, uint64_t * making, uint32_t * freed, uint64_t * freeing, uint32_t * again);+/* Clear the memory that is kept of surfaces that are gone, for the next ones: when the caller has a moment. */+void MiniIOSurfaceClearKept(void);+/* Wait, for so many milliseconds at most, until the GPU is done with a surface's pixels (RedwoodGPU.cpp). */+bool MiniIOSurfaceDrawn(MiniIOSurface * surface, uint64_t milliseconds);MiniIOSurface * MiniIOSurfaceCreateSimple(uint32_t width, uint32_t height, uint32_t pixelFormat);void MiniIOSurfaceDrop(MiniIOSurface * surface);/* A Mach send right for the surface in the task (what IOSurfaceCreateMachPort gives); 0 on failure. */diff --git a/xnu/files/iokit/Kernel/RedwoodGPU.cpp b/xnu/files/iokit/Kernel/RedwoodGPU.cppindex a36d526..1c6670f 100644--- a/xnu/files/iokit/Kernel/RedwoodGPU.cpp+++ b/xnu/files/iokit/Kernel/RedwoodGPU.cpp@@ -209,6 +209,20 @@ gpuWait(uint32_t fence, uint64_t milliseconds)return false;}+bool+MiniIOSurfaceDrawn(MiniIOSurface * surface, uint64_t milliseconds)+{+ uint32_t fence = surface->drawn;+ bool done = true;++ if (fence != 0 && gGPULock != NULL) {+ IOLockLock(gGPULock);+ done = !redwood_gpu_ready() || gpuWait(fence, milliseconds);+ IOLockUnlock(gGPULock);+ }+ return done;+}+/* How long from now a time of msm's is, in milliseconds; 0: now or past. */static uint64_tmillisecondsUntil(const struct msm_timespec * when)@@ -311,8 +325,24 @@ struct gpu_buffer {uint32_t seed; /* the surface's when it was last pushed out of the cache, */uint64_t pushed; /* ... and when that was */bool seen; /* by the program: mapped, and from then on written by it */+ uint32_t fence; /* the last submission that names it (0: none has) */};+/*+ * A buffer given back while the GPU is still at it: its memory and its place in the GPU's+ * address space are kept until the submission is done, and nobody waits for that. (A window+ * server that makes a surface for every frame gives the last frame's back while the GPU draws+ * this one: waiting there, for all the GPU had been given, cost it some five milliseconds a+ * frame.)+ */+struct gpu_left {+ IOMemoryDescriptor * memory;+ MiniIOSurface * surface;+ uint64_t address, size;+ uint32_t fence;+};+#define GPU_LEFT 64+class RedwoodGPUUserClient : public IOUserClient{OSDeclareDefaultStructors(RedwoodGPUUserClient);@@ -325,10 +355,13 @@ class RedwoodGPUUserClient : public IOUserClientuint64_t fBufferBytes;uint32_t fSubmits;uint32_t fStrangers; /* requests that named a buffer the client does not have */+ struct gpu_left fLeft[GPU_LEFT];+ uint32_t fLeftCount;struct gpu_buffer * buffer(uint32_t handle);struct gpu_buffer * newBuffer(IOMemoryDescriptor * memory, uint64_t from, uint64_t size, uint32_t flags, uint32_t * handle);- void freeBuffer(struct gpu_buffer * b, bool idle);+ void freeBuffer(struct gpu_buffer * b);+ void reap(void);IOReturn gemNew(struct msm_gem_new * request);IOReturn surfaceBuffer(struct redwood_surface * request);IOReturn gemInfo(struct msm_gem_info * request);@@ -373,46 +406,89 @@ RedwoodGPUUserClient::start(IOService * provider)* written, and must not be somebody else's by then.*/void-RedwoodGPUUserClient::freeBuffer(struct gpu_buffer * b, bool idle)+RedwoodGPUUserClient::freeBuffer(struct gpu_buffer * b){- if (!idle) {- static uint32_t said;+ bool busy = redwood_gpu_ready() && b->fence != 0 && !redwood_gpu_done(b->fence);- if (b->surface == NULL) {- b->memory->retain();- } else {- b->surface->memory->retain();+ if (busy && fLeftCount == GPU_LEFT) {+ busy = !gpuWait(b->fence, 1000); /* (nowhere to keep it: this one is waited for) */+ }+ if (busy && fLeftCount < GPU_LEFT) {+ struct gpu_left * left = &fLeft[fLeftCount++];++ left->memory = b->memory;+ left->surface = b->surface;+ left->address = b->address;+ left->size = b->size;+ left->fence = b->fence;+ } else {+ if (busy) {+ static uint32_t said;++ if (b->surface == NULL) {+ b->memory->retain();+ } else {+ b->surface->memory->retain();+ }+ if (said++ < 8) {+ IOLog("RedwoodGPU: the GPU is not done with what it was given: a buffer of %llu bytes stays its own\n", b->size);+ }+ } else if (redwood_gpu_ready()) {+ redwood_gpu_unmap(b->address, b->size);+ redwood_gpu_address_free(b->address, b->size);}- if (said++ < 8) {- IOLog("RedwoodGPU: the GPU is not done with what it was given: a buffer of %llu bytes stays its own\n", b->size);+ b->memory->release();+ if (b->surface != NULL) {+ MiniIOSurfaceDrop(b->surface);}- } else if (redwood_gpu_ready()) {- redwood_gpu_unmap(b->address, b->size);- redwood_gpu_address_free(b->address, b->size);}- b->memory->release();b->memory = NULL;- if (b->surface != NULL) {- MiniIOSurfaceDrop(b->surface);- b->surface = NULL;- }+ b->surface = NULL;fBufferCount--;fBufferBytes -= b->size;}+/* The buffers that were given back early and that the GPU is done with now: freed. With the lock held. */+void+RedwoodGPUUserClient::reap(void)+{+ for (uint32_t i = 0; i < fLeftCount;) {+ struct gpu_left * left = &fLeft[i];++ if (redwood_gpu_ready() && !redwood_gpu_done(left->fence)) {+ i++;+ continue;+ }+ if (redwood_gpu_ready()) {+ redwood_gpu_unmap(left->address, left->size);+ redwood_gpu_address_free(left->address, left->size);+ }+ left->memory->release();+ if (left->surface != NULL) {+ MiniIOSurfaceDrop(left->surface);+ }+ *left = fLeft[--fLeftCount];+ }+}+IOReturnRedwoodGPUUserClient::clientClose(void){if (fBuffers != NULL) {IOLockLock(gGPULock);/* what the client had the GPU do last may still be going on, in these buffers */- bool idle = !redwood_gpu_ready() || gpuWait(redwood_gpu_last(), 1000);-+ if (redwood_gpu_ready()) {+ gpuWait(redwood_gpu_last(), 1000);+ }for (uint32_t i = 0; i < GPU_BUFFERS; i++) {if (fBuffers[i].memory != NULL) {- freeBuffer(&fBuffers[i], idle);+ freeBuffer(&fBuffers[i]);}}+ reap();+ if (fLeftCount != 0) {+ IOLog("RedwoodGPU: the GPU is not done with %u buffers of a program that is gone: they stay its own\n", fLeftCount);+ }IOLockUnlock(gGPULock);}if (!isInactive()) {@@ -486,6 +562,7 @@ RedwoodGPUUserClient::newBuffer(IOMemoryDescriptor * memory, uint64_t from, uintb->seed = 0;b->pushed = 0;b->seen = false;+ b->fence = 0;b->surface = NULL;fBufferCount++;fBufferBytes += size;@@ -704,6 +781,23 @@ RedwoodGPUUserClient::submit(struct msm_gem_submit * request)if (request->flags & MSM_SUBMIT_FENCE_FD_OUT) {request->fence_fd = -1;}+ /*+ * The surfaces named are being drawn into, or read, until this submission is done: the+ * display's driver waits for that before it puts one on the panel (MiniIOSurfaceDrawn()).+ * (freedreno names every buffer for reading and writing alike, so which it is cannot be+ * told; the last submission of a frame names the surface the frame is drawn into.)+ */+ for (uint32_t i = 0; request->fence != 0 && i < request->nr_bos; i++) {+ struct gpu_buffer * b = buffer(bos[i].handle);++ if (b != NULL) {+ b->fence = request->fence;+ if (b->surface != NULL) {+ b->surface->drawn = request->fence;+ }+ }+ }+ reap();if (request->fence == 0 && !gGPUReported) {gGPUReported = true;redwood_gpu_report("the ring is full");@@ -883,7 +977,8 @@ RedwoodGPUUserClient::externalMethod(uint32_t selector, IOExternalMethodArgumentif (b == NULL) {ret = kIOReturnBadArgument;} else {- freeBuffer(b, gpuWait(redwood_gpu_last(), 1000));+ freeBuffer(b);+ reap();}IOLockUnlock(gGPULock);break;