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

GPU path: one boot-arg (gpu=1), framebuffer fetch mended in freedreno

vcvkke1c04c34dabb
diff --git a/README.md b/README.md
index 85c9580..554631b 100644
--- a/README.md
+++ b/README.md
@@ -145,6 +145,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| `machine_name=0` | сообщать `hw.machine = arm64` вместо iPhone10,3 (как было раньше; тогда iOS не находит ни одного ресурса с суффиксом `~iphone`, и, например, Пункт управления теряет раскладку) |
| `wfi=0 wfe_mode=0` | простаивающее ядро процессора не засыпает, а крутится в цикле, как всегда было с одним ядром (с `cpus=N` простой — это WFI; на случай, если под гипервизором телефона он поведёт себя плохо) |
| `return_cpu=N`, `return_panic=1` | для проверки возврата в загрузчик с несколькими ядрами: вернуться по таймеру с процессора N (по номеру в ядре: 0 — загрузочный) и/или через панику |
+| `gpu=1` | рисовать графическим процессором телефона (образ с `GL=1`, прошивки в `fw-gpu/`; см. раздел «GPU»). Без него, без прошивок и в QEMU всё рисует программный рендер CoreAnimation |
| `adreno=N` | опыт с GPU телефона: первые N шагов его пробуждения (питание, такты, первые регистры), каждый шаг пишет в журнал, что собирается тронуть и что прочёл; шаги и остальные параметры описаны в начале `bsd/dev/redwood_adreno.c` |
Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). Лучший
@@ -174,22 +175,25 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
```sh
tools/mk-mesa.sh
GL=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" ./xl run
+XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4 gpu=1" ./xl run
```
-При втором и следующих запусках за одну загрузку телефона добавлять `adreno_zap=0`. Без параметров `adreno…`
-тот же образ рисует программным драйвером Mesa (в QEMU — всегда так).
+`gpu=1` — всё, что нужно сказать: ядро само запускает GPU и само выгружает и загружает zap-шейдер в TrustZone
+(`adreno_zap=0` больше не нужен; прежняя длинная строка `adreno=21 … adreno_keep=1` работает как раньше).
+Без `gpu=1`, без прошивок и в QEMU библиотека OpenGL ES не загружается вовсе, рисует программный рендер
+CoreAnimation; если GPU не запустился, в журнале одна строка `adreno: THE GPU IS NOT STARTED: …` с причиной.
Состояние — опытный режим, не по умолчанию. GPU рисует прямо в память поверхностей (IOSurface экрана и
полноэкранных слоёв — общая с GPU, без копий); готовый кадр ждёт GPU и уходит на панель в потоке драйвера экрана,
по его собственному такту 60 Гц. Прокрутка Настроек на телефоне: 56–58 кадров/с, 95–97 % кадров с шагом 16,7 мс
(программный рендер на четырёх ядрах — около 28–35). Короткий сценарий (разблокировка, прокрутка, Часы) — 1383 кадра
против 929. Известные дефекты: нет размытой подложки под листом FaceTime; кадр может рваться (копирование в панель
-не привязано к развёртке). Расширение `EXT_shader_framebuffer_fetch` от CoreAnimation скрыто: на этом GPU при
-отрисовке плитками freedreno читает в нём не те пиксели (`glfetch=1` возвращает его для опытов).
+не привязано к развёртке; панель обновляется 120 раз в секунду). Чтение кадра из шейдера
+(`EXT_shader_framebuffer_fetch`, им CoreAnimation рисует тени подписей) в freedreno исправлено заплаткой в
+`tools/mesa/freedreno-darwin.patch`; `glfetch=0` прячет расширение для сравнения.
Прерываний нет (ожидание опросом). GPU выключается при любом штатном конце сеанса (таймер, `./xl stop`, пять
-пальцев); после паники с включённым GPU — `./xl reboot`. Приложения, использующие Metal сами, от этого ничего не
-получают.
+пальцев); после паники следующий запуск сам останавливает его и запускает заново. Приложения, использующие Metal
+сами, от этого ничего не получают.
## Сборка из исходников
@@ -239,9 +243,9 @@ REST=1 userland/build.sh
`GL=1 REST=1 userland/build.sh` — образ, в котором оконный сервер рисует через OpenGL ES, а не программным
растеризатором CoreAnimation: за `EAGLContext` встаёт Mesa (прослойка — `userland/src/eagl.c`). На телефоне с
-параметрами ядра `adreno=21 adreno_skip=0x1c00 adreno_pause=0 adreno_keep=1` рисует сам Adreno: драйвер freedreno
-из Mesa говорит с ядром (`iokit/Kernel/RedwoodGPU.cpp`) на языке линуксового msm DRM. Без этих параметров и в
-QEMU — программный softpipe. После первого запуска с момента включения телефона добавляйте `adreno_zap=0`.
+параметром ядра `gpu=1` рисует сам Adreno: драйвер freedreno из Mesa говорит с ядром
+(`iokit/Kernel/RedwoodGPU.cpp`) на языке линуксового msm DRM. Без него и в QEMU библиотека не загружается, и
+образ ведёт себя как собранный без `GL=1` (`gl=1` — всё же загрузить, с программным softpipe: для отладки прослойки).
Mesa в репозитории нет: `tools/mk-mesa.sh` один раз скачивает и собирает её (нужны meson, ninja, bison, flex).
`GL=test RC_JOBS=rc.jobs.gltest` — только библиотека и `gl_test`: один треугольник на экран.
diff --git a/tools/mesa/freedreno-darwin.patch b/tools/mesa/freedreno-darwin.patch
index a7b3e3a..93353ca 100644
--- a/tools/mesa/freedreno-darwin.patch
+++ b/tools/mesa/freedreno-darwin.patch
@@ -134,6 +134,42 @@
subdir('drm')
endif
+--- a/src/gallium/drivers/freedreno/a6xx/fd6_draw.cc
++++ b/src/gallium/drivers/freedreno/a6xx/fd6_draw.cc
+@@ -445,6 +445,21 @@
+ DRAW == DRAW_INDIRECT_OP_INDIRECT_COUNT)
+ ctx->batch->barrier |= FD6_WAIT_FOR_ME;
+
++ /* Darwin on redwood: a draw that reads the framebuffer reads it through
++ * UCHE. Among primitives drawn with FLUSH_PER_OVERLAP the hardware sees
++ * to it that they read what the ones before them wrote, but it knows
++ * nothing of what was drawn before that mode was on: the first triangle
++ * to read the framebuffer after a draw that did not, read (with GMEM)
++ * pixels of another tile. Seen on a642l with CoreAnimation, which draws
++ * a label's shadow that way over icons drawn the ordinary way: the first
++ * triangle of each such quad was wrong, the second right. A CCU colour
++ * flush before the draw mends it, and so does a UCHE invalidate alone;
++ * the first such draw gets both, as a framebuffer barrier would give.
++ */
++ if (unlikely(emit.fs->fb_read) && !ctx->batch->prev_draw_read_fb)
++ ctx->batch->barrier |= FD6_FLUSH_CCU_COLOR | FD6_INVALIDATE_CACHE;
++ ctx->batch->prev_draw_read_fb = emit.fs->fb_read;
++
+ if (ctx->batch->barrier)
+ fd6_barrier_flush<CHIP>(ctx->batch);
+
+--- a/src/gallium/drivers/freedreno/freedreno_batch.h
++++ b/src/gallium/drivers/freedreno/freedreno_batch.h
+@@ -136,6 +136,9 @@
+ /* Driver specific barrier/flush flags: */
+ unsigned barrier;
+
++ /* The last draw emitted read the framebuffer (see fd6_draw.cc): */
++ bool prev_draw_read_fb;
++
+ /* A calculated "draw cost" value for the batch, which tries to
+ * estimate the bandwidth-per-sample of all the draws according
+ * to:
--- a/src/gallium/drivers/freedreno/freedreno_screen.c
+++ b/src/gallium/drivers/freedreno/freedreno_screen.c
@@ -25,7 +25,9 @@
diff --git a/tools/mk-mesa.sh b/tools/mk-mesa.sh
index 42a08b8..61b1612 100755
--- a/tools/mk-mesa.sh
+++ b/tools/mk-mesa.sh
@@ -88,5 +88,7 @@ llvm-strip -x -o out/libOSMesa.8.dylib $BUILD/src/gallium/targets/osmesa/libOSMe
install_name_tool -id /redwood/lib/libOSMesa.8.dylib out/libOSMesa.8.dylib
nm -gU out/libOSMesa.8.dylib | awk '$3 ~ /^_gl/ { print substr($3, 2) }' > out/exported-gl.txt
cp mesa-$VERSION/src/mapi/glapi/registry/gl.xml out/gl.xml
+# (userland/build.sh comes here again when this no longer matches)
+cat "$ROOT"/tools/mesa/*.patch "$ROOT"/tools/mesa/redwood-drm/* | sha256sum > out/built-from
echo "mk-mesa.sh: Mesa $VERSION ($DRIVERS): $B/out/libOSMesa.8.dylib, $(stat -c %s out/libOSMesa.8.dylib) bytes," \
"$(wc -l < out/exported-gl.txt) gl* functions"
diff --git a/userland/build.sh b/userland/build.sh
index d4be2bf..d717ddb 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -18,11 +18,12 @@
# rc.jobs.unlock, which also swipes the lock screen away (for the phone,
# where nothing else can touch the screen yet)
# GL=1 with an OpenGL ES implementation for the window server: Mesa
-# (tools/mk-mesa.sh fetches and builds it, once) behind src/eagl.c, as
-# lib/libOSMesa.8.dylib (15 MB) and lib/libredwood-gl.dylib. CoreAnimation
-# then draws with its OpenGL ES renderer instead of its software one --
-# by the phone's GPU where the kernel keeps it on (boot-arg adreno_keep=1),
-# by Mesa's software driver elsewhere.
+# (tools/mk-mesa.sh fetches and builds it) behind src/eagl.c, as
+# lib/libOSMesa.8.dylib (15 MB) and lib/libredwood-gl.dylib. Where the
+# kernel has started the phone's GPU, CoreAnimation then draws with its
+# OpenGL ES renderer, by that GPU (boot-arg gpu=1); anywhere else -- QEMU,
+# no boot-arg, no firmware in ../fw-gpu -- the library is not even loaded
+# and nothing changes (src/inject.c, opengl_es()).
# GL=test: only the library and bin/gl_test (a triangle, src/gl_test.c;
# RC_JOBS=rc.jobs.gltest runs it); the window server stays as it is.
# system.packfs the system image, the root filesystem (second RAM disk, /dev/md1): the part of
@@ -104,8 +105,10 @@ if [ -d $IOS/rootfs/usr/lib ]; then
-o obj/libredwood-sb.dylib src/inject_sb.c
if [ -n "$GL" ]; then
# the OpenGL ES library, and the table of functions that hands CoreAnimation's calls to it
+ # (Mesa says beside the library what it was built from: one from other patches is built again)
M=../xnu-deps/build/mesa/out
- [ -f $M/libOSMesa.8.dylib ] || ../tools/mk-mesa.sh
+ [ "$(cat $M/built-from 2>/dev/null)" = "$(cat ../tools/mesa/*.patch ../tools/mesa/redwood-drm/* | sha256sum)" ] ||
+ ../tools/mk-mesa.sh
./mkeagl.py src/eagl_slots.txt $M/gl.xml $M/exported-gl.txt src/eagl.c > obj/eagl_gen.h
$DYN -dynamiclib -install_name /redwood/lib/libredwood-gl.dylib -Iobj -framework CoreFoundation \
-framework IOKit -framework IOSurface -lobjc $M/libOSMesa.8.dylib -o obj/libredwood-gl.dylib \
diff --git a/userland/src/eagl.c b/userland/src/eagl.c
index bfc5eb5..c8bd343 100644
--- a/userland/src/eagl.c
+++ b/userland/src/eagl.c
@@ -47,7 +47,7 @@
* shader, glshow=TEXTURE puts that texture over the corner of the picture, glplain=0 leaves the
* draws without a program alone, glcopy=1 copies every IOSurface as if the library could not
* share one, glwait=1 waits for the GPU at the end of every frame and glwait=0 never (see
- * wait_for_frames), glfetch=1 lets CoreAnimation have EXT_shader_framebuffer_fetch (see
+ * wait_for_frames), glfetch=0 keeps EXT_shader_framebuffer_fetch from CoreAnimation (see
* fetch_offered), glenv=NAME=VALUE puts that into the environment for the library to find
* (its own switches: FD_MESA_DEBUG=sysmem, say).
*/
@@ -268,16 +268,16 @@ static int wait_for_frames = 1;
* EXT_shader_framebuffer_fetch -- a fragment shader reads the pixel it is about to write -- is
* what CoreAnimation draws a number of things with where the library offers it: the shadows
* under the home screen's labels, when they are of the kind that darkens only what is light,
- * are quads that read the picture and write it back. Mesa's driver for this GPU has the
- * extension, and with it the first triangle of each such quad came out with pixels from
- * somewhere else whenever the picture was drawn in tiles: fragments of other icons under the
- * icons of the first and the fourth row. (Flushing overlapping primitives, a constant layer and
- * a constant sample for the read made no difference; drawn straight into memory the shadows
- * were right and the Search field went white.) So the extension is not passed on: CoreAnimation
- * then does the same with what OpenGL ES always has, and the picture is right. Boot-arg
- * glfetch=1 passes it on, for whoever wants to see or mend that.
+ * are quads that read the picture and write it back, and a colour matrix over what is there
+ * (the Search field's text) is one draw instead of a copy and a draw. Without the extension
+ * CoreAnimation does the same with what OpenGL ES always has, at four times the submissions
+ * for a home screen. (Mesa's driver for this GPU drew the first triangle of each such quad
+ * with pixels of another tile, fragments of other icons under the labels, until it was given a
+ * flush before the first draw that reads the picture after one that does not:
+ * tools/mesa/freedreno-darwin.patch, fd6_draw.cc.) Boot-arg glfetch=0 keeps the extension from
+ * CoreAnimation, to see the difference.
*/
-static int fetch_offered;
+static int fetch_offered = 1;
static const char *eagl_slot_name(unsigned offset);
@@ -2063,7 +2063,7 @@ install(void)
}
trace_lit = strstr(arguments, "gltrace_lit=1") != NULL;
trace_look = strstr(arguments, "gltrace_look=1") != NULL;
- fetch_offered = strstr(arguments, "glfetch=1") != NULL;
+ fetch_offered = strstr(arguments, "glfetch=0") == NULL;
if ((argument = strstr(arguments, "gltrace_place=")) != NULL) {
char *end = (char *)argument + 14;
diff --git a/userland/src/inject.c b/userland/src/inject.c
index cadec66..f579a19 100644
--- a/userland/src/inject.c
+++ b/userland/src/inject.c
@@ -26,6 +26,7 @@
* every one is checked against what is expected to be there before it is touched.
*/
#include <CoreFoundation/CoreFoundation.h>
+#include <IOKit/IOKitLib.h>
#include <dispatch/dispatch.h>
#include <dlfcn.h>
#include <errno.h>
@@ -38,6 +39,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/sysctl.h>
#include <unistd.h>
#include "redwood_input.h"
@@ -210,6 +212,7 @@ my_render_update(void *server, void *update, unsigned *flags)
*/
#define VT_GLES_CONTEXT 0x1d5b3b540UL /* vtable for CA::OGL::GLESContext */
+static int gl_loaded; /* CoreAnimation draws with OpenGL ES (opengl_es() below) */
static int (*orig_function_supported)(void *context);
static int
@@ -245,7 +248,7 @@ window_server_fixes(void)
orig_renderer = replace_virtual("renderer", VSLOT(VT_EAGL_SERVER, 0x1a0), 0x1882e2548UL, my_renderer);
orig_render_update = replace_virtual("render_update", VSLOT(VT_EAGL_SERVER, 0x178), 0x18835770cUL,
my_render_update);
- if (access(REDWOOD_GL, R_OK) == 0) {
+ if (gl_loaded) {
orig_function_supported = replace_virtual("function_supported", VSLOT(VT_GLES_CONTEXT, 0x378), 0x1884a9308UL,
my_function_supported);
}
@@ -684,6 +687,56 @@ container_manager_fixes(void)
/* ---------------------------------------------------------------------------------------------- */
+/*
+ * An OpenGL ES implementation for CoreAnimation (src/eagl.c, Mesa behind it): loaded, it puts
+ * itself behind EAGLContext, and the renderer the server then gets is the OpenGL ES one. That
+ * is worth it where a GPU does the drawing, and only there: on the phone, when the kernel has
+ * started the GPU and keeps it (boot-arg gpu=1), which the service RedwoodGPU says (it is there
+ * before the first program runs, or not at all). Everywhere else -- QEMU, a run without the
+ * boot-arg, a phone without the GPU's firmware in the image, a GPU that did not start --
+ * nothing is loaded, and CoreAnimation draws with its own software renderer as in an image
+ * without the library.
+ * Boot-arg gl=0: not even with a GPU; gl=1: also without one, by Mesa's software driver (slow;
+ * for working on eagl.c in QEMU).
+ */
+static void
+opengl_es(void)
+{
+ char arguments[1024] = "";
+ size_t size = sizeof(arguments) - 1;
+ const char *argument;
+ io_service_t gpu;
+ int wanted = -1, told = 0;
+
+ if (access(REDWOOD_GL, R_OK) != 0) {
+ return; /* (an image built without it) */
+ }
+ if (sysctlbyname("kern.bootargs", arguments, &size, NULL, 0) == 0) {
+ for (argument = arguments; (argument = strstr(argument, "gl=")) != NULL; argument += 3) {
+ if (argument == arguments || argument[-1] == ' ') {
+ wanted = argument[3] != '0';
+ told = 1;
+ }
+ }
+ }
+ if (wanted < 0) {
+ gpu = IOServiceGetMatchingService(0, IOServiceMatching("RedwoodGPU"));
+ wanted = gpu != 0;
+ if (gpu != 0) {
+ IOObjectRelease(gpu);
+ }
+ }
+ if (!wanted) {
+ say("redwood: %s: CoreAnimation keeps its software renderer\n", told ? "gl=0" : "no GPU to draw with");
+ return;
+ }
+ if (dlopen(REDWOOD_GL, RTLD_NOW) == NULL) {
+ say("redwood: %s: %s\n", REDWOOD_GL, dlerror());
+ return;
+ }
+ gl_loaded = 1;
+}
+
__attribute__((constructor))
static void
redwood_init(void)
@@ -697,16 +750,7 @@ redwood_init(void)
}
slide = (uintptr_t)cache - CACHE_BASE;
if (strcmp(name, "backboardd") == 0) {
- /*
- * An OpenGL ES implementation for CoreAnimation, where the image has one (build.sh GL=1;
- * src/eagl.c): it puts itself behind EAGLContext as it is loaded, and the renderer the
- * server then gets is the OpenGL ES one.
- */
- if (access(REDWOOD_GL, R_OK) == 0) {
- if (dlopen(REDWOOD_GL, RTLD_NOW) == NULL) {
- say("redwood: %s: %s\n", REDWOOD_GL, dlerror());
- }
- }
+ opengl_es();
window_server_fixes();
/*
* brightness_fixes() is not used for now: with it backboardd no longer took our touch